diff options
Diffstat (limited to 'Source/WebCore')
342 files changed, 3922 insertions, 35758 deletions
diff --git a/Source/WebCore/ChangeLog b/Source/WebCore/ChangeLog index 3d3589e67..c4321a62b 100644 --- a/Source/WebCore/ChangeLog +++ b/Source/WebCore/ChangeLog @@ -1,3 +1,1731 @@ +2012-09-24 Andrey Kosyakov <caseq@chromium.org> + + Unreviewed follow-up to r129336 -- fixed closure compiler warnings. + + * inspector/front-end/HAREntry.js: + * inspector/front-end/TimelineModel.js: + +2012-09-24 Andrey Adaikin <aandrey@chromium.org> + + Web Inspector: [TextEditor] Line numbers out of sync after closing breakpoint condition editor + https://bugs.webkit.org/show_bug.cgi?id=96510 + + Reviewed by Vsevolod Vlasov. + + Sync line heights on adding/removing decorations. + + * inspector/front-end/DefaultTextEditor.js: + (WebInspector.TextEditorGutterChunk): + (WebInspector.TextEditorGutterChunk.prototype.addDecoration): + (WebInspector.TextEditorGutterChunk.prototype.removeDecoration): + (WebInspector.TextEditorGutterChunk.prototype.set expanded): + (WebInspector.TextEditorGutterChunk.prototype.get height): + (WebInspector.TextEditorGutterChunk.prototype._createRow): + (WebInspector.TextEditorMainChunk.prototype.addDecoration): + (WebInspector.TextEditorMainChunk.prototype.removeDecoration): + (WebInspector.TextEditorMainChunk.prototype.removeAllDecorations): + +2012-09-21 Andrey Kosyakov <caseq@chromium.org> + + Web Inspector: support saving HAR with resources content + https://bugs.webkit.org/show_bug.cgi?id=97341 + + Reviewed by Vsevolod Vlasov. + + - add WebInspector.HARWriter that writes HAR with content to a stream; + - replace Save all as HAR with Save all with Content as HAR in network's panel context menu; + - remove entries for copying/saving of individual request items to reduce clutter in context menu; + - a drive-by fix of an exception when invoking context menu not on a network item; + + Test: http/tests/inspector/network/har-content.html + + * English.lproj/localizedStrings.js: + * inspector/front-end/FileUtils.js: + * inspector/front-end/HAREntry.js: + (WebInspector.HAREntry.prototype._buildPostData): + (WebInspector.HARLog.prototype.build): + (WebInspector.HARLog.prototype._creator): + (WebInspector.HARWriter): + (WebInspector.HARWriter.prototype.write): + (WebInspector.HARWriter.prototype._onContentAvailable): + (WebInspector.HARWriter.prototype._beginWrite): + (WebInspector.HARWriter.prototype._writeNextChunk): + * inspector/front-end/NetworkPanel.js: + (WebInspector.NetworkLogView.prototype.get statusBarItems): + (WebInspector.NetworkLogView.prototype._createStatusBarItems): + (WebInspector.NetworkLogView.prototype._contextMenu): + (WebInspector.NetworkLogView.prototype._exportAll.openCallback): + (WebInspector.NetworkLogView.prototype._exportAll): + +2012-09-24 Nico Weber <thakis@chromium.org> + + [chromium] Remove BitLockerSkia. It's apparently not used. + https://bugs.webkit.org/show_bug.cgi?id=97434 + + Reviewed by Kent Tamura. + + * platform/graphics/skia/BitLockerSkia.cpp: Removed. + * platform/graphics/skia/BitLockerSkia.h: Removed. + +2012-09-24 Matt Falkenhagen <falken@chromium.org> + + Skeleton implementation of dialog.showModal() + https://bugs.webkit.org/show_bug.cgi?id=97425 + + Reviewed by Kent Tamura. + + This adds a basic implementation of showModal(), so it later can be + used to test the top layer, once it is implemented. The main features + of showModal(), modality and the top layer, are not yet implemented. + + Test: fast/dom/HTMLDialogElement/dialog-show-modal.html + + * html/HTMLDialogElement.cpp: + (WebCore::HTMLDialogElement::showModal): The same as show(), but throws an error in the cases specified in the spec. + (WebCore): + * html/HTMLDialogElement.h: + (HTMLDialogElement): + * html/HTMLDialogElement.idl: + +2012-09-24 Ryuan Choi <ryuan.choi@samsung.com> + + [EFL] Regression after r129328 + https://bugs.webkit.org/show_bug.cgi?id=97429 + + Unreviewed, rolling out r129328. + + * platform/efl/RenderThemeEfl.cpp: + (WebCore::RenderTheme::themeForPage): + +2012-09-23 Ryuan Choi <ryuan.choi@samsung.com> + + [EFL] Duplicated RenderThemeEfl creation for same page + https://bugs.webkit.org/show_bug.cgi?id=88391 + + Reviewed by Gyuyoung Kim. + + Other ports return one or two RenderTheme regardless of page. + But, WebKit/Efl can create different theme for each page and + themeForPage creates new RenderTheme whenever it is called with page. + So more than one RenderTheme can be created for a page. + + This patches checks whether page already has RenderTheme not to create new + RenderTheme for same page. + + * platform/efl/RenderThemeEfl.cpp: + (WebCore::RenderTheme::themeForPage): + +2012-09-23 Keishi Hattori <keishi@webkit.org> + + Add suggestionPicker to CalendarPicker + https://bugs.webkit.org/show_bug.cgi?id=97201 + + Reviewed by Kent Tamura. + + This adds the suggestionPicker to CalendarPicker. It is not available yet as a datalist UI but it can be used inside ManualTests/forms/calendar-picker.html. + + No new tests. Suggestion Picker can be tested in ManualTests/forms/calendar-picker.html. + + * Resources/pagepopups/calendarPicker.js: + (initialize): + (openSuggestionPicker): + * Resources/pagepopups/pickerCommon.js: + (enclosingNodeOrSelfWithClass): + * Resources/pagepopups/suggestionPicker.css: Added. + (.suggestion-list): + (.suggestion-list-entry): + (.suggestion-list-entry:focus): + (.suggestion-list-entry:focus .label): + (.suggestion-list-entry .content): + (.suggestion-list-entry .title): + (.suggestion-list-entry .label): + (.measuring-width .suggestion-list-entry .label): + (.suggestion-list .separator): + * Resources/pagepopups/suggestionPicker.js: Added. + (SuggestionPicker): + (SuggestionPicker.validateConfig): + (SuggestionPicker.prototype.cleanup): + (SuggestionPicker.prototype._setColors): Creates css rules that sets highlight colors. + (SuggestionPicker.prototype._createSuggestionEntryElement): Creates an entry that when selected submits the value. + (SuggestionPicker.prototype._createActionEntryElement): Creates an entry that causes an action. (e.x. "Other...") + (SuggestionPicker.prototype._measureMaxContentWidth): Temporarily left align everything to measure the width. + (SuggestionPicker.prototype._fixWindowSize): + (SuggestionPicker.prototype._layout): + (SuggestionPicker.prototype.selectEntry): + (SuggestionPicker.prototype._handleEntryClick): + (SuggestionPicker.prototype._findFirstVisibleEntry): + (SuggestionPicker.prototype._findLastVisibleEntry): + (SuggestionPicker.prototype._handleBodyKeyDown): + (SuggestionPicker.prototype._handleEntryMouseOver): + (SuggestionPicker.prototype._handleMouseOut): + * WebCore.gyp/WebCore.gyp: + +2012-09-23 Andreas Kling <kling@webkit.org> + + REGRESSION(r128239): Mutable ElementAttributeData leak their Attribute vectors. + <http://webkit.org/b/97423> + + Reviewed by Anders Carlsson. + + r128239 added a WTF::deleteOwnedPtr() override for ElementAttributeData*, but ElementAttributeData is + a ref-counted object. Fixed this by overriding deref() instead to call the appropriate subclass destructor. + + * dom/ElementAttributeData.h: + (WebCore::ElementAttributeData::deref): + +2012-09-23 Byungwoo Lee <bw80.lee@gmail.com> + + Fix build warnings : -Wunused-parameter, -Wparentheses, -Wuninitialized. + https://bugs.webkit.org/show_bug.cgi?id=97306 + + Reviewed by Benjamin Poulain. + + Fix build warning about -Wunused-parameter on ImageBufferCairo.cpp, + ImageDecoder.h by using ASSERT_UNUSED() macro. + + * platform/graphics/cairo/ImageBufferCairo.cpp: + (WebCore::encodeImage): + * platform/image-decoders/ImageDecoder.h: + (WebCore::ImageDecoder::rgbColorProfile): + (WebCore::ImageDecoder::inputDeviceColorProfile): + +2012-09-23 Andreas Kling <kling@webkit.org> + + Enable ElementAttributeData sharing for non-HTML elements. + <http://webkit.org/b/97413> + + Reviewed by Anders Carlsson. + + Use the whole qualified tag name when creating the ElementAttributeData cache key + instead of just the localName(). This allows sharing and caching of attribute data + for non-HTML elements and makes the code a little cleaner. + + * dom/Element.cpp: + (WebCore::Element::parserSetAttributes): + + Enable the ElementAttributeData sharing path for non-HTML elements. + + * dom/ElementAttributeData.h: + + Make immutableAttributeArray() public so Document can call it instead of getting + the raw data address from a const_cast'ed attributeItem(0). + + * dom/Document.cpp: + (WebCore::ImmutableAttributeDataCacheKey::ImmutableAttributeDataCacheKey): + (WebCore::ImmutableAttributeDataCacheKey::operator!=): + (WebCore::ImmutableAttributeDataCacheKey::hash): + (ImmutableAttributeDataCacheKey): + (WebCore::ImmutableAttributeDataCacheEntry::ImmutableAttributeDataCacheEntry): + (ImmutableAttributeDataCacheEntry): + (WebCore::Document::cachedImmutableAttributeData): + + Let the immutable attribute data cache use a QualifiedName/attributes key + instead of the AtomicString/attributes we were using before. We still grab the + existingHash() from the QualifiedName::localName() and use that for the actual + HashMap key. + +2012-09-23 Mike West <mkwst@chromium.org> + + Measure the usage of the "X-WebKit-CSP" header in the hopes of dropping the prefix completely. + https://bugs.webkit.org/show_bug.cgi?id=97408 + + Reviewed by Adam Barth. + + We plan on landing the unprefixed header in webkit.org/b/96765 once the + spec moves to CR. Though we plan to use it for experimentation in the + near future, we'll want to drop the prefixed header completely at some + point in the future. Starting to measure its usage now will give us a + good baseline when we start contemplating that decision. + + No new functionality, so no new tests. + + * page/ContentSecurityPolicy.cpp: + (WebCore::ContentSecurityPolicy::didReceiveHeader): + * page/FeatureObserver.h: + +2012-09-22 Dominic Mazzoni <dmazzoni@google.com> + + AX: Layout tests would be easier to write if AccessibilityController could find an element by id + https://bugs.webkit.org/show_bug.cgi?id=97301 + + Reviewed by Chris Fleizach. + + Add a method to get the DOM "id" attribute from an accessible object, only for layout tests. + + Makes existing test more cross-platform: + Tests: accessibility/aria-hidden-with-elements.html + + * accessibility/mac/WebAccessibilityObjectWrapper.mm: + (-[WebAccessibilityObjectWrapper accessibilityAttributeValue:]): + +2012-09-22 Thierry Reding <thierry.reding@avionic-design.de> + + [GTK] Build is broken with GLib Unicode backend + https://bugs.webkit.org/show_bug.cgi?id=97308. + + Reviewed by Carlos Garcia Campos. + + The TextBreakIteratorGtk implementation uses ubrk_close() to delete + the iterator. However that function is ICU specific and not declared + when using the GLib backend. Instead the iterator can simply be freed + using the delete operator. + + This commit is based on work by Martin Schlemmer who posted a fix for + this here: + + http://permalink.gmane.org/gmane.os.opendarwin.webkit.gtk/1210 + + No new tests. + + * platform/text/gtk/TextBreakIteratorGtk.cpp: + (WebCore::NonSharedCharacterBreakIterator::~NonSharedCharacterBreakIterator): + Free iterator using delete instead of ubrk_close(). + +2012-09-21 Ami Fischman <fischman@chromium.org> + + HTMLMediaElement isn't garbage collected between document reloads + https://bugs.webkit.org/show_bug.cgi?id=97020 + + Reviewed by Eric Carlson. + + JS-created (as opposed to DOM-created) Audio nodes never got collected, because they + appear to always hasPendingActivity(), because m_playing is never set to false. + + Manual test added: ManualTests/audio-freed-during-reload.html + + * html/HTMLMediaElement.cpp: + (WebCore::HTMLMediaElement::stop): set m_playing = false; explicitly. + +2012-09-21 Simon Fraser <simon.fraser@apple.com> + + RenderMarquee causes ASSERTION FAILED: enclosingIntRect(rendererMappedResult) == enclosingIntRect(FloatQuad(result).boundingBox()) : WebCore::FloatRect WebCore::RenderGeometryMap::absoluteRect(const WebCore::FloatRect &) const + https://bugs.webkit.org/show_bug.cgi?id=92464 + + Reviewed by Sam Weinig. + + Marquees could cause an updateCompositingLayersAfterScroll() to be called when + we're in the middle of updating layer positions. updateCompositingLayersAfterScroll() + does a full RenderLayer tree walk, but its use of RenderGeomeryMap reveals that + it's using layers whose positions haven't been updated yet. + + Fix by avoiding the updateCompositingLayersAfterScroll() if we're in the process + of updating a marquee when updating layer positions. We'll do a compositing update + soon anyway. + + Tested by fast/events/tabindex-focus-blur-all.html + + * rendering/RenderLayer.cpp: + (WebCore::RenderLayer::RenderLayer): + (WebCore::RenderLayer::updateLayerPositions): + (WebCore::RenderLayer::updateLayerPositionsAfterScroll): + (WebCore::RenderLayer::scrollTo): + * rendering/RenderLayer.h: + (RenderLayer): + +2012-09-21 Adam Klein <adamk@chromium.org> + + Remove bogus assertions from ChildListMutationScope + https://bugs.webkit.org/show_bug.cgi?id=97372 + + Reviewed by Ryosuke Niwa. + + Some asserts (and their accompanying comment) were trying to enforce + proper usage of ChildListMutationScope from WebCore, but in the + presence of MutationEvents they could fail due to arbitrary script + execution. + + This change gets rid of those asserts and adds tests exercising + the (pre-existing) codepaths for handling these out-of-order cases. + Without this patch, these tests ASSERT in debug builds. + + Tests: fast/mutation/added-out-of-order.html + fast/mutation/removed-out-of-order.html + + * dom/ChildListMutationScope.cpp: + (WebCore::ChildListMutationAccumulator::childAdded): + (WebCore::ChildListMutationAccumulator::willRemoveChild): + * dom/ChildListMutationScope.h: + (WebCore): + +2012-09-21 Dan Bernstein <mitz@apple.com> + + REGRESSION (r129176): Incorrect line breaking when kerning occurs between a space and the following character + https://bugs.webkit.org/show_bug.cgi?id=97377 + + Reviewed by Enrica Casucci. + + Test: fast/text/kerning-with-TextLayout.html + + When kerning is enabled, the last character in a word may have its advance shortened because + of its trailing space. To account for that, words are measured along with the trailing space, + then the width of a space is subtracted from the result. This doesn’t work when the trailing + space itself has its advance shortened due to the character following it, which can happen + when using the TextLayout optimization. However, when the optimization is used, the advance + of the last character of the word is already adjusted for the trailing space, so there is no + need to measure with that space and subtract its advance. + + * rendering/RenderBlockLineLayout.cpp: + (WebCore::RenderBlock::LineBreaker::nextLineBreak): Changed to not use the trailingSpaceWidth + mechanism when TextLayout is being used. + +2012-09-21 Adam Klein <adamk@chromium.org> + + Simplify and optimize ChildListMutationScope + https://bugs.webkit.org/show_bug.cgi?id=97352 + + Reviewed by Ryosuke Niwa. + + ChildListMutationScope is one of the most complicated bits of + MutationObserver implementation. This patch aims to simplify it for + clarity and improve its performance (mostly by just doing less). + + The big change is to remove the MutationAccumulatorRouter class, + replacing it with lifetime-management logic in ChildListMutationAccumulator + ChildListMutationScope is expected to call getOrCreate() in + its constructor, and each scope holds a RefPtr to the accumulator. + When the last scope holding such a RefPtr is destroyed, + ChildListMutationAccumulator's destructor enqueues the accumulated record. + + This greatly reduces the number of lines of code, and condenses + two HashMaps into one. It also reduces hash lookups, which now + occur only on scope creation and when the refcount for a given + accumulator reaches 0 (previously, each childAdded and willRemoveChild + call could result in two hash lookups each). + + There are some minor changes as well: the ChildListMutationAccumulator::clear() + method is gone, as it was doing more work than necessary; + DEFINE_STATIC_LOCAL is now used instead of hand-rolled static-management + code; ChildListMutationAccumulator::m_lastAdded is no longer a RefPtr, since it + always points at a Node that's already being ref'd by the accumulator. + Also various minor syntactic cleanups. + + No new tests, no change in behavior. + + * dom/ChildListMutationScope.cpp: + (WebCore::accumulatorMap): Reduced two maps to one, and manage its lifetime with DEFINE_STATIC_LOCAL. + (WebCore::ChildListMutationAccumulator::ChildListMutationAccumulator): Remove unnecessary call to clear() (which itself has been removed). + (WebCore::ChildListMutationAccumulator::~ChildListMutationAccumulator): Enqueue record if not empty at destruction, and have the accumulator + remove itself from the map. + (WebCore::ChildListMutationAccumulator::getOrCreate): Replaces half of MutationAccumulatorRouter's job. + (WebCore::ChildListMutationAccumulator::childAdded): Minor RefPtr usage improvements. + (WebCore::ChildListMutationAccumulator::isRemovedNodeInOrder): Simplify RefPtr syntax. + (WebCore::ChildListMutationAccumulator::willRemoveChild): Minor RefPtr usage improvements. + (WebCore::ChildListMutationAccumulator::enqueueMutationRecord): Replace call to clear() with clearing m_lastAdded, + since it's the only bit not cleared by the MutationRecord creation call. Also remove + isEmpty check and replace with asserts now that it's a private method. + (WebCore::ChildListMutationAccumulator::isEmpty): Added more assertions about emptiness. + * dom/ChildListMutationScope.h: + (WebCore): + (ChildListMutationAccumulator): Extract the inner class to make everything easier to read. + (WebCore::ChildListMutationScope::ChildListMutationScope): Store m_accumulator rather than m_target. + (WebCore::ChildListMutationScope::~ChildListMutationScope): ditto + (WebCore::ChildListMutationScope::childAdded): ditto + (WebCore::ChildListMutationScope::willRemoveChild): ditto + (ChildListMutationScope): + * html/HTMLElement.cpp: Remove unused ChildListMutationScope.h #include. + +2012-09-21 Chris Rogers <crogers@google.com> + + BiquadFilterNode must take audio-rate parameter changes into account + https://bugs.webkit.org/show_bug.cgi?id=97369 + + Reviewed by Kenneth Russell. + + BiquadFilterNode is currently ignoring any timeline or audio-rate changes to its parameters. + We now check if any of its parameters have timeline or audio-rate changes and, if so, take + them into account. Otherwise, we use ordinary parameter smoothing/de-zippering which is + the case when the parameters are adjusted, for example, from a knob or slider in the UI. + + * Modules/webaudio/BiquadDSPKernel.cpp: + (WebCore::BiquadDSPKernel::updateCoefficientsIfNecessary): + * Modules/webaudio/BiquadProcessor.cpp: + (WebCore::BiquadProcessor::checkForDirtyCoefficients): + * Modules/webaudio/BiquadProcessor.h: + (WebCore::BiquadProcessor::hasSampleAccurateValues): + (BiquadProcessor): + +2012-09-21 Brandon Jones <bajones@google.com> + + Add support for OES_vertex_array_object in chromium + https://bugs.webkit.org/show_bug.cgi?id=96578 + + Reviewed by Kenneth Russell. + + Adding basic reference counting to WebGLBuffer objects to satisfy spec requirements + for the OES_vertex_array_object extension. Added code to allow calls to the + OES_vertex_array_object extension to interface properly with the chromium WebGL + implementation. + + Test: fast/canvas/webgl/oes-vertex-array-object.html + + * html/canvas/WebGLRenderingContext.cpp: + (WebCore): + (WebCore::WebGLRenderingContext::deleteBuffer): + (WebCore::WebGLRenderingContext::vertexAttribPointer): + * html/canvas/WebGLVertexArrayObjectOES.cpp: + (WebCore::WebGLVertexArrayObjectOES::setElementArrayBuffer): + (WebCore): + * html/canvas/WebGLVertexArrayObjectOES.h: + (WebGLVertexArrayObjectOES): + (WebCore::WebGLVertexArrayObjectOES::getVertexAttribStateSize): + * platform/chromium/support/Extensions3DChromium.cpp: + (WebCore::Extensions3DChromium::createVertexArrayOES): + (WebCore::Extensions3DChromium::deleteVertexArrayOES): + (WebCore::Extensions3DChromium::isVertexArrayOES): + (WebCore::Extensions3DChromium::bindVertexArrayOES): + +2012-09-21 Kenichi Ishibashi <bashi@chromium.org> + + [Chromium] Use OpenTypeVerticalData on Linux + https://bugs.webkit.org/show_bug.cgi?id=97277 + + Reviewed by Tony Chang. + + Remove HarfBuzz dependency from GlyphPageTreeNodeSkia. Use OpenTypeVerticalData instead. + + No new tests. Rebaselined existing tests. + + * WebCore.gyp/WebCore.gyp: Added OpenTypeTypes.h and OpenTypeVerticalData.(cpp|h) for linux and android. + * platform/graphics/FontCache.cpp: + Inserted a space between > and > in typedef of FontVerticalDataCache so that making some compilers happy. + (WebCore): + * platform/graphics/SimpleFontData.h: + (SimpleFontData): Moved declaration of m_verticalData to avoid compile warnings. + * platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp: + (WebCore): + (WebCore::FontPlatformData::verticalData): Added. + (WebCore::FontPlatformData::openTypeTable): Added. + * platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h: + (WebCore): + (FontPlatformData): + * platform/graphics/skia/GlyphPageTreeNodeSkia.cpp: Removed substituteWithVerticalGlyphs(). + (WebCore::GlyphPage::fill): + +2012-09-21 Jeremy Apthorp <jeremya@chromium.org> + + Crash in WebCore::Document::fullScreenChangeDelayTimerFired + https://bugs.webkit.org/show_bug.cgi?id=97367 + + Reviewed by Abhishek Arya. + + The document could be destroyed during the processing of the + fullscreenchange event, if the document was destroyed as a result of + one of the dispatchEvent calls. + + This bug isn't reliably reproducible, so no new tests. + + * dom/Document.cpp: + (WebCore::Document::fullScreenChangeDelayTimerFired): + +2012-09-21 Pratik Solanki <psolanki@apple.com> + + No need to pass order file for WebCoreTestSupport build + https://bugs.webkit.org/show_bug.cgi?id=97363 + + Reviewed by David Kilzer. + + No new tests because no functional change. + + * Configurations/WebCoreTestSupport.xcconfig: + +2012-09-21 Chris Rogers <crogers@google.com> + + Add Web Audio support for deprecated/legacy APIs + https://bugs.webkit.org/show_bug.cgi?id=97050 + + Reviewed by Eric Carlson. + + The Web Audio API specification has undergone much review and some small API changes + have been made (mostly naming-related changes). This patch adds an ENABLE_LEGACY_WEB_AUDIO + build option to allow ports to support the old names. + + Tests changed: + audiobuffersource-playbackrate.html + audiobuffersource.html + note-grain-on-testing.js + oscillator-testing.js + + * Configurations/FeatureDefines.xcconfig: + * GNUmakefile.features.am: + * Modules/webaudio/AudioBufferSourceNode.cpp: + (WebCore::AudioBufferSourceNode::startGrain): + (WebCore): + (WebCore::AudioBufferSourceNode::noteGrainOn): + * Modules/webaudio/AudioBufferSourceNode.h: + (AudioBufferSourceNode): + * Modules/webaudio/AudioBufferSourceNode.idl: + * Modules/webaudio/AudioScheduledSourceNode.cpp: + (WebCore::AudioScheduledSourceNode::start): + (WebCore::AudioScheduledSourceNode::stop): + (WebCore): + (WebCore::AudioScheduledSourceNode::noteOn): + (WebCore::AudioScheduledSourceNode::noteOff): + * Modules/webaudio/AudioScheduledSourceNode.h: + * Modules/webaudio/Oscillator.idl: + * page/FeatureObserver.h: + +2012-09-21 Mark Pilgrim <pilgrim@chromium.org> + + [Chromium] remove getFontFamilyForCharacters from PlatformSupport + https://bugs.webkit.org/show_bug.cgi?id=96282 + + Reviewed by Tony Chang. + + Migrating away from PlatformSupport. getFontFamilyForCharacters is + moved to FontCache.h and overridden by the two platforms that + need it (Chromium Linux and Blackberry). New files for the overrides. + Part of a larger refactoring series. See tracking bug 82948. + + * PlatformBlackBerry.cmake: + * WebCore.gypi: + * platform/chromium/PlatformSupport.h: + (PlatformSupport): + * platform/graphics/FontCache.h: + (SimpleFontFamily): + (FontCache): + * platform/graphics/blackberry/FontCacheBlackberry.cpp: Added. + (WebCore): + (WebCore::FontCache::getFontFamilyForCharacters): + * platform/graphics/blackberry/skia/PlatformSupport.cpp: + (WebCore): + * platform/graphics/blackberry/skia/PlatformSupport.h: + (PlatformSupport): + * platform/graphics/chromium/FontCacheAndroid.cpp: + (WebCore::FontCache::getFontDataForCharacters): + * platform/graphics/chromium/FontCacheChromiumLinux.cpp: Added. + (WebCore): + (WebCore::FontCache::getFontFamilyForCharacters): + * platform/graphics/skia/FontCacheSkia.cpp: + (WebCore::FontCache::getFontDataForCharacters): + +2012-09-21 Chris Fleizach <cfleizach@apple.com> + + AX: WebKit exposes incorrect bounds for embedded SVG in HTML + https://bugs.webkit.org/show_bug.cgi?id=96168 + + Reviewed by Eric Seidel. + + Override absoluteFocusRingQuads() for SVG objects because the default + implementation relies on addFocusRingRects(). In addFocusRingRects(), SVG + objects adds local positions for its rects instead of absolute positions. + + Test: accessibility/svg-bounds.html + + * rendering/RenderObject.h: + (RenderObject): + * rendering/svg/RenderSVGModelObject.cpp: + (WebCore): + (WebCore::RenderSVGModelObject::absoluteFocusRingQuads): + * rendering/svg/RenderSVGModelObject.h: + (RenderSVGModelObject): + +2012-09-21 Lianghui Chen <liachen@rim.com> + + [BlackBerry] Really fix bug 95488 that user can get the authentication challenge dialog while the other tab has focus. + https://bugs.webkit.org/show_bug.cgi?id=97348 + Internal PR: 186597. + + Internally reviewed by Yong Li, Joe Mason. + Reviewed by Yong Li. + + Add a singleton AuthenticationChallengeManager to manage authentication + challenge dialog. It does following things: + Record page creation/deletion, so it knows what page is present or not. + Record page visibility change so it knows when to display a dialog or not. + Accept authentication challenge, and decide whether to postpone the + challenge dialog based on whether there is active authentication challenge + dialog already and whether its page is visible or not. + When a challenge result comes back, notify the result to all clients + authenticating for the same protection space, and then start the next + authentication challenge from the same page, if there is one. + When a page becomes visible, start the first authentication challenge + dialog that has been blocked before. + + And to support this new AuthenticationChallengeManager, and making the + challenge really asynchronous, NetworkJob has been updated to support + the concept of "freeze", which means buffering all network loading status + change but don't send them to NetworkJob clients. + This is necessary when authentication challenge is asynchronous, as the + previous network loading status will likely come before user make any + decision. + + No new tests for platform specific internal change. + + * PlatformBlackBerry.cmake: + * platform/blackberry/AuthenticationChallengeManager.cpp: Added. + (WebCore): + (ChallengeInfo): + (WebCore::ChallengeInfo::ChallengeInfo): + (AuthenticationChallengeManagerPrivate): + (WebCore::AuthenticationChallengeManagerPrivate::AuthenticationChallengeManagerPrivate): + (WebCore::AuthenticationChallengeManagerPrivate::resumeAuthenticationChallenge): + (WebCore::AuthenticationChallengeManagerPrivate::startAuthenticationChallenge): + (WebCore::AuthenticationChallengeManagerPrivate::pageExists): + (WebCore::AuthenticationChallengeManager::AuthenticationChallengeManager): + (WebCore::AuthenticationChallengeManager::pageCreated): + (WebCore::AuthenticationChallengeManager::pageDeleted): + (WebCore::AuthenticationChallengeManager::pageVisibilityChanged): + (WebCore::AuthenticationChallengeManager::authenticationChallenge): + (WebCore::AuthenticationChallengeManager::cancelAuthenticationChallenge): + (WebCore::AuthenticationChallengeManager::notifyChallengeResult): + (WebCore::AuthenticationChallengeManager::instance): + (WebCore::AuthenticationChallengeManager::init): + * platform/blackberry/AuthenticationChallengeManager.h: + (WebCore): + (AuthenticationChallengeManager): + * platform/blackberry/PageClientBlackBerry.h: + * platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.cpp: + (WebCore::MediaPlayerPrivate::MediaPlayerPrivate): + (WebCore::MediaPlayerPrivate::~MediaPlayerPrivate): + (WebCore::MediaPlayerPrivate::onAuthenticationNeeded): + (WebCore::MediaPlayerPrivate::notifyChallengeResult): + * platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.h: + (MediaPlayerPrivate): + * platform/network/blackberry/NetworkJob.cpp: + (WebCore::NetworkJob::NetworkJob): + (WebCore::NetworkJob::~NetworkJob): + (WebCore): + (WebCore::NetworkJob::handleNotifyStatusReceived): + (WebCore::NetworkJob::handleNotifyClose): + (WebCore::NetworkJob::sendRequestWithCredentials): + (WebCore::NetworkJob::notifyChallengeResult): + * platform/network/blackberry/NetworkJob.h: + (NetworkJob): + +2012-09-21 Simon Hausmann <simon.hausmann@digia.com> + + Unreviewed, rolling out r129248. + http://trac.webkit.org/changeset/129248 + https://bugs.webkit.org/show_bug.cgi?id=96000 + + Broke win build + + * Target.pri: + * WebCore.vcproj/WebCore.vcproj: + * rendering/RenderingAllInOne.cpp: + +2012-09-21 Simon Hausmann <simon.hausmann@nokia.com> + + Make RenderingAllInOne.cpp usable for ports other than Apple/Win + https://bugs.webkit.org/show_bug.cgi?id=96000 + + Reviewed by Ryosuke Niwa. + + RenderingAllInOne.cpp unconditionally includes RenderThemeWin. This patch separates + it out from the file. + + * Target.pri: Add RenderingAllInOne.cpp to the list of supported all-in-one files. + * WebCore.vcproj/WebCore.vcproj: Compile RenderThemeWin.cpp separately. + * rendering/RenderingAllInOne.cpp: Don't include RenderThemeWin.cpp here. + +2012-09-21 Joanmarie Diggs <jdiggs@igalia.com> + + REGRESSION (r127882): accessibility/spinbutton-value.html failing on GTK + https://bugs.webkit.org/show_bug.cgi?id=96196 + + Reviewed by Martin Robinson. + + The "regression" is that a new test was added but the support was missing + in the Gtk port for spin buttons. + + No new tests. Instead the new test which had been skipped was unskipped + as part of this fix. + + * accessibility/gtk/WebKitAccessibleWrapperAtk.cpp: + (atkRole): Map SpinButtonRole to ATK_ROLE_SPIN_BUTTON + (getInterfaceMaskFromObject): Add SpinButtonRole to the roles implementing + the AtkValue interface. + +2012-09-21 Joanmarie Diggs <jdiggs@igalia.com> + + [GTK] [Stable] Infinite recursion in WebCore::AXObjectCache::getOrCreate + https://bugs.webkit.org/show_bug.cgi?id=96932 + + Reviewed by Martin Robinson. + + Make the decision based on RenderObjects rather than AccessibilityObjects + to avoid the infinite recursion which occurs when remapAriaRoleDueToParent + gets called. + + Test: platform/gtk/accessibility/remapped-aria-crash.html + + * accessibility/gtk/AccessibilityObjectAtk.cpp: + (WebCore::AccessibilityObject::accessibilityPlatformIncludesObject): + +2012-09-21 Jonathan Dong <jonathan.dong@torchmobile.com.cn> + + [BlackBerry] HTML5 media does not handle SSL certificate failures + https://bugs.webkit.org/show_bug.cgi?id=93324 + + Reviewed by Eric Carlson. + + RIM PR: 116205 + Passed FrameLoaderClientBlackBerry's playerId to MMRPlayer::load() + because MMRPlayer::load() added playerId as a new parameter, which + is required to initiate a MediaSSLHandlerStream to deal with + certificate failure when loading a "https" media url. + + Internally reviewed by Joe Mason <jmason@rim.com>. + + No new tests since there's no functional change. + + * platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.cpp: + (WebCore::MediaPlayerPrivate::load): + +2012-09-21 Evan Wallace <evan.exe@gmail.com> + + [WebSocket] Receiving a large message is really slow + https://bugs.webkit.org/show_bug.cgi?id=97237 + + Reviewed by Alexey Proskuryakov. + + WebSocketChannel always reallocates its internal buffer when it receives + and appends new data which causes dramatic slowdowns for messages over + 2 MB in size. This patch changes the internal buffer of WebSocketChannel + from a raw char array to a Vector<char> and uses its amortized append() + method. This brings the time to receive a 5 MB message from 5.2 seconds + to 0.25 seconds. + + This patch is only for optimization. No new tests are needed. + + * Modules/websockets/WebSocketChannel.cpp: + (WebCore::WebSocketChannel::WebSocketChannel): + (WebCore::WebSocketChannel::~WebSocketChannel): + (WebCore::WebSocketChannel::fail): + (WebCore::WebSocketChannel::resume): + (WebCore::WebSocketChannel::didReceiveSocketStreamData): + (WebCore::WebSocketChannel::appendToBuffer): + (WebCore::WebSocketChannel::skipBuffer): + (WebCore::WebSocketChannel::processBuffer): + (WebCore::WebSocketChannel::resumeTimerFired): + (WebCore::WebSocketChannel::processFrame): + * Modules/websockets/WebSocketChannel.h: + +2012-09-21 Andrey Adaikin <aandrey@chromium.org> + + Fix build with ENABLE_WEBGL=false + https://bugs.webkit.org/show_bug.cgi?id=97309 + + Reviewed by Eric Seidel. + + WebKit no longer builds when WEBGL is not enabled. + + * rendering/FilterEffectRenderer.h: + (FilterEffectRenderer): + +2012-09-21 Jonathan Dong <jonathan.dong@torchmobile.com.cn> + + [BlackBerry] Media player won't resize for the following source when first source fail to load + https://bugs.webkit.org/show_bug.cgi?id=97342 + + Reviewed by Yong Li. + + As platformPlayer will notify MediaPlayerPrivate for size change + when loading metadata failed (in this case hasVideo() is false), + we should prevent MediaPlayerPrivate to set width and height + attribute of media element, otherwise we won't get the correct + dimension for the following media sources. + + Internally reviewed by Max Feil. + + Test case: media/video-size.html + + * platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.cpp: + (WebCore::MediaPlayerPrivate::resizeSourceDimensions): + +2012-09-21 Dan Bernstein <mitz@apple.com> + + REGRESSION (r126763): Incorrect line breaking when both kerning and word spacing are enabled + https://bugs.webkit.org/show_bug.cgi?id=97280 + + Reviewed by Adele Peterson. + + Font::width() never applies word spacing to the first character in the TextRun. The + TextLayout optimization tried to achieve this behavior by not applying word spacing to + any character, which led to this bug. + + Test: fast/text/word-space-with-kerning-2.html + + * platform/graphics/mac/ComplexTextController.cpp: + (WebCore::TextLayout::TextLayout): Changed to use the given font rather than a version + without word spacing. + (WebCore::TextLayout::width): Added a check if the run starts with a space at a non-zero + offset. If that is the case, then the ComplexTextController has added word spacing to that + space, so subtract it here in order to maintain the behavior described above. + +2012-09-21 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r129219. + http://trac.webkit.org/changeset/129219 + https://bugs.webkit.org/show_bug.cgi?id=97338 + + Presumably broke Apple Mac compilation (Requested by yurys_ on + #webkit). + + * bindings/js/JSHTMLCanvasElementCustom.cpp: + (WebCore::JSHTMLCanvasElement::getContext): + * bindings/v8/custom/V8HTMLCanvasElementCustom.cpp: + (WebCore::V8HTMLCanvasElement::getContextCallback): + * inspector/InjectedScriptCanvasModule.cpp: + (WebCore::InjectedScriptCanvasModule::wrapWebGLContext): + (WebCore): + * inspector/InjectedScriptCanvasModule.h: + (InjectedScriptCanvasModule): + * inspector/InspectorCanvasAgent.cpp: + * inspector/InspectorCanvasAgent.h: + * inspector/InspectorCanvasInstrumentation.h: + * inspector/InspectorInstrumentation.h: + (InspectorInstrumentation): + +2012-09-21 Andrey Adaikin <aandrey@chromium.org> + + Web Inspector: [Canvas] support 2D canvas instrumentation from the inspector C++ code + https://bugs.webkit.org/show_bug.cgi?id=97203 + + Reviewed by Yury Semikhatsky. + + Implements wrapping a 2D canvas context through the injected canvas module script facility. + + * bindings/js/JSHTMLCanvasElementCustom.cpp: + (WebCore::JSHTMLCanvasElement::getContext): + * bindings/v8/custom/V8HTMLCanvasElementCustom.cpp: + (WebCore::V8HTMLCanvasElement::getContextCallback): + * inspector/InjectedScriptCanvasModule.cpp: + (WebCore::InjectedScriptCanvasModule::wrapCanvas2DContext): + (WebCore): + (WebCore::InjectedScriptCanvasModule::wrapWebGLContext): + (WebCore::InjectedScriptCanvasModule::callWrapContextFunction): + * inspector/InjectedScriptCanvasModule.h: + (InjectedScriptCanvasModule): + * inspector/InspectorCanvasAgent.cpp: + (WebCore::InspectorCanvasAgent::wrapCanvas2DRenderingContextForInstrumentation): + (WebCore): + * inspector/InspectorCanvasAgent.h: + (InspectorCanvasAgent): + * inspector/InspectorCanvasInstrumentation.h: + (WebCore::InspectorInstrumentation::wrapCanvas2DRenderingContextForInstrumentation): + (WebCore): + * inspector/InspectorInstrumentation.h: + (InspectorInstrumentation): + +2012-09-20 Andrey Kosyakov <caseq@chromium.org> + + Web Inspector: [refactoring] simplify interface to FileOutputStream + https://bugs.webkit.org/show_bug.cgi?id=97226 + + Reviewed by Yury Semikhatsky. + + - change OutputStream interface to match that of stream; + - fix OutputStream implementations (FileOutputStream and those in heap profiler); + - fix usages in Timeline and HeapProfiler. + + * inspector/front-end/FileUtils.js: + (WebInspector.OutputStream.prototype.write): + (WebInspector.OutputStream.prototype.close): + (WebInspector.ChunkedFileReader.prototype.start): + (WebInspector.ChunkedFileReader.prototype._onChunkLoaded): + (WebInspector.ChunkedXHRReader.prototype.start): + (WebInspector.ChunkedXHRReader.prototype._onProgress): + (WebInspector.ChunkedXHRReader.prototype._onLoad): + (WebInspector.FileOutputStream): + (WebInspector.FileOutputStream.prototype.open.callbackWrapper): + (WebInspector.FileOutputStream.prototype.open): + (WebInspector.FileOutputStream.prototype.write): + (WebInspector.FileOutputStream.prototype.close): + (WebInspector.FileOutputStream.prototype._onAppendDone): + * inspector/front-end/HeapSnapshotLoader.js: + (WebInspector.HeapSnapshotLoader.prototype.close): + (WebInspector.HeapSnapshotLoader.prototype.write): + * inspector/front-end/HeapSnapshotProxy.js: + (WebInspector.HeapSnapshotLoaderProxy.prototype.startTransfer): + (WebInspector.HeapSnapshotLoaderProxy.prototype.write): + (WebInspector.HeapSnapshotLoaderProxy.prototype.close): + * inspector/front-end/HeapSnapshotView.js: + (WebInspector.HeapProfileHeader): + (WebInspector.HeapProfileHeader.prototype.load): + (WebInspector.HeapProfileHeader.prototype._setupWorker): + (WebInspector.HeapProfileHeader.prototype.dispose): + (WebInspector.HeapProfileHeader.prototype.transferChunk.callback): + (WebInspector.HeapProfileHeader.prototype.transferChunk): + (WebInspector.HeapProfileHeader.prototype.finishHeapSnapshot): + (WebInspector.HeapProfileHeader.prototype.saveToFile.onOpen): + (WebInspector.HeapProfileHeader.prototype.saveToFile): + * inspector/front-end/TimelineModel.js: + (WebInspector.TimelineModel.prototype._createFileWriter): + (WebInspector.TimelineModel.prototype.saveToFile.callback): + (WebInspector.TimelineModel.prototype.saveToFile): + (WebInspector.TimelineModelLoader): + (WebInspector.TimelineModelLoader.prototype.write): + (WebInspector.TimelineModelLoader.prototype.close): + (WebInspector.TimelineSaver): + (WebInspector.TimelineSaver.prototype.save): + (WebInspector.TimelineSaver.prototype._writeNextChunk): + +2012-09-21 Alexandru Chiculita <achicu@adobe.com> + + -webkit-clip-path is applied on elements that are not descendant of the container + https://bugs.webkit.org/show_bug.cgi?id=97217 + + Reviewed by Dirk Schulze. + + The clip-path was set on the GraphicsContext, but was never restored, thus making all the layers + rendered in the same "group" of save/restore state use the same clip-path. + + Test: css3/masking/clip-path-restore.html + + * css/StyleResolver.cpp: + (WebCore::StyleResolver::collectMatchingRulesForList): + clip-path property should create a stacking-context, otherwise the RenderLayers will not be nested, + meaning that the clip-path of the parent is not going to apply correctly. + + * rendering/RenderLayer.cpp: + (WebCore::RenderLayer::paintLayerContents): + +2012-09-21 Kent Tamura <tkent@chromium.org> + + Remove unused functions of LocalizedDate.h + https://bugs.webkit.org/show_bug.cgi?id=97311 + + Reviewed by Kentaro Hara. + + WebCore::localizedTimeFormatText, WebCore::localizedShortTimeFormatText, + and WebCore::timeAMPMLabels are not used any more because we switched to + the corresponding functions of Localizer. + + No new tests because of no behavior changes. + + * platform/text/Localizer.h: + (Localizer): Moved comments from LocalizedDate.h. + * platform/text/LocalizedDate.h: + (WebCore): Removed localizedTimeFormatText, + localizedShortTimeFormatText, and timeAMPMLabels. + * platform/text/LocalizedDateICU.cpp: + (WebCore): ditto. + * platform/text/LocalizedDateWin.cpp: + (WebCore): ditto. + * platform/text/mac/LocalizedDateMac.cpp: + (WebCore): ditto. + +2012-09-21 Keishi Hattori <keishi@webkit.org> + + Add datalist suggestions into DateTimeChooserParameters + https://bugs.webkit.org/show_bug.cgi?id=97292 + + Reviewed by Kent Tamura. + + We read datalist suggestions, add them to DateTimeChooserParameters, + and pass them to the page popup. + + No new tests. No behavior change yet. + + * html/shadow/CalendarPickerElement.cpp: + (WebCore::CalendarPickerElement::openPopup): Read datalist suggestions and add them to DateTimeChooserParameters + * platform/DateTimeChooser.h: + (DateTimeChooserParameters): Added localizedSuggestionValues so we can show localized values inside the page popup. + +2012-09-21 Yoshifumi Inoue <yosin@chromium.org> + + [Forms] DateTimeEditElement::layout() should take date time format as a parameter + https://bugs.webkit.org/show_bug.cgi?id=97300 + + Reviewed by Kent Tamura. + + This patch introduces DateTimeEditElement::LayoutParameters struct for + passing four parameters to DateTimeEditElement::layout() for passing + date time format from client of DateTimeEditElement instead of + DateTimeEditElement::layout() takes time or short time format. + + This patch is a part of preparation of introducing multiple fields + date/datetime/month/week input UI. + + This patch affects ports which enable both ENABLE_INPUT_TYPE_TIME and + ENABLE_INPUT_TYPE_TIME_MULTIPLE_FIELDS. + + No new tests. This patch doesn't change behavior. + + * html/TimeInputType.cpp: + (WebCore::TimeInputType::updateInnerTextValue): Changed to use LayoutParmeters. + * html/shadow/DateTimeEditElement.cpp: Removed unused include files, LocalizedDate.h and LocalizedNumber.h. + (DateTimeEditBuilder): + (WebCore::DateTimeEditBuilder::DateTimeEditBuilder): Changed parameters to LayoutParmeters. + (WebCore::DateTimeEditElement::LayoutParameters::shouldHaveSecondField): Moved from DateTimeEditBuilder::needSecondField(). + (WebCore::DateTimeEditElement::layout): Changed to take LayoutParameters. + (WebCore::DateTimeEditElement::setValueAsDate): ditto + (WebCore::DateTimeEditElement::setEmptyValue): ditto + * html/shadow/DateTimeEditElement.h: Removed unused classe declarations DateComponents and DateTimeEditLayouter. + (LayoutParameters): Added to bundle parameters for layout(). + (WebCore::DateTimeEditElement::LayoutParameters::LayoutParameters): Added. + +2012-09-20 Pavel Feldman <pfeldman@chromium.org> + + Web Inspector: render grid scale to the right / at bottom in case box is close to 0 on that axis. + https://bugs.webkit.org/show_bug.cgi?id=97219 + + Reviewed by Vsevolod Vlasov. + + Otherwise, it is hard to inspect objects close to (0, 0) + + * inspector/InspectorOverlayPage.html: + +2012-09-21 Sheriff Bot <webkit.review.bot@gmail.com> + + Unreviewed, rolling out r129086. + http://trac.webkit.org/changeset/129086 + https://bugs.webkit.org/show_bug.cgi?id=97312 + + Broke input rendering (Requested by shinyak on #webkit). + + * html/BaseButtonInputType.cpp: + (WebCore): + * html/BaseButtonInputType.h: + (WebCore::BaseButtonInputType::BaseButtonInputType): + (BaseButtonInputType): + * html/FileInputType.cpp: + (WebCore::UploadButtonElement::create): + (WebCore::UploadButtonElement::createForMultiple): + * html/HTMLInputElement.cpp: + (WebCore::HTMLInputElement::parseAttribute): + * html/InputType.cpp: + * html/InputType.h: + (InputType): + * rendering/RenderButton.cpp: + (WebCore::RenderButton::RenderButton): + (WebCore::RenderButton::styleDidChange): + (WebCore::RenderButton::updateFromElement): + (WebCore): + (WebCore::RenderButton::setText): + (WebCore::RenderButton::text): + * rendering/RenderButton.h: + (RenderButton): + +2012-09-21 Kihong Kwon <kihong.kwon@samsung.com> + + Remove useless class prototypes from Vibration.h + https://bugs.webkit.org/show_bug.cgi?id=97304 + + Reviewed by Kentaro Hara. + + Remove two useless class prototype statements in the Vibration.h + + * Modules/vibration/Vibration.h: + +2012-09-21 Keishi Hattori <keishi@webkit.org> + + Prepare CalendarPicker so we can add another picker, SuggetionPicker + https://bugs.webkit.org/show_bug.cgi?id=97193 + + Reviewed by Kent Tamura. + + Preparation so we can add another picker to CalendarPicker and switch + between them. + + No new tests. No behavior change. + + * Resources/pagepopups/calendarPicker.css: + (.calendar-picker): Added so we can apply these styles just to calendar picker. + * Resources/pagepopups/calendarPicker.js: + (CalendarPicker.validateConfig): Renamed so each picker can validate the config object. + (initialize): + (closePicker): Call Picker.cleanup(). + (openCalendarPicker): + (CalendarPicker): + (CalendarPicker.prototype.cleanup): Cleanup event listener on document.body. + * Resources/pagepopups/pickerCommon.js: + (Picker.prototype.cleanup): + +2012-09-20 John Mellor <johnme@chromium.org> + + Text Autosizing: Cluster text at flow roots, for consistency and to avoid autosizing headers/footers. + https://bugs.webkit.org/show_bug.cgi?id=97025 + + Reviewed by Julien Chaffraix. + + This patch has 3 main changes: + + 1. All text within a "cluster" (roughly equivalent to a CSS flow root / + block formatting context) must have a uniform textAutosizingMultiplier, + except for subtrees which are themselves clusters. This improves the + consistency of the final output, since sibling blocks are now more + likely to have the same multiplier (hence grow in proportion). + + 2. Clusters must contain a minimum amount of text in order to be + autosized (4 lines of text, assuming each char is 1em wide, so about + 2 lines of text in practice). This is to reduce the likelihood of + autosizing things like headers and footers, which can be quite + visually distracting. The rationale is that if a cluster contains + very few lines of text then it's ok to have to zoom in and pan from + side to side to read each line, since if there are very few lines of + text you'll only need to pan across once or twice. + + 3. To avoid adding a 3rd tree traversal, processSubtree/processBox were + refactored such that all of Text Autosizing now happens as a single + tree traversal (hence halving the number of tree traversals done). + + Tests: fast/text-autosizing/cluster-narrow-in-wide.html + fast/text-autosizing/cluster-wide-in-narrow.html + fast/text-autosizing/clusters-insufficient-text.html + fast/text-autosizing/clusters-insufficient-width.html + fast/text-autosizing/clusters-sufficient-text-except-in-root.html + fast/text-autosizing/clusters-sufficient-width.html + + * rendering/TextAutosizer.cpp: + (TextAutosizingWindowInfo): + + Added this struct to bundle together the various sizes that + processSubtree needs to pass to every recursive call to + processCluster and processContainer. + + (WebCore::TextAutosizer::processSubtree): + + - Bundle windowSize and minLayoutSize together as a single struct, + TextAutosizingWindowInfo, rather than passing them separately. + - Walk up the tree to find the current cluster and container, rather + than (incorrectly) assuming that the layoutRoot is always a + container. + - Call processCluster instead of traversing the tree. + + (WebCore::TextAutosizer::processCluster): + + Calculates the multiplier based on the width of the cluster (moved + the calculation here from processBox, since now the multiplier is + fixed per cluster), and delegates to processContainer for the actual + tree traversal (since clusters are also containers). + + (WebCore::contentHeightIsConstrained): + + Changed parameter to RenderBlock. + + (WebCore::TextAutosizer::processContainer): + + This now takes care of the whole tree traversal, recursively calling + processCluster/processContainer when it encounters such an object, + and setMultiplier on RenderText objects (as processBox used to). + Also added a check that the RenderText's multiplier is not already + equal to the target multiplier (to save needlessly setting it). + + (WebCore::TextAutosizer::isContainer): + + - Changed to be a positive (is) instead of negative (isNot) check. + - Require objects to be RenderBlocks so it's easier to find them + using containingBlock, and there don't seem to be many interesting + RenderBoxes that aren't RenderBlocks. + + (WebCore::TextAutosizer::isAutosizingCluster): + + A container that is also a flow root / block formatting context + (approximately), hence demarcates an independent region of the page, + within which we want consistent autosizing. + + (WebCore::TextAutosizer::clusterShouldBeAutosized): + + Uses measureDescendantTextWidth and to check whether the cluster + contains enough text to be worth autosizing. + + (WebCore::TextAutosizer::measureDescendantTextWidth): + + Recursively traverse the cluster, skipping constrained height + containers as processContainer does, to measure how much autosizable + text it contains. Early out as soon as the minimum text width is + reached. + + (WebCore::TextAutosizer::nextInPreOrderSkippingDescendantsOfContainers): + + Replaces nextInPreOrderMatchingFilter. The filter is now fixed to + isContainer (we no longer need an isAutosizingCluster filter, since + I consolidated the tree traversal), and filtered objects are + actually returned (so they can in turn be recursively traversed), + it's just their descendants that get skipped. + + * rendering/TextAutosizer.h: + (TextAutosizer): + + - Deleted RenderObjectFilterFunctor, since the filter of + nextInPreOrderSkippingDescendantsOfContainers is now fixed. + +2012-09-20 Yoshifumi Inoue <yosin@chromium.org> + + [Platform] There are memory leak in LocaleICU + https://bugs.webkit.org/show_bug.cgi?id=97289 + + Reviewed by Kent Tamura. + + This patch adds udt_close() calls for medium time format and short + time format data used in LocaleICU class to avoid memory leak. + + This memory leak is found by external tool Valgrind and reported in + Chromium bug repositry(http://crbug.com/151006) with stack trace of + call path of leaked memory. + + This patch affects ports which enable both ENABLE_INPUT_TYPE_TIME and + ENABLE_INPUT_TYPE_TIME_MULTIPLE_FIELDS. + + No new tests. External tool such as Valgrind will check this memory leak. + + * platform/text/LocaleICU.cpp: + (WebCore::LocaleICU::~LocaleICU): Added to call udt_close() for m_mediumTimeFormat + and m_shortTimeFormat which have UDateFormat objects. + +2012-09-20 Kenichi Ishibashi <bashi@chromium.org> + + Chromium mac cannot display AppleColorEmoji + https://bugs.webkit.org/show_bug.cgi?id=97286 + + Reviewed by Kent Tamura. + + Disable AppleColorEmoji for now. We will re-enable it after Skia supports CTFontDrawGlyphs(). + + No new tests. Fallback fonts should be used for emoji codepoints. + + * platform/graphics/mac/FontCacheMac.mm: + (WebCore::FontCache::getFontDataForCharacters): + +2012-09-20 Luke Macpherson <macpherson@chromium.org> + + Fix use-after free when using a variable to specify a -webkit-filter. + https://bugs.webkit.org/show_bug.cgi?id=97153 + + Reviewed by Abhishek Arya. + + Make StyleResolver's m_pendingSVGDocuments a hashmap of RefPtr instead of raw pointers such that the document values cannot be freed prematurely. + Present assumption is that storing raw pointers is ok because CSSValues will live as long as the StyleResolver instance, however that it no longer + true when variables are used, so we must ensure we increment the reference counter to ensure the CSSValues are not freed prematurely. + + Test: fast/css/variables/var-filter.html + + * css/StyleResolver.cpp: + (WebCore::StyleResolver::collectMatchingRulesForList): + * css/StyleResolver.h: + (StyleResolver): + +2012-09-20 Levi Weintraub <leviw@chromium.org> + + Prevent reading stale data from InlineTextBoxes + https://bugs.webkit.org/show_bug.cgi?id=94750 + + Reviewed by Abhishek Arya. + + Text from dirty InlineTextBoxes should never be read or used. This change + enforces this design goal by forcefully zero-ing out the start and length + of InlineTextBoxes when they're being marked dirty. Ideally, we'd also + add asserts to the accessors for this data, but there are still several + places in editing that cause this. https://bugs.webkit.org/show_bug.cgi?id=97264 + tracks these cases. + + This change involves making markDirty virtual. Running the line-layout + performance test as well as profiling resizing the html5 spec showed + negligable impact with this change. + + No new tests as this doesn't change any proper behavior. + + * dom/Position.cpp: + (WebCore::Position::downstream): Adding a FIXME. + * rendering/InlineBox.h: + (WebCore::InlineBox::markDirty): Marking virtual to allow InlineTextBox to + overload and zero out its start and length. + * rendering/InlineTextBox.cpp: + (WebCore::InlineTextBox::markDirty): Zeroing out the start and length when + we mark the box dirty. + * rendering/InlineTextBox.h: + * rendering/RenderText.cpp: + (WebCore::RenderText::setTextWithOffset): Adding a FIXME. + +2012-09-20 Adam Barth <abarth@webkit.org> + + Measure how often web pages use Worker and SharedWorker + https://bugs.webkit.org/show_bug.cgi?id=97273 + + Reviewed by Ojan Vafai. + + We're not considering removing these features, but it will give us a + baseline idea of how often they're used. + + * page/FeatureObserver.h: + * workers/SharedWorker.cpp: + (WebCore::SharedWorker::create): + * workers/Worker.cpp: + (WebCore::Worker::create): + +2012-09-20 Tony Chang <tony@chromium.org> + + [chromium] Enable more clang warnings + https://bugs.webkit.org/show_bug.cgi?id=97257 + + Reviewed by James Robinson. + + Add -Wunused-parameter to WebCore targets. Apple's Mac compile already + warns on this and it's a common source of error for Chromium patches. + + No new tests, should compile cleanly. + + * WebCore.gyp/WebCore.gyp: + +2012-09-20 Dan Bernstein <mitz@apple.com> + + Kerning never occurs between a space and the following glyph + https://bugs.webkit.org/show_bug.cgi?id=97269 + + Reviewed by Tim Horton. + + Covered by several existing tests. + + * platform/graphics/mac/ComplexTextController.cpp: + (WebCore::ComplexTextController::adjustGlyphsAndAdvances): Changed to not reset the advance + of a space, and added a comment about how this also needs to be fixed for other characters + that are treated as spaces. + +2012-09-20 Kenichi Ishibashi <bashi@chromium.org> + + [Chromium] Improve glyph selection of HarfBuzzShaper + https://bugs.webkit.org/show_bug.cgi?id=97164 + + Reviewed by Tony Chang. + + Take into account clusters for selection. + + Test: fast/text/international/hebrew-selection.html + + * platform/graphics/harfbuzz/ng/HarfBuzzShaper.cpp: + (WebCore::HarfBuzzShaper::HarfBuzzRun::applyShapeResult): Removed m_logClusters. + m_logCluster is no longer used. + (WebCore::HarfBuzzShaper::HarfBuzzRun::characterIndexForXPosition): + - If targetX is in the left side of the first cluster, return the leftmost character index. + - If targetX is in the right side of the last cluster, return the rightmost character index. + - If targetX is between the right side of the cluster N and the left side of the cluster N+1, then: + - return N+1 for LTR. + - return N for RTL. + (WebCore::HarfBuzzShaper::HarfBuzzRun::xPositionForOffset): + Find the cluster of index in question, then: + - return the left side boundary of the cluster for LTR. + - return the right side boundary of the cluster for RTL. + * platform/graphics/harfbuzz/ng/HarfBuzzShaper.h: + (HarfBuzzRun): + +2012-09-20 Tony Chang <tony@chromium.org> + + Replace RenderListBox::updateLogicalHeight with RenderListBox::computeLogicalHeight + https://bugs.webkit.org/show_bug.cgi?id=97263 + + Reviewed by Ojan Vafai. + + This is part of making computeLogicalHeight virtual so with any RenderBox pointer, one + can compute the logical height without mutating the RenderBox. + + No new tests, this is a refactor and existing list box tests should pass. + + * rendering/RenderBox.h: + (RenderBox): + * rendering/RenderListBox.cpp: + (WebCore::RenderListBox::layout): Move layout related logic here. + (WebCore::RenderListBox::computeLogicalHeight): Use const version and remove layout related code. + * rendering/RenderListBox.h: + (RenderListBox): Override computeLogicalHeight. + +2012-09-20 Mike West <mkwst@chromium.org> + + CSP reports should send an empty "blocked-uri" rather than nothing. + https://bugs.webkit.org/show_bug.cgi?id=97256 + + Reviewed by Adam Barth. + + In cases where a Content Security Policy violation report is generated + without blocking a resource at a particular URI (inline scripts, for + example), we currently leave the "blocked-uri" attribute out of the + report entirely. For the same reason that we included the "referrer" + attribute in webkit.org/b/97233, we should include an explicitly empty + "blocked-uri" in these cases. + + This new behavior is covered by updates to existing test expectations + around the reporting functionality. + + * page/ContentSecurityPolicy.cpp: + (WebCore::ContentSecurityPolicy::reportViolation): + If the 'blocked-uri' is invalid, add a "blocked-uri" attribute that + is explicitly empty. + +2012-09-20 Patrick Gansterer <paroga@webkit.org> + + Add String::numberToFixedPrecisionString() + https://bugs.webkit.org/show_bug.cgi?id=96330 + + Reviewed by Benjamin Poulain. + + * platform/text/TextStream.cpp: + (WebCore::TextStream::operator<<): Use the new function instead of String::number() with flags. + +2012-09-20 Adam Klein <adamk@chromium.org> + + Rename ContainerNode::parserAddChild "parserAppendChild" for consistency + https://bugs.webkit.org/show_bug.cgi?id=97254 + + Reviewed by Adam Barth. + + No functional change, all the below changes are simple renames. + + * dom/ContainerNode.cpp: + (WebCore::ContainerNode::takeAllChildrenFrom): + (WebCore::ContainerNode::parserAppendChild): + * dom/ContainerNode.h: + (ContainerNode): + * dom/DOMImplementation.cpp: + (WebCore::DOMImplementation::createDocument): + * editing/markup.cpp: + (WebCore::createFragmentForTransformToFragment): + * html/HTMLViewSourceDocument.cpp: + (WebCore::HTMLViewSourceDocument::createContainingTable): + (WebCore::HTMLViewSourceDocument::addSpanWithClassName): + (WebCore::HTMLViewSourceDocument::addLine): + (WebCore::HTMLViewSourceDocument::finishLine): + (WebCore::HTMLViewSourceDocument::addText): + (WebCore::HTMLViewSourceDocument::addBase): + (WebCore::HTMLViewSourceDocument::addLink): + * html/parser/HTMLConstructionSite.cpp: + (WebCore::executeTask): + * html/parser/HTMLTreeBuilder.cpp: + (WebCore::HTMLTreeBuilder::callTheAdoptionAgency): + * html/track/WebVTTParser.cpp: + (WebCore::WebVTTParser::constructTreeFromToken): + * xml/XMLErrors.cpp: + (WebCore::createXHTMLParserErrorHeader): + (WebCore::XMLErrors::insertErrorMessageBlock): + * xml/parser/XMLDocumentParser.cpp: + (WebCore::XMLDocumentParser::enterText): + (WebCore::XMLDocumentParser::parseDocumentFragment): + * xml/parser/XMLDocumentParserLibxml2.cpp: + (WebCore::XMLDocumentParser::startElementNs): + (WebCore::XMLDocumentParser::processingInstruction): + (WebCore::XMLDocumentParser::cdataBlock): + (WebCore::XMLDocumentParser::comment): + (WebCore::XMLDocumentParser::internalSubset): + * xml/parser/XMLDocumentParserQt.cpp: + (WebCore::XMLDocumentParser::parseStartElement): + (WebCore::XMLDocumentParser::parseProcessingInstruction): + (WebCore::XMLDocumentParser::parseCdata): + (WebCore::XMLDocumentParser::parseComment): + (WebCore::XMLDocumentParser::parseDtd): + * xml/parser/XMLTreeBuilder.cpp: + (WebCore::XMLTreeBuilder::processDOCTYPE): + (WebCore::XMLTreeBuilder::processStartTag): + (WebCore::XMLTreeBuilder::add): + +2012-09-20 James Robinson <jamesr@chromium.org> + + [chromium] Remove unused copy of chromium compositor implementation files + https://bugs.webkit.org/show_bug.cgi?id=97255 + + Reviewed by Adam Barth. + + Now that use_libcc_for_compositor is set to 1 these files aren't used anywhere. + + * WebCore.gyp/WebCore.gyp: + * WebCore.gypi: + * platform/chromium/support/CCThreadImpl.cpp: Removed. + * platform/chromium/support/CCThreadImpl.h: Removed. + * platform/chromium/support/WebCompositorImpl.cpp: Removed. + * platform/chromium/support/WebCompositorImpl.h: Removed. + * platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.cpp: Removed. + * platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.h: Removed. + * platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.cpp: Removed. + * platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.h: Removed. + * platform/graphics/chromium/Canvas2DLayerBridge.cpp: + (WebCore::Canvas2DLayerBridge::Canvas2DLayerBridge): + (WebCore::Canvas2DLayerBridge::~Canvas2DLayerBridge): + * platform/graphics/chromium/CanvasLayerTextureUpdater.cpp: Removed. + * platform/graphics/chromium/CanvasLayerTextureUpdater.h: Removed. + * platform/graphics/chromium/ContentLayerChromium.cpp: Removed. + * platform/graphics/chromium/ContentLayerChromium.h: Removed. + * platform/graphics/chromium/ContentLayerChromiumClient.h: Removed. + * platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.cpp: Removed. + * platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.h: Removed. + * platform/graphics/chromium/GeometryBinding.cpp: Removed. + * platform/graphics/chromium/GeometryBinding.h: Removed. + * platform/graphics/chromium/GraphicsLayerChromium.cpp: + * platform/graphics/chromium/HeadsUpDisplayLayerChromium.cpp: Removed. + * platform/graphics/chromium/HeadsUpDisplayLayerChromium.h: Removed. + * platform/graphics/chromium/IOSurfaceLayerChromium.cpp: Removed. + * platform/graphics/chromium/IOSurfaceLayerChromium.h: Removed. + * platform/graphics/chromium/ImageLayerChromium.cpp: Removed. + * platform/graphics/chromium/ImageLayerChromium.h: Removed. + * platform/graphics/chromium/LayerChromium.cpp: Removed. + * platform/graphics/chromium/LayerChromium.h: Removed. + * platform/graphics/chromium/LayerTextureSubImage.cpp: Removed. + * platform/graphics/chromium/LayerTextureSubImage.h: Removed. + * platform/graphics/chromium/LayerTextureUpdater.h: Removed. + * platform/graphics/chromium/PlatformColor.h: Removed. + * platform/graphics/chromium/ProgramBinding.cpp: Removed. + * platform/graphics/chromium/ProgramBinding.h: Removed. + * platform/graphics/chromium/RateLimiter.cpp: Removed. + * platform/graphics/chromium/RateLimiter.h: Removed. + * platform/graphics/chromium/RenderSurfaceChromium.cpp: Removed. + * platform/graphics/chromium/RenderSurfaceChromium.h: Removed. + * platform/graphics/chromium/ScrollbarLayerChromium.cpp: Removed. + * platform/graphics/chromium/ScrollbarLayerChromium.h: Removed. + * platform/graphics/chromium/ShaderChromium.cpp: Removed. + * platform/graphics/chromium/ShaderChromium.h: Removed. + * platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.cpp: Removed. + * platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.h: Removed. + * platform/graphics/chromium/SolidColorLayerChromium.cpp: Removed. + * platform/graphics/chromium/SolidColorLayerChromium.h: Removed. + * platform/graphics/chromium/TextureCopier.cpp: Removed. + * platform/graphics/chromium/TextureCopier.h: Removed. + * platform/graphics/chromium/TextureLayerChromium.cpp: Removed. + * platform/graphics/chromium/TextureLayerChromium.h: Removed. + * platform/graphics/chromium/TextureLayerChromiumClient.h: Removed. + * platform/graphics/chromium/ThrottledTextureUploader.cpp: Removed. + * platform/graphics/chromium/ThrottledTextureUploader.h: Removed. + * platform/graphics/chromium/TiledLayerChromium.cpp: Removed. + * platform/graphics/chromium/TiledLayerChromium.h: Removed. + * platform/graphics/chromium/TreeSynchronizer.cpp: Removed. + * platform/graphics/chromium/TreeSynchronizer.h: Removed. + * platform/graphics/chromium/UnthrottledTextureUploader.h: Removed. + * platform/graphics/chromium/VideoLayerChromium.cpp: Removed. + * platform/graphics/chromium/VideoLayerChromium.h: Removed. + * platform/graphics/chromium/cc/CCActiveAnimation.cpp: Removed. + * platform/graphics/chromium/cc/CCActiveAnimation.h: Removed. + * platform/graphics/chromium/cc/CCAnimationCurve.cpp: Removed. + * platform/graphics/chromium/cc/CCAnimationCurve.h: Removed. + * platform/graphics/chromium/cc/CCAnimationEvents.h: Removed. + * platform/graphics/chromium/cc/CCAppendQuadsData.h: Removed. + * platform/graphics/chromium/cc/CCCheckerboardDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCCheckerboardDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCCompletionEvent.h: Removed. + * platform/graphics/chromium/cc/CCDamageTracker.cpp: Removed. + * platform/graphics/chromium/cc/CCDamageTracker.h: Removed. + * platform/graphics/chromium/cc/CCDebugBorderDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCDebugBorderDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCDebugRectHistory.cpp: Removed. + * platform/graphics/chromium/cc/CCDebugRectHistory.h: Removed. + * platform/graphics/chromium/cc/CCDelayBasedTimeSource.cpp: Removed. + * platform/graphics/chromium/cc/CCDelayBasedTimeSource.h: Removed. + * platform/graphics/chromium/cc/CCDirectRenderer.cpp: Removed. + * platform/graphics/chromium/cc/CCDirectRenderer.h: Removed. + * platform/graphics/chromium/cc/CCDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCFontAtlas.cpp: Removed. + * platform/graphics/chromium/cc/CCFontAtlas.h: Removed. + * platform/graphics/chromium/cc/CCFrameRateController.cpp: Removed. + * platform/graphics/chromium/cc/CCFrameRateController.h: Removed. + * platform/graphics/chromium/cc/CCFrameRateCounter.cpp: Removed. + * platform/graphics/chromium/cc/CCFrameRateCounter.h: Removed. + * platform/graphics/chromium/cc/CCGraphicsContext.h: Removed. + * platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCInputHandler.h: Removed. + * platform/graphics/chromium/cc/CCKeyframedAnimationCurve.cpp: Removed. + * platform/graphics/chromium/cc/CCKeyframedAnimationCurve.h: Removed. + * platform/graphics/chromium/cc/CCLayerAnimationController.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerAnimationController.h: Removed. + * platform/graphics/chromium/cc/CCLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCLayerIterator.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerIterator.h: Removed. + * platform/graphics/chromium/cc/CCLayerQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerQuad.h: Removed. + * platform/graphics/chromium/cc/CCLayerSorter.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerSorter.h: Removed. + * platform/graphics/chromium/cc/CCLayerTilingData.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerTilingData.h: Removed. + * platform/graphics/chromium/cc/CCLayerTreeHost.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerTreeHost.h: Removed. + * platform/graphics/chromium/cc/CCLayerTreeHostClient.h: Removed. + * platform/graphics/chromium/cc/CCLayerTreeHostCommon.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerTreeHostCommon.h: Removed. + * platform/graphics/chromium/cc/CCLayerTreeHostImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCLayerTreeHostImpl.h: Removed. + * platform/graphics/chromium/cc/CCMathUtil.cpp: Removed. + * platform/graphics/chromium/cc/CCMathUtil.h: Removed. + * platform/graphics/chromium/cc/CCOcclusionTracker.cpp: Removed. + * platform/graphics/chromium/cc/CCOcclusionTracker.h: Removed. + * platform/graphics/chromium/cc/CCOverdrawMetrics.cpp: Removed. + * platform/graphics/chromium/cc/CCOverdrawMetrics.h: Removed. + * platform/graphics/chromium/cc/CCPageScaleAnimation.cpp: Removed. + * platform/graphics/chromium/cc/CCPageScaleAnimation.h: Removed. + * platform/graphics/chromium/cc/CCPrioritizedTexture.cpp: Removed. + * platform/graphics/chromium/cc/CCPrioritizedTexture.h: Removed. + * platform/graphics/chromium/cc/CCPrioritizedTextureManager.cpp: Removed. + * platform/graphics/chromium/cc/CCPrioritizedTextureManager.h: Removed. + * platform/graphics/chromium/cc/CCPriorityCalculator.cpp: Removed. + * platform/graphics/chromium/cc/CCPriorityCalculator.h: Removed. + * platform/graphics/chromium/cc/CCProxy.cpp: Removed. + * platform/graphics/chromium/cc/CCProxy.h: Removed. + * platform/graphics/chromium/cc/CCQuadCuller.cpp: Removed. + * platform/graphics/chromium/cc/CCQuadCuller.h: Removed. + * platform/graphics/chromium/cc/CCQuadSink.h: Removed. + * platform/graphics/chromium/cc/CCRenderPass.cpp: Removed. + * platform/graphics/chromium/cc/CCRenderPass.h: Removed. + * platform/graphics/chromium/cc/CCRenderPassDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCRenderPassDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCRenderPassSink.h: Removed. + * platform/graphics/chromium/cc/CCRenderSurface.cpp: Removed. + * platform/graphics/chromium/cc/CCRenderSurface.h: Removed. + * platform/graphics/chromium/cc/CCRenderSurfaceFilters.cpp: Removed. + * platform/graphics/chromium/cc/CCRenderSurfaceFilters.h: Removed. + * platform/graphics/chromium/cc/CCRenderer.h: Removed. + * platform/graphics/chromium/cc/CCRendererGL.cpp: Removed. + * platform/graphics/chromium/cc/CCRendererGL.h: Removed. + * platform/graphics/chromium/cc/CCRenderingStats.h: Removed. + * platform/graphics/chromium/cc/CCResourceProvider.cpp: Removed. + * platform/graphics/chromium/cc/CCResourceProvider.h: Removed. + * platform/graphics/chromium/cc/CCScheduler.cpp: Removed. + * platform/graphics/chromium/cc/CCScheduler.h: Removed. + * platform/graphics/chromium/cc/CCSchedulerStateMachine.cpp: Removed. + * platform/graphics/chromium/cc/CCSchedulerStateMachine.h: Removed. + * platform/graphics/chromium/cc/CCScopedTexture.cpp: Removed. + * platform/graphics/chromium/cc/CCScopedTexture.h: Removed. + * platform/graphics/chromium/cc/CCScopedThreadProxy.h: Removed. + * platform/graphics/chromium/cc/CCScrollbarAnimationController.cpp: Removed. + * platform/graphics/chromium/cc/CCScrollbarAnimationController.h: Removed. + * platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.cpp: Removed. + * platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.h: Removed. + * platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.cpp: Removed. + * platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.h: Removed. + * platform/graphics/chromium/cc/CCScrollbarGeometryStub.cpp: Removed. + * platform/graphics/chromium/cc/CCScrollbarGeometryStub.h: Removed. + * platform/graphics/chromium/cc/CCScrollbarLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCScrollbarLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCSettings.cpp: Removed. + * platform/graphics/chromium/cc/CCSettings.h: Removed. + * platform/graphics/chromium/cc/CCSharedQuadState.cpp: Removed. + * platform/graphics/chromium/cc/CCSharedQuadState.h: Removed. + * platform/graphics/chromium/cc/CCSingleThreadProxy.cpp: Removed. + * platform/graphics/chromium/cc/CCSingleThreadProxy.h: Removed. + * platform/graphics/chromium/cc/CCSolidColorDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCSolidColorDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCSolidColorLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCSolidColorLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCStreamVideoDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCStreamVideoDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCTexture.cpp: Removed. + * platform/graphics/chromium/cc/CCTexture.h: Removed. + * platform/graphics/chromium/cc/CCTextureDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCTextureDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCTextureLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCTextureLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCTextureUpdateController.cpp: Removed. + * platform/graphics/chromium/cc/CCTextureUpdateController.h: Removed. + * platform/graphics/chromium/cc/CCTextureUpdateQueue.cpp: Removed. + * platform/graphics/chromium/cc/CCTextureUpdateQueue.h: Removed. + * platform/graphics/chromium/cc/CCThread.h: Removed. + * platform/graphics/chromium/cc/CCThreadProxy.cpp: Removed. + * platform/graphics/chromium/cc/CCThreadProxy.h: Removed. + * platform/graphics/chromium/cc/CCThreadTask.h: Removed. + * platform/graphics/chromium/cc/CCTileDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCTileDrawQuad.h: Removed. + * platform/graphics/chromium/cc/CCTiledLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCTiledLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCTimeSource.h: Removed. + * platform/graphics/chromium/cc/CCTimer.cpp: Removed. + * platform/graphics/chromium/cc/CCTimer.h: Removed. + * platform/graphics/chromium/cc/CCTimingFunction.cpp: Removed. + * platform/graphics/chromium/cc/CCTimingFunction.h: Removed. + * platform/graphics/chromium/cc/CCVideoLayerImpl.cpp: Removed. + * platform/graphics/chromium/cc/CCVideoLayerImpl.h: Removed. + * platform/graphics/chromium/cc/CCYUVVideoDrawQuad.cpp: Removed. + * platform/graphics/chromium/cc/CCYUVVideoDrawQuad.h: Removed. + 2012-09-20 Tony Chang <tony@chromium.org> Implement absolutely positioned flex items diff --git a/Source/WebCore/Configurations/FeatureDefines.xcconfig b/Source/WebCore/Configurations/FeatureDefines.xcconfig index 44393b90e..5a32c82e3 100644 --- a/Source/WebCore/Configurations/FeatureDefines.xcconfig +++ b/Source/WebCore/Configurations/FeatureDefines.xcconfig @@ -97,6 +97,7 @@ ENABLE_LEGACY_NOTIFICATIONS_macosx_1070 = ; ENABLE_LEGACY_NOTIFICATIONS_macosx_1080 = ENABLE_LEGACY_NOTIFICATIONS; ENABLE_LEGACY_NOTIFICATIONS_macosx_1090 = ENABLE_LEGACY_NOTIFICATIONS; ENABLE_LEGACY_VENDOR_PREFIXES = ENABLE_LEGACY_VENDOR_PREFIXES; +ENABLE_LEGACY_WEB_AUDIO = ENABLE_LEGACY_WEB_AUDIO; ENABLE_LINK_PREFETCH = ; ENABLE_LINK_PRERENDER = ; ENABLE_MATHML = ENABLE_MATHML; @@ -141,4 +142,4 @@ ENABLE_WIDGET_REGION_macosx = ENABLE_WIDGET_REGION; ENABLE_WORKERS = ENABLE_WORKERS; ENABLE_XSLT = ENABLE_XSLT; -FEATURE_DEFINES = $(ENABLE_3D_RENDERING) $(ENABLE_ACCELERATED_2D_CANVAS) $(ENABLE_ANIMATION_API) $(ENABLE_BLOB) $(ENABLE_CHANNEL_MESSAGING) $(ENABLE_CSP_NEXT) $(ENABLE_CSS_BOX_DECORATION_BREAK) $(ENABLE_CSS_EXCLUSIONS) $(ENABLE_CSS_FILTERS) $(ENABLE_CSS_HIERARCHIES) $(ENABLE_CSS_IMAGE_ORIENTATION) $(ENABLE_CSS_IMAGE_RESOLUTION) $(ENABLE_CSS_REGIONS) $(ENABLE_CSS_SHADERS) $(ENABLE_CSS_COMPOSITING) $(ENABLE_CSS_STICKY_POSITION) $(ENABLE_CSS_VARIABLES) $(ENABLE_CSS3_TEXT_DECORATION) $(ENABLE_CUSTOM_SCHEME_HANDLER) $(ENABLE_DASHBOARD_SUPPORT) $(ENABLE_DATALIST_ELEMENT) $(ENABLE_DATA_TRANSFER_ITEMS) $(ENABLE_DETAILS_ELEMENT) $(ENABLE_DEVICE_ORIENTATION) $(ENABLE_DIALOG_ELEMENT) $(ENABLE_DIRECTORY_UPLOAD) $(ENABLE_FILE_SYSTEM) $(ENABLE_FILTERS) $(ENABLE_FULLSCREEN_API) $(ENABLE_GAMEPAD) $(ENABLE_GEOLOCATION) $(ENABLE_HIGH_DPI_CANVAS) $(ENABLE_ICONDATABASE) $(ENABLE_IFRAME_SEAMLESS) $(ENABLE_INDEXED_DATABASE) $(ENABLE_INPUT_SPEECH) $(ENABLE_INPUT_TYPE_COLOR) $(ENABLE_INPUT_TYPE_DATE) $(ENABLE_INPUT_TYPE_DATETIME) $(ENABLE_INPUT_TYPE_DATETIMELOCAL) $(ENABLE_INPUT_TYPE_MONTH) $(ENABLE_INPUT_TYPE_TIME) $(ENABLE_INPUT_TYPE_WEEK) $(ENABLE_JAVASCRIPT_DEBUGGER) $(ENABLE_LEGACY_CSS_VENDOR_PREFIXES) $(ENABLE_LEGACY_NOTIFICATIONS) $(ENABLE_LEGACY_VENDOR_PREFIXES) $(ENABLE_LINK_PREFETCH) $(ENABLE_LINK_PRERENDER) $(ENABLE_MATHML) $(ENABLE_MEDIA_SOURCE) $(ENABLE_MEDIA_STATISTICS) $(ENABLE_METER_ELEMENT) $(ENABLE_MHTML) $(ENABLE_MICRODATA) $(ENABLE_MUTATION_OBSERVERS) $(ENABLE_NAVIGATOR_CONTENT_UTILS) $(ENABLE_NOTIFICATIONS) $(ENABLE_PAGE_VISIBILITY_API) $(ENABLE_PROGRESS_ELEMENT) $(ENABLE_QUOTA) $(ENABLE_REQUEST_ANIMATION_FRAME) $(ENABLE_SCRIPTED_SPEECH) $(ENABLE_SHADOW_DOM) $(ENABLE_SHARED_WORKERS) $(ENABLE_SQL_DATABASE) $(ENABLE_STYLE_SCOPED) $(ENABLE_SVG) $(ENABLE_SVG_DOM_OBJC_BINDINGS) $(ENABLE_SVG_FONTS) $(ENABLE_TEXT_AUTOSIZING) $(ENABLE_TEXT_NOTIFICATIONS_ONLY) $(ENABLE_TOUCH_ICON_LOADING) $(ENABLE_UNDO_MANAGER) $(ENABLE_VIDEO) $(ENABLE_VIDEO_TRACK) $(ENABLE_WEBGL) $(ENABLE_WEB_AUDIO) $(ENABLE_WEB_SOCKETS) $(ENABLE_WEB_TIMING) $(ENABLE_WIDGET_REGION) $(ENABLE_WORKERS) $(ENABLE_XSLT); +FEATURE_DEFINES = $(ENABLE_3D_RENDERING) $(ENABLE_ACCELERATED_2D_CANVAS) $(ENABLE_ANIMATION_API) $(ENABLE_BLOB) $(ENABLE_CHANNEL_MESSAGING) $(ENABLE_CSP_NEXT) $(ENABLE_CSS_BOX_DECORATION_BREAK) $(ENABLE_CSS_EXCLUSIONS) $(ENABLE_CSS_FILTERS) $(ENABLE_CSS_HIERARCHIES) $(ENABLE_CSS_IMAGE_ORIENTATION) $(ENABLE_CSS_IMAGE_RESOLUTION) $(ENABLE_CSS_REGIONS) $(ENABLE_CSS_SHADERS) $(ENABLE_CSS_COMPOSITING) $(ENABLE_CSS_STICKY_POSITION) $(ENABLE_CSS_VARIABLES) $(ENABLE_CSS3_TEXT_DECORATION) $(ENABLE_CUSTOM_SCHEME_HANDLER) $(ENABLE_DASHBOARD_SUPPORT) $(ENABLE_DATALIST_ELEMENT) $(ENABLE_DATA_TRANSFER_ITEMS) $(ENABLE_DETAILS_ELEMENT) $(ENABLE_DEVICE_ORIENTATION) $(ENABLE_DIALOG_ELEMENT) $(ENABLE_DIRECTORY_UPLOAD) $(ENABLE_FILE_SYSTEM) $(ENABLE_FILTERS) $(ENABLE_FULLSCREEN_API) $(ENABLE_GAMEPAD) $(ENABLE_GEOLOCATION) $(ENABLE_HIGH_DPI_CANVAS) $(ENABLE_ICONDATABASE) $(ENABLE_IFRAME_SEAMLESS) $(ENABLE_INDEXED_DATABASE) $(ENABLE_INPUT_SPEECH) $(ENABLE_INPUT_TYPE_COLOR) $(ENABLE_INPUT_TYPE_DATE) $(ENABLE_INPUT_TYPE_DATETIME) $(ENABLE_INPUT_TYPE_DATETIMELOCAL) $(ENABLE_INPUT_TYPE_MONTH) $(ENABLE_INPUT_TYPE_TIME) $(ENABLE_INPUT_TYPE_WEEK) $(ENABLE_JAVASCRIPT_DEBUGGER) $(ENABLE_LEGACY_CSS_VENDOR_PREFIXES) $(ENABLE_LEGACY_NOTIFICATIONS) $(ENABLE_LEGACY_VENDOR_PREFIXES) $(ENABLE_LEGACY_WEB_AUDIO) $(ENABLE_LINK_PREFETCH) $(ENABLE_LINK_PRERENDER) $(ENABLE_MATHML) $(ENABLE_MEDIA_SOURCE) $(ENABLE_MEDIA_STATISTICS) $(ENABLE_METER_ELEMENT) $(ENABLE_MHTML) $(ENABLE_MICRODATA) $(ENABLE_MUTATION_OBSERVERS) $(ENABLE_NAVIGATOR_CONTENT_UTILS) $(ENABLE_NOTIFICATIONS) $(ENABLE_PAGE_VISIBILITY_API) $(ENABLE_PROGRESS_ELEMENT) $(ENABLE_QUOTA) $(ENABLE_REQUEST_ANIMATION_FRAME) $(ENABLE_SCRIPTED_SPEECH) $(ENABLE_SHADOW_DOM) $(ENABLE_SHARED_WORKERS) $(ENABLE_SQL_DATABASE) $(ENABLE_STYLE_SCOPED) $(ENABLE_SVG) $(ENABLE_SVG_DOM_OBJC_BINDINGS) $(ENABLE_SVG_FONTS) $(ENABLE_TEXT_AUTOSIZING) $(ENABLE_TEXT_NOTIFICATIONS_ONLY) $(ENABLE_TOUCH_ICON_LOADING) $(ENABLE_UNDO_MANAGER) $(ENABLE_VIDEO) $(ENABLE_VIDEO_TRACK) $(ENABLE_WEBGL) $(ENABLE_WEB_AUDIO) $(ENABLE_WEB_SOCKETS) $(ENABLE_WEB_TIMING) $(ENABLE_WIDGET_REGION) $(ENABLE_WORKERS) $(ENABLE_XSLT); diff --git a/Source/WebCore/Configurations/Version.xcconfig b/Source/WebCore/Configurations/Version.xcconfig index 64d233886..b861f70e7 100644 --- a/Source/WebCore/Configurations/Version.xcconfig +++ b/Source/WebCore/Configurations/Version.xcconfig @@ -22,7 +22,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. MAJOR_VERSION = 537; -MINOR_VERSION = 11; +MINOR_VERSION = 12; TINY_VERSION = 0; FULL_VERSION = $(MAJOR_VERSION).$(MINOR_VERSION); diff --git a/Source/WebCore/Configurations/WebCoreTestSupport.xcconfig b/Source/WebCore/Configurations/WebCoreTestSupport.xcconfig index 81aeaa4f2..ad669ee47 100644 --- a/Source/WebCore/Configurations/WebCoreTestSupport.xcconfig +++ b/Source/WebCore/Configurations/WebCoreTestSupport.xcconfig @@ -45,3 +45,4 @@ PRODUCT_NAME = WebCoreTestSupport; EXECUTABLE_PREFIX = lib; EXPORTED_SYMBOLS_FILE = ; OTHER_LDFLAGS = ; +SECTORDER_FLAGS = ; diff --git a/Source/WebCore/English.lproj/localizedStrings.js b/Source/WebCore/English.lproj/localizedStrings.js index fad1f2a67..7be257bfc 100644 --- a/Source/WebCore/English.lproj/localizedStrings.js +++ b/Source/WebCore/English.lproj/localizedStrings.js @@ -129,14 +129,10 @@ localizedStrings["Continue to Here"] = "Continue to Here"; localizedStrings["Continue to here"] = "Continue to here"; localizedStrings["Continue"] = "Continue"; localizedStrings["Copy as HTML"] = "Copy as HTML"; -localizedStrings["Copy entry as HAR"] = "Copy entry as HAR"; -localizedStrings["Copy Entry as HAR"] = "Copy Entry as HAR"; -localizedStrings["Save entry as HAR"] = "Save entry as HAR"; -localizedStrings["Save Entry as HAR"] = "Save Entry as HAR"; localizedStrings["Copy all as HAR"] = "Copy all as HAR"; localizedStrings["Copy All as HAR"] = "Copy All as HAR"; -localizedStrings["Save all as HAR"] = "Save all as HAR"; -localizedStrings["Save All as HAR"] = "Save All as HAR"; +localizedStrings["Save as HAR with content"] = "Save as HAR with content"; +localizedStrings["Save as HAR with Content"] = "Save as HAR with Content"; localizedStrings["Copy link address"] = "Copy link address"; localizedStrings["Copy Link Address"] = "Copy Link Address"; localizedStrings["Copy request headers"] = "Copy request headers"; @@ -749,3 +745,5 @@ localizedStrings["Layout forced"] = "Layout forced"; localizedStrings["Paused on assertion."] = "Paused on assertion."; localizedStrings["%s (%s%s)"] = "%s (%s%s)"; localizedStrings["Running audit"] = "Running audit"; +localizedStrings["Collecting content…"] = "Collecting content…"; +localizedStrings["Writing file…"] = "Writing file…"; diff --git a/Source/WebCore/GNUmakefile.features.am b/Source/WebCore/GNUmakefile.features.am index 07c941834..75aea9560 100644 --- a/Source/WebCore/GNUmakefile.features.am +++ b/Source/WebCore/GNUmakefile.features.am @@ -48,6 +48,7 @@ feature_defines_defaults += \ ENABLE_LEGACY_CSS_VENDOR_PREFIXES=0 \ ENABLE_LEGACY_NOTIFICATIONS=0 \ ENABLE_LEGACY_VENDOR_PREFIXES=1 \ + ENABLE_LEGACY_WEB_AUDIO=1 \ ENABLE_LEGACY_WEBKIT_BLOB_BUILDER=1 \ ENABLE_LINK_PREFETCH=1 \ ENABLE_LINK_PRERENDER=0 \ diff --git a/Source/WebCore/Modules/vibration/Vibration.h b/Source/WebCore/Modules/vibration/Vibration.h index 361586bc1..3d110b5c4 100644 --- a/Source/WebCore/Modules/vibration/Vibration.h +++ b/Source/WebCore/Modules/vibration/Vibration.h @@ -28,8 +28,6 @@ namespace WebCore { -class Navigator; -class Page; class VibrationClient; class Vibration : public Supplement<Page> { diff --git a/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.cpp b/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.cpp index 44257b639..4f7432572 100644 --- a/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.cpp +++ b/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.cpp @@ -346,7 +346,7 @@ unsigned AudioBufferSourceNode::numberOfChannels() return output(0)->numberOfChannels(); } -void AudioBufferSourceNode::noteGrainOn(double when, double grainOffset, double grainDuration) +void AudioBufferSourceNode::startGrain(double when, double grainOffset, double grainDuration) { ASSERT(isMainThread()); @@ -383,6 +383,13 @@ void AudioBufferSourceNode::noteGrainOn(double when, double grainOffset, double m_playbackState = SCHEDULED_STATE; } +#if ENABLE(LEGACY_WEB_AUDIO) +void AudioBufferSourceNode::noteGrainOn(double when, double grainOffset, double grainDuration) +{ + startGrain(when, grainOffset, grainDuration); +} +#endif + double AudioBufferSourceNode::totalPitchRate() { double dopplerRate = 1.0; diff --git a/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.h b/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.h index 3899252df..24736e165 100644 --- a/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.h +++ b/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.h @@ -62,8 +62,11 @@ public: unsigned numberOfChannels(); // Play-state - // noteOn(), noteGrainOn(), and noteOff() must all be called from the main thread. + void startGrain(double when, double grainOffset, double grainDuration); + +#if ENABLE(LEGACY_WEB_AUDIO) void noteGrainOn(double when, double grainOffset, double grainDuration); +#endif // Note: the attribute was originally exposed as .looping, but to be more consistent in naming with <audio> // and with how it's described in the specification, the proper attribute name is .loop diff --git a/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.idl b/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.idl index ae6af93e8..41596927a 100644 --- a/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.idl +++ b/Source/WebCore/Modules/webaudio/AudioBufferSourceNode.idl @@ -44,8 +44,14 @@ module audio { attribute boolean loop; // This is the proper attribute name from the specification. attribute boolean looping; // This is an alias for the .loop attribute for backwards compatibility. - void noteOn(in double when); - void noteGrainOn(in double when, in double grainOffset, in double grainDuration); + [V8MeasureAs=WebAudioStart] void start(in double when); + [V8MeasureAs=WebAudioStart] [ImplementedAs=startGrain] void start(in double when, in double grainOffset, in double grainDuration); + void stop(in double when); + +#if defined(ENABLE_LEGACY_WEB_AUDIO) && ENABLE_LEGACY_WEB_AUDIO + [V8MeasureAs=LegacyWebAudioNoteOn] void noteOn(in double when); + [V8MeasureAs=LegacyWebAudioNoteOn] void noteGrainOn(in double when, in double grainOffset, in double grainDuration); void noteOff(in double when); +#endif }; } diff --git a/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.cpp b/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.cpp index ec39e1988..d78bf797c 100644 --- a/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.cpp +++ b/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.cpp @@ -128,7 +128,7 @@ void AudioScheduledSourceNode::updateSchedulingInfo(size_t quantumFrameSize, return; } -void AudioScheduledSourceNode::noteOn(double when) +void AudioScheduledSourceNode::start(double when) { ASSERT(isMainThread()); if (m_playbackState != UNSCHEDULED_STATE) @@ -138,7 +138,7 @@ void AudioScheduledSourceNode::noteOn(double when) m_playbackState = SCHEDULED_STATE; } -void AudioScheduledSourceNode::noteOff(double when) +void AudioScheduledSourceNode::stop(double when) { ASSERT(isMainThread()); if (!(m_playbackState == SCHEDULED_STATE || m_playbackState == PLAYING_STATE)) @@ -148,6 +148,18 @@ void AudioScheduledSourceNode::noteOff(double when) m_endTime = when; } +#if ENABLE(LEGACY_WEB_AUDIO) +void AudioScheduledSourceNode::noteOn(double when) +{ + start(when); +} + +void AudioScheduledSourceNode::noteOff(double when) +{ + stop(when); +} +#endif + void AudioScheduledSourceNode::finish() { if (m_playbackState != FINISHED_STATE) { diff --git a/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.h b/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.h index 7a1dcd2ad..0a4502ec9 100644 --- a/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.h +++ b/Source/WebCore/Modules/webaudio/AudioScheduledSourceNode.h @@ -57,8 +57,13 @@ public: AudioScheduledSourceNode(AudioContext*, float sampleRate); // Scheduling. + void start(double when); + void stop(double when); + +#if ENABLE(LEGACY_WEB_AUDIO) void noteOn(double when); void noteOff(double when); +#endif unsigned short playbackState() const { return static_cast<unsigned short>(m_playbackState); } bool isPlayingOrScheduled() const { return m_playbackState == PLAYING_STATE || m_playbackState == SCHEDULED_STATE; } diff --git a/Source/WebCore/Modules/webaudio/BiquadDSPKernel.cpp b/Source/WebCore/Modules/webaudio/BiquadDSPKernel.cpp index cfed1da4d..a0611dcd4 100644 --- a/Source/WebCore/Modules/webaudio/BiquadDSPKernel.cpp +++ b/Source/WebCore/Modules/webaudio/BiquadDSPKernel.cpp @@ -47,8 +47,12 @@ void BiquadDSPKernel::updateCoefficientsIfNecessary(bool useSmoothing, bool forc double value1; double value2; double gain; - - if (useSmoothing) { + + if (biquadProcessor()->hasSampleAccurateValues()) { + value1 = biquadProcessor()->parameter1()->finalValue(); + value2 = biquadProcessor()->parameter2()->finalValue(); + gain = biquadProcessor()->parameter3()->finalValue(); + } else if (useSmoothing) { value1 = biquadProcessor()->parameter1()->smoothedValue(); value2 = biquadProcessor()->parameter2()->smoothedValue(); gain = biquadProcessor()->parameter3()->smoothedValue(); diff --git a/Source/WebCore/Modules/webaudio/BiquadProcessor.cpp b/Source/WebCore/Modules/webaudio/BiquadProcessor.cpp index e8677d29e..3ae02636a 100644 --- a/Source/WebCore/Modules/webaudio/BiquadProcessor.cpp +++ b/Source/WebCore/Modules/webaudio/BiquadProcessor.cpp @@ -68,21 +68,27 @@ void BiquadProcessor::checkForDirtyCoefficients() // The BiquadDSPKernel objects rely on this value to see if they need to re-compute their internal filter coefficients. m_filterCoefficientsDirty = false; + m_hasSampleAccurateValues = false; - if (m_hasJustReset) { - // Snap to exact values first time after reset, then smooth for subsequent changes. - m_parameter1->resetSmoothedValue(); - m_parameter2->resetSmoothedValue(); - m_parameter3->resetSmoothedValue(); + if (m_parameter1->hasSampleAccurateValues() || m_parameter2->hasSampleAccurateValues() || m_parameter3->hasSampleAccurateValues()) { m_filterCoefficientsDirty = true; - m_hasJustReset = false; + m_hasSampleAccurateValues = true; } else { - // Smooth all of the filter parameters. If they haven't yet converged to their target value then mark coefficients as dirty. - bool isStable1 = m_parameter1->smooth(); - bool isStable2 = m_parameter2->smooth(); - bool isStable3 = m_parameter3->smooth(); - if (!(isStable1 && isStable2 && isStable3)) + if (m_hasJustReset) { + // Snap to exact values first time after reset, then smooth for subsequent changes. + m_parameter1->resetSmoothedValue(); + m_parameter2->resetSmoothedValue(); + m_parameter3->resetSmoothedValue(); m_filterCoefficientsDirty = true; + m_hasJustReset = false; + } else { + // Smooth all of the filter parameters. If they haven't yet converged to their target value then mark coefficients as dirty. + bool isStable1 = m_parameter1->smooth(); + bool isStable2 = m_parameter2->smooth(); + bool isStable3 = m_parameter3->smooth(); + if (!(isStable1 && isStable2 && isStable3)) + m_filterCoefficientsDirty = true; + } } } diff --git a/Source/WebCore/Modules/webaudio/BiquadProcessor.h b/Source/WebCore/Modules/webaudio/BiquadProcessor.h index 408294402..9c3b9682d 100644 --- a/Source/WebCore/Modules/webaudio/BiquadProcessor.h +++ b/Source/WebCore/Modules/webaudio/BiquadProcessor.h @@ -67,6 +67,7 @@ public: void checkForDirtyCoefficients(); bool filterCoefficientsDirty() const { return m_filterCoefficientsDirty; } + bool hasSampleAccurateValues() const { return m_hasSampleAccurateValues; } AudioParam* parameter1() { return m_parameter1.get(); } AudioParam* parameter2() { return m_parameter2.get(); } @@ -84,6 +85,9 @@ private: // so DSP kernels know when to re-compute coefficients bool m_filterCoefficientsDirty; + + // Set to true if any of the filter parameters are sample-accurate. + bool m_hasSampleAccurateValues; }; } // namespace WebCore diff --git a/Source/WebCore/Modules/webaudio/Oscillator.idl b/Source/WebCore/Modules/webaudio/Oscillator.idl index f8e2a8892..452967f28 100644 --- a/Source/WebCore/Modules/webaudio/Oscillator.idl +++ b/Source/WebCore/Modules/webaudio/Oscillator.idl @@ -50,8 +50,14 @@ module audio { readonly attribute AudioParam frequency; // in Hertz readonly attribute AudioParam detune; // in Cents + void start(in double when); + void stop(in double when); + +#if defined(ENABLE_LEGACY_WEB_AUDIO) && ENABLE_LEGACY_WEB_AUDIO void noteOn(in double when); void noteOff(in double when); +#endif + void setWaveTable(in WaveTable waveTable); }; diff --git a/Source/WebCore/Modules/websockets/WebSocketChannel.cpp b/Source/WebCore/Modules/websockets/WebSocketChannel.cpp index 8953650a3..371ce2a71 100644 --- a/Source/WebCore/Modules/websockets/WebSocketChannel.cpp +++ b/Source/WebCore/Modules/websockets/WebSocketChannel.cpp @@ -73,8 +73,6 @@ const double TCPMaximumSegmentLifetime = 2 * 60.0; WebSocketChannel::WebSocketChannel(Document* document, WebSocketChannelClient* client) : m_document(document) , m_client(client) - , m_buffer(0) - , m_bufferSize(0) , m_resumeTimer(this, &WebSocketChannel::resumeTimerFired) , m_suspended(false) , m_closing(false) @@ -97,7 +95,6 @@ WebSocketChannel::WebSocketChannel(Document* document, WebSocketChannelClient* c WebSocketChannel::~WebSocketChannel() { - fastFree(m_buffer); } void WebSocketChannel::connect(const KURL& url, const String& protocol) @@ -206,8 +203,8 @@ void WebSocketChannel::fail(const String& reason) // once the WebSocket connection is failed (section 7.1.7). RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference. m_shouldDiscardReceivedData = true; - if (m_buffer) - skipBuffer(m_bufferSize); // Save memory. + if (!m_buffer.isEmpty()) + skipBuffer(m_buffer.size()); // Save memory. m_deflateFramer.didFail(); m_hasContinuousFrame = false; m_continuousFrameData.clear(); @@ -238,7 +235,7 @@ void WebSocketChannel::suspend() void WebSocketChannel::resume() { m_suspended = false; - if ((m_buffer || m_closed) && m_client && !m_resumeTimer.isActive()) + if ((!m_buffer.isEmpty() || m_closed) && m_client && !m_resumeTimer.isActive()) m_resumeTimer.startOneShot(0); } @@ -312,7 +309,7 @@ void WebSocketChannel::didReceiveSocketStreamData(SocketStreamHandle* handle, co fail("Ran out of memory while receiving WebSocket data."); return; } - while (!m_suspended && m_client && m_buffer) + while (!m_suspended && m_client && !m_buffer.isEmpty()) if (!processBuffer()) break; } @@ -392,55 +389,41 @@ void WebSocketChannel::didFail(int errorCode) bool WebSocketChannel::appendToBuffer(const char* data, size_t len) { - size_t newBufferSize = m_bufferSize + len; - if (newBufferSize < m_bufferSize) { - LOG(Network, "WebSocket buffer overflow (%lu+%lu)", static_cast<unsigned long>(m_bufferSize), static_cast<unsigned long>(len)); + size_t newBufferSize = m_buffer.size() + len; + if (newBufferSize < m_buffer.size()) { + LOG(Network, "WebSocket buffer overflow (%lu+%lu)", static_cast<unsigned long>(m_buffer.size()), static_cast<unsigned long>(len)); return false; } - char* newBuffer = 0; - if (!tryFastMalloc(newBufferSize).getValue(newBuffer)) - return false; - - if (m_buffer) - memcpy(newBuffer, m_buffer, m_bufferSize); - memcpy(newBuffer + m_bufferSize, data, len); - fastFree(m_buffer); - m_buffer = newBuffer; - m_bufferSize = newBufferSize; + m_buffer.append(data, len); return true; } void WebSocketChannel::skipBuffer(size_t len) { - ASSERT(len <= m_bufferSize); - m_bufferSize -= len; - if (!m_bufferSize) { - fastFree(m_buffer); - m_buffer = 0; - return; - } - memmove(m_buffer, m_buffer + len, m_bufferSize); + ASSERT(len <= m_buffer.size()); + memmove(m_buffer.data(), m_buffer.data() + len, m_buffer.size() - len); + m_buffer.resize(m_buffer.size() - len); } bool WebSocketChannel::processBuffer() { ASSERT(!m_suspended); ASSERT(m_client); - ASSERT(m_buffer); - LOG(Network, "WebSocketChannel %p processBuffer %lu", this, static_cast<unsigned long>(m_bufferSize)); + ASSERT(!m_buffer.isEmpty()); + LOG(Network, "WebSocketChannel %p processBuffer %lu", this, static_cast<unsigned long>(m_buffer.size())); if (m_shouldDiscardReceivedData) return false; if (m_receivedClosingHandshake) { - skipBuffer(m_bufferSize); + skipBuffer(m_buffer.size()); return false; } RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference. if (m_handshake->mode() == WebSocketHandshake::Incomplete) { - int headerLength = m_handshake->readServerHandshake(m_buffer, m_bufferSize); + int headerLength = m_handshake->readServerHandshake(m_buffer.data(), m_buffer.size()); if (headerLength <= 0) return false; if (m_handshake->mode() == WebSocketHandshake::Connected) { @@ -456,8 +439,8 @@ bool WebSocketChannel::processBuffer() LOG(Network, "WebSocketChannel %p connected", this); skipBuffer(headerLength); m_client->didConnect(); - LOG(Network, "remaining in read buf %lu", static_cast<unsigned long>(m_bufferSize)); - return m_buffer; + LOG(Network, "remaining in read buf %lu", static_cast<unsigned long>(m_buffer.size())); + return !m_buffer.isEmpty(); } ASSERT(m_handshake->mode() == WebSocketHandshake::Failed); LOG(Network, "WebSocketChannel %p connection failed", this); @@ -477,7 +460,7 @@ void WebSocketChannel::resumeTimerFired(Timer<WebSocketChannel>* timer) ASSERT_UNUSED(timer, timer == &m_resumeTimer); RefPtr<WebSocketChannel> protect(this); // The client can close the channel, potentially removing the last reference. - while (!m_suspended && m_client && m_buffer) + while (!m_suspended && m_client && !m_buffer.isEmpty()) if (!processBuffer()) break; if (!m_suspended && m_client && m_closed && m_handle) @@ -517,12 +500,12 @@ void WebSocketChannel::closingTimerFired(Timer<WebSocketChannel>* timer) bool WebSocketChannel::processFrame() { - ASSERT(m_buffer); + ASSERT(!m_buffer.isEmpty()); WebSocketFrame frame; const char* frameEnd; String errorString; - WebSocketFrame::ParseFrameResult result = WebSocketFrame::parseFrame(m_buffer, m_bufferSize, frame, frameEnd, errorString); + WebSocketFrame::ParseFrameResult result = WebSocketFrame::parseFrame(m_buffer.data(), m_buffer.size(), frame, frameEnd, errorString); if (result == WebSocketFrame::FrameIncomplete) return false; if (result == WebSocketFrame::FrameError) { @@ -530,8 +513,8 @@ bool WebSocketChannel::processFrame() return false; } - ASSERT(m_buffer < frameEnd); - ASSERT(frameEnd <= m_buffer + m_bufferSize); + ASSERT(m_buffer.data() < frameEnd); + ASSERT(frameEnd <= m_buffer.data() + m_buffer.size()); OwnPtr<InflateResultHolder> inflateResult = m_deflateFramer.inflate(frame); if (!inflateResult->succeeded()) { @@ -585,7 +568,7 @@ bool WebSocketChannel::processFrame() return false; } m_continuousFrameData.append(frame.payload, frame.payloadLength); - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); if (frame.final) { // onmessage handler may eventually call the other methods of this channel, // so we should pretend that we have finished to read this frame and @@ -617,7 +600,7 @@ bool WebSocketChannel::processFrame() message = String::fromUTF8(frame.payload, frame.payloadLength); else message = ""; - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); if (message.isNull()) fail("Could not decode a text frame as UTF-8."); else @@ -627,7 +610,7 @@ bool WebSocketChannel::processFrame() m_continuousFrameOpCode = WebSocketFrame::OpCodeText; ASSERT(m_continuousFrameData.isEmpty()); m_continuousFrameData.append(frame.payload, frame.payloadLength); - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); } break; @@ -635,14 +618,14 @@ bool WebSocketChannel::processFrame() if (frame.final) { OwnPtr<Vector<char> > binaryData = adoptPtr(new Vector<char>(frame.payloadLength)); memcpy(binaryData->data(), frame.payload, frame.payloadLength); - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); m_client->didReceiveBinaryData(binaryData.release()); } else { m_hasContinuousFrame = true; m_continuousFrameOpCode = WebSocketFrame::OpCodeBinary; ASSERT(m_continuousFrameData.isEmpty()); m_continuousFrameData.append(frame.payload, frame.payloadLength); - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); } break; @@ -667,7 +650,7 @@ bool WebSocketChannel::processFrame() m_closeEventReason = String::fromUTF8(&frame.payload[2], frame.payloadLength - 2); else m_closeEventReason = ""; - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); m_receivedClosingHandshake = true; startClosingHandshake(m_closeEventCode, m_closeEventReason); if (m_closing) { @@ -678,22 +661,22 @@ bool WebSocketChannel::processFrame() case WebSocketFrame::OpCodePing: enqueueRawFrame(WebSocketFrame::OpCodePong, frame.payload, frame.payloadLength); - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); break; case WebSocketFrame::OpCodePong: // A server may send a pong in response to our ping, or an unsolicited pong which is not associated with // any specific ping. Either way, there's nothing to do on receipt of pong. - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); break; default: ASSERT_NOT_REACHED(); - skipBuffer(frameEnd - m_buffer); + skipBuffer(frameEnd - m_buffer.data()); break; } - return m_buffer; + return !m_buffer.isEmpty(); } void WebSocketChannel::enqueueTextFrame(const CString& string) diff --git a/Source/WebCore/Modules/websockets/WebSocketChannel.h b/Source/WebCore/Modules/websockets/WebSocketChannel.h index 3dde648ec..170ab183a 100644 --- a/Source/WebCore/Modules/websockets/WebSocketChannel.h +++ b/Source/WebCore/Modules/websockets/WebSocketChannel.h @@ -195,8 +195,7 @@ private: WebSocketChannelClient* m_client; OwnPtr<WebSocketHandshake> m_handshake; RefPtr<SocketStreamHandle> m_handle; - char* m_buffer; - size_t m_bufferSize; + Vector<char> m_buffer; Timer<WebSocketChannel> m_resumeTimer; bool m_suspended; diff --git a/Source/WebCore/PlatformBlackBerry.cmake b/Source/WebCore/PlatformBlackBerry.cmake index 53c2d3565..987202cde 100644 --- a/Source/WebCore/PlatformBlackBerry.cmake +++ b/Source/WebCore/PlatformBlackBerry.cmake @@ -42,6 +42,7 @@ LIST(APPEND WebCore_SOURCES # Skia font backend sources LIST(APPEND WebCore_SOURCES + platform/graphics/blackberry/FontCacheBlackberry.cpp platform/graphics/blackberry/skia/PlatformBridge.cpp platform/graphics/harfbuzz/ComplexTextControllerHarfBuzz.cpp platform/graphics/harfbuzz/FontHarfBuzz.cpp @@ -60,6 +61,7 @@ LIST(APPEND WebCore_SOURCES bindings/cpp/WebDOMString.cpp bindings/cpp/WebExceptionHandler.cpp platform/blackberry/CookieDatabaseBackingStore/CookieDatabaseBackingStore.cpp + platform/blackberry/AuthenticationChallengeManager.cpp platform/blackberry/CookieManager.cpp platform/blackberry/CookieMap.cpp platform/blackberry/CookieParser.cpp diff --git a/Source/WebCore/Resources/pagepopups/calendarPicker.css b/Source/WebCore/Resources/pagepopups/calendarPicker.css index 518a25ad1..8133d71b0 100644 --- a/Source/WebCore/Resources/pagepopups/calendarPicker.css +++ b/Source/WebCore/Resources/pagepopups/calendarPicker.css @@ -40,14 +40,13 @@ body { outline: none; } -#main { +.calendar-picker { 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; - whitespace: nowrap; - /* width is reset in the JS code. */ + white-space: nowrap; width: 500px; } diff --git a/Source/WebCore/Resources/pagepopups/calendarPicker.js b/Source/WebCore/Resources/pagepopups/calendarPicker.js index 8acc42b28..db984a538 100644 --- a/Source/WebCore/Resources/pagepopups/calendarPicker.js +++ b/Source/WebCore/Resources/pagepopups/calendarPicker.js @@ -72,7 +72,8 @@ var ClassNames = { */ var global = { argumentsReceived: false, - params: null + params: null, + picker: null }; // ---------------------------------------------------------------- @@ -239,25 +240,25 @@ function handleArgumentsTimeout() { } /** - * @param {!Object} args + * @param {!Object} config * @return {?string} An error message, or null if the argument has no errors. */ -function validateArguments(args) { - if (!args.monthLabels) +CalendarPicker.validateConfig = function(config) { + if (!config.monthLabels) return "No monthLabels."; - if (args.monthLabels.length != 12) + if (config.monthLabels.length != 12) return "monthLabels is not an array with 12 elements."; - if (!args.dayLabels) + if (!config.dayLabels) return "No dayLabels."; - if (args.dayLabels.length != 7) + if (config.dayLabels.length != 7) return "dayLabels is not an array with 7 elements."; - if (!args.clearLabel) + if (!config.clearLabel) return "No clearLabel."; - if (!args.todayLabel) + if (!config.todayLabel) return "No todayLabel."; - if (args.weekStartDay) { - if (args.weekStartDay < 0 || args.weekStartDay > 6) - return "Invalid weekStartDay: " + args.weekStartDay; + if (config.weekStartDay) { + if (config.weekStartDay < 0 || config.weekStartDay > 6) + return "Invalid weekStartDay: " + config.weekStartDay; } return null; } @@ -266,26 +267,38 @@ function validateArguments(args) { * @param {!Object} args */ function initialize(args) { - var errorString = validateArguments(args); + var errorString = CalendarPicker.validateConfig(args); + if (args.suggestionValues) + errorString = errorString || SuggestionPicker.validateConfig(args) if (errorString) { var main = $("main"); main.textContent = "Internal error: " + errorString; resizeWindow(main.offsetWidth, main.offsetHeight); } else { global.params = args; - openCalendarPicker(); + if (global.params.suggestionValues && global.params.suggestionValues.length) + openSuggestionPicker(); + else + openCalendarPicker(); } } -function resetMain() { +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() { - resetMain(); - new CalendarPicker($("main"), global.params); + closePicker(); + global.picker = new CalendarPicker($("main"), global.params); }; /** @@ -295,6 +308,7 @@ function openCalendarPicker() { */ function CalendarPicker(element, config) { Picker.call(this, element, config); + this._element.classList.add("calendar-picker"); // We assume this._config.min is a valid date. this.minimumDate = (typeof this._config.min !== "undefined") ? parseDateString(this._config.min) : CalendarPicker.MinimumPossibleDate; // We assume this._config.max is a valid date. @@ -311,7 +325,8 @@ function CalendarPicker(element, config) { initialDate = this.maximumDate; this.daysTable.selectDate(initialDate); this.fixWindowSize(); - document.body.addEventListener("keydown", this._handleBodyKeyDown.bind(this), false); + this._handleBodyKeyDownBound = this._handleBodyKeyDown.bind(this); + document.body.addEventListener("keydown", this._handleBodyKeyDownBound, false); } CalendarPicker.prototype = Object.create(Picker.prototype); @@ -321,6 +336,10 @@ CalendarPicker.MaximumPossibleDate = new Date(8640000000000000.0); // See WebCore/html/DateInputType.cpp. CalendarPicker.BaseStep = 86400000; +CalendarPicker.prototype.cleanup = function() { + document.body.removeEventListener("keydown", this._handleBodyKeyDownBound, false); +}; + CalendarPicker.prototype._layout = function() { this._element.style.direction = global.params.isRTL ? "rtl" : "ltr"; this.yearMonthController.attachTo(this._element); diff --git a/Source/WebCore/Resources/pagepopups/pickerCommon.js b/Source/WebCore/Resources/pagepopups/pickerCommon.js index 852332160..619f2ee76 100644 --- a/Source/WebCore/Resources/pagepopups/pickerCommon.js +++ b/Source/WebCore/Resources/pagepopups/pickerCommon.js @@ -1,3 +1,4 @@ +"use strict"; /* * Copyright (C) 2012 Google Inc. All rights reserved. * @@ -57,6 +58,9 @@ function resizeWindow(width, height) { } } +/** + * @return {!number} + */ function getScrollbarWidth() { if (typeof window.scrollbarWidth === "undefined") { var scrollDiv = document.createElement("div"); @@ -72,6 +76,19 @@ function getScrollbarWidth() { } /** + * @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 @@ -104,3 +121,5 @@ Picker.prototype.handleCancel = function() { Picker.prototype.chooseOtherColor = function() { window.pagePopupController.setValueAndClosePopup(Picker.Actions.ChooseOtherColor, ""); } + +Picker.prototype.cleanup = function() {}; diff --git a/Source/WebCore/Resources/pagepopups/suggestionPicker.css b/Source/WebCore/Resources/pagepopups/suggestionPicker.css new file mode 100644 index 000000000..aca47ddff --- /dev/null +++ b/Source/WebCore/Resources/pagepopups/suggestionPicker.css @@ -0,0 +1,43 @@ +.suggestion-list { + list-style: none; + padding: 0; + margin: 0; + font: -webkit-small-control; + border: 1px solid #7f9db9; + background-color: white; + overflow-y: auto; +} + +.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 { + padding-left: 20px; + text-align: right; + color: #737373; + float: right; + margin-right: 4px; +} + +.measuring-width .suggestion-list-entry .label { + float: none; + margin-right: 0; +} + +.suggestion-list .separator { + border-top: 1px solid #dcdcdc; + height: 0; +} diff --git a/Source/WebCore/Resources/pagepopups/suggestionPicker.js b/Source/WebCore/Resources/pagepopups/suggestionPicker.js new file mode 100644 index 000000000..c78b1e059 --- /dev/null +++ b/Source/WebCore/Resources/pagepopups/suggestionPicker.js @@ -0,0 +1,311 @@ +"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 {!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; + if (typeof this._config.inputWidth === "number") + maxContentWidth = this._config.inputWidth; + 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; + 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; + } + + resizeWindow(desiredWindowWidth, desiredWindowHeight); +}; + +SuggestionPicker.prototype._layout = function() { + 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) { + openCalendarPicker(); + } +}; + +/** + * @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/Source/WebCore/WebCore.gyp/WebCore.gyp b/Source/WebCore/WebCore.gyp/WebCore.gyp index 171223314..d9a55911e 100644 --- a/Source/WebCore/WebCore.gyp/WebCore.gyp +++ b/Source/WebCore/WebCore.gyp/WebCore.gyp @@ -46,8 +46,6 @@ # binary and increasing the speed of gdb. 'enable_svg%': 1, - 'use_libcc_for_compositor%': 0, - 'enable_wexit_time_destructors': 1, 'use_harfbuzz_ng%': 0, @@ -361,9 +359,9 @@ }], # condition OS == "mac" ['clang==1', { 'target_defaults': { - 'cflags': ['-Wglobal-constructors'], + 'cflags': ['-Wglobal-constructors', '-Wunused-parameter'], 'xcode_settings': { - 'WARNING_CFLAGS': ['-Wglobal-constructors'], + 'WARNING_CFLAGS': ['-Wglobal-constructors', '-Wunused-parameter'], }, }, }], @@ -948,6 +946,8 @@ 'inputs': [ '../Resources/pagepopups/calendarPicker.css', '../Resources/pagepopups/calendarPicker.js', + '../Resources/pagepopups/suggestionPicker.css', + '../Resources/pagepopups/suggestionPicker.js', ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/webkit/CalendarPicker.h', @@ -1669,6 +1669,8 @@ ['include', 'platform/graphics/harfbuzz/FontPlatformDataHarfBuzz\\.cpp$'], ['include', 'platform/graphics/harfbuzz/HarfBuzzSkia\\.cpp$'], ['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$'], ], }, { # use_x11==0 @@ -1887,6 +1889,8 @@ ['include', 'platform/graphics/harfbuzz/FontPlatformDataHarfBuzz\\.cpp$'], ['include', 'platform/graphics/harfbuzz/HarfBuzzSkia\\.cpp$'], ['include', 'platform/graphics/harfbuzz/HarfBuzzShaperBase\\.cpp$'], + ['include', 'platform/graphics/opentype/OpenTypeTypes\\.h$'], + ['include', 'platform/graphics/opentype/OpenTypeVerticalData\\.(cpp|h)$'], ['exclude', 'platform/graphics/skia/FontCacheSkia\\.cpp$'], ['include', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'], ], @@ -1910,19 +1914,6 @@ '<@(webcore_platform_geometry_files)', ], }, - { - 'target_name': 'webcore_chromium_compositor', - 'type': 'static_library', - 'dependencies': [ - 'webcore_prerequisites', - ], - 'defines': [ - 'WEBKIT_IMPLEMENTATION=1', - ], - 'sources': [ - '<@(webcore_chromium_compositor_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. @@ -2210,11 +2201,6 @@ 'webcore_svg', ], }], - ['use_libcc_for_compositor==0', { - 'dependencies': [ - 'webcore_chromium_compositor' - ], - }] ], }, { diff --git a/Source/WebCore/WebCore.gypi b/Source/WebCore/WebCore.gypi index 4d43c4165..e8af673cc 100644 --- a/Source/WebCore/WebCore.gypi +++ b/Source/WebCore/WebCore.gypi @@ -4888,6 +4888,7 @@ 'platform/graphics/chromium/DrawingBufferChromium.cpp', 'platform/graphics/chromium/Extensions3DChromium.h', 'platform/graphics/chromium/FontCacheAndroid.cpp', + 'platform/graphics/chromium/FontCacheChromiumLinux.cpp', 'platform/graphics/chromium/FontCacheChromiumWin.cpp', 'platform/graphics/chromium/FontChromiumWin.cpp', 'platform/graphics/chromium/FontPlatformData.h', @@ -8357,8 +8358,6 @@ '<(PRODUCT_DIR)/DerivedSources/WebCore/XPathGrammar.h', ], 'webcore_platform_support_files': [ - 'platform/chromium/support/CCThreadImpl.cpp', - 'platform/chromium/support/CCThreadImpl.h', 'platform/chromium/support/Extensions3DChromium.cpp', 'platform/chromium/support/GraphicsContext3DChromium.cpp', 'platform/chromium/support/GraphicsContext3DPrivate.cpp', @@ -8366,8 +8365,6 @@ 'platform/chromium/support/PlatformGestureCurveFactory.cpp', 'platform/chromium/support/PlatformGestureCurveFactory.h', 'platform/chromium/support/WebAudioBus.cpp', - 'platform/chromium/support/WebCompositorImpl.cpp', - 'platform/chromium/support/WebCompositorImpl.h', 'platform/chromium/support/WebData.cpp', 'platform/chromium/support/WebFlingAnimatorToGestureCurveAdapter.h', 'platform/chromium/support/WebHTTPBody.cpp', @@ -8403,209 +8400,6 @@ 'platform/chromium/support/WrappedResourceRequest.h', 'platform/chromium/support/WrappedResourceResponse.h', ], - 'webcore_chromium_compositor_files': [ - 'platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.cpp', - 'platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.h', - 'platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.cpp', - 'platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.h', - 'platform/graphics/chromium/CanvasLayerTextureUpdater.cpp', - 'platform/graphics/chromium/CanvasLayerTextureUpdater.h', - 'platform/graphics/chromium/ContentLayerChromium.cpp', - 'platform/graphics/chromium/ContentLayerChromium.h', - 'platform/graphics/chromium/ContentLayerChromiumClient.h', - 'platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.cpp', - 'platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.h', - 'platform/graphics/chromium/GeometryBinding.cpp', - 'platform/graphics/chromium/GeometryBinding.h', - 'platform/graphics/chromium/HeadsUpDisplayLayerChromium.cpp', - 'platform/graphics/chromium/HeadsUpDisplayLayerChromium.h', - 'platform/graphics/chromium/IOSurfaceLayerChromium.cpp', - 'platform/graphics/chromium/IOSurfaceLayerChromium.h', - 'platform/graphics/chromium/ImageLayerChromium.cpp', - 'platform/graphics/chromium/ImageLayerChromium.h', - 'platform/graphics/chromium/LayerChromium.cpp', - 'platform/graphics/chromium/LayerChromium.h', - 'platform/graphics/chromium/LayerPainterChromium.h', - 'platform/graphics/chromium/LayerTextureSubImage.cpp', - 'platform/graphics/chromium/LayerTextureSubImage.h', - 'platform/graphics/chromium/LayerTextureUpdater.h', - 'platform/graphics/chromium/PlatformColor.h', - 'platform/graphics/chromium/ProgramBinding.cpp', - 'platform/graphics/chromium/ProgramBinding.h', - 'platform/graphics/chromium/RateLimiter.cpp', - 'platform/graphics/chromium/RateLimiter.h', - 'platform/graphics/chromium/RenderSurfaceChromium.cpp', - 'platform/graphics/chromium/RenderSurfaceChromium.h', - 'platform/graphics/chromium/ScrollbarLayerChromium.cpp', - 'platform/graphics/chromium/ScrollbarLayerChromium.h', - 'platform/graphics/chromium/ShaderChromium.cpp', - 'platform/graphics/chromium/ShaderChromium.h', - 'platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.cpp', - 'platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.h', - 'platform/graphics/chromium/SolidColorLayerChromium.cpp', - 'platform/graphics/chromium/SolidColorLayerChromium.h', - 'platform/graphics/chromium/TextureCopier.cpp', - 'platform/graphics/chromium/TextureCopier.h', - 'platform/graphics/chromium/TextureLayerChromium.cpp', - 'platform/graphics/chromium/TextureLayerChromium.h', - 'platform/graphics/chromium/TextureLayerChromiumClient.h', - 'platform/graphics/chromium/TextureUploader.h', - 'platform/graphics/chromium/ThrottledTextureUploader.cpp', - 'platform/graphics/chromium/ThrottledTextureUploader.h', - 'platform/graphics/chromium/TiledLayerChromium.cpp', - 'platform/graphics/chromium/TiledLayerChromium.h', - 'platform/graphics/chromium/TreeSynchronizer.cpp', - 'platform/graphics/chromium/TreeSynchronizer.h', - 'platform/graphics/chromium/UnthrottledTextureUploader.h', - 'platform/graphics/chromium/VideoLayerChromium.cpp', - 'platform/graphics/chromium/VideoLayerChromium.h', - 'platform/graphics/chromium/cc/CCActiveAnimation.cpp', - 'platform/graphics/chromium/cc/CCActiveAnimation.h', - 'platform/graphics/chromium/cc/CCAnimationCurve.cpp', - 'platform/graphics/chromium/cc/CCAnimationCurve.h', - 'platform/graphics/chromium/cc/CCAnimationEvents.h', - 'platform/graphics/chromium/cc/CCCheckerboardDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCCheckerboardDrawQuad.h', - 'platform/graphics/chromium/cc/CCCompletionEvent.h', - 'platform/graphics/chromium/cc/CCDamageTracker.cpp', - 'platform/graphics/chromium/cc/CCDamageTracker.h', - 'platform/graphics/chromium/cc/CCDebugBorderDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCDebugBorderDrawQuad.h', - 'platform/graphics/chromium/cc/CCDebugRectHistory.cpp', - 'platform/graphics/chromium/cc/CCDebugRectHistory.h', - 'platform/graphics/chromium/cc/CCDelayBasedTimeSource.cpp', - 'platform/graphics/chromium/cc/CCDelayBasedTimeSource.h', - 'platform/graphics/chromium/cc/CCDirectRenderer.h', - 'platform/graphics/chromium/cc/CCDirectRenderer.cpp', - 'platform/graphics/chromium/cc/CCDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCDrawQuad.h', - 'platform/graphics/chromium/cc/CCFontAtlas.cpp', - 'platform/graphics/chromium/cc/CCFontAtlas.h', - 'platform/graphics/chromium/cc/CCFrameRateController.cpp', - 'platform/graphics/chromium/cc/CCFrameRateController.h', - 'platform/graphics/chromium/cc/CCFrameRateCounter.cpp', - 'platform/graphics/chromium/cc/CCFrameRateCounter.h', - 'platform/graphics/chromium/cc/CCGraphicsContext.h', - 'platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.h', - 'platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.h', - 'platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.h', - 'platform/graphics/chromium/cc/CCInputHandler.h', - 'platform/graphics/chromium/cc/CCKeyframedAnimationCurve.cpp', - 'platform/graphics/chromium/cc/CCKeyframedAnimationCurve.h', - 'platform/graphics/chromium/cc/CCLayerAnimationController.cpp', - 'platform/graphics/chromium/cc/CCLayerAnimationController.h', - 'platform/graphics/chromium/cc/CCLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCLayerImpl.h', - 'platform/graphics/chromium/cc/CCLayerIterator.cpp', - 'platform/graphics/chromium/cc/CCLayerIterator.h', - 'platform/graphics/chromium/cc/CCLayerQuad.cpp', - 'platform/graphics/chromium/cc/CCLayerQuad.h', - 'platform/graphics/chromium/cc/CCLayerSorter.cpp', - 'platform/graphics/chromium/cc/CCLayerSorter.h', - 'platform/graphics/chromium/cc/CCLayerTilingData.cpp', - 'platform/graphics/chromium/cc/CCLayerTilingData.h', - 'platform/graphics/chromium/cc/CCLayerTreeHost.cpp', - 'platform/graphics/chromium/cc/CCLayerTreeHost.h', - 'platform/graphics/chromium/cc/CCLayerTreeHostClient.h', - 'platform/graphics/chromium/cc/CCLayerTreeHostCommon.cpp', - 'platform/graphics/chromium/cc/CCLayerTreeHostCommon.h', - 'platform/graphics/chromium/cc/CCLayerTreeHostImpl.cpp', - 'platform/graphics/chromium/cc/CCLayerTreeHostImpl.h', - 'platform/graphics/chromium/cc/CCMathUtil.cpp', - 'platform/graphics/chromium/cc/CCMathUtil.h', - 'platform/graphics/chromium/cc/CCOcclusionTracker.cpp', - 'platform/graphics/chromium/cc/CCOcclusionTracker.h', - 'platform/graphics/chromium/cc/CCOverdrawMetrics.cpp', - 'platform/graphics/chromium/cc/CCOverdrawMetrics.h', - 'platform/graphics/chromium/cc/CCPageScaleAnimation.cpp', - 'platform/graphics/chromium/cc/CCPageScaleAnimation.h', - 'platform/graphics/chromium/cc/CCPrioritizedTexture.cpp', - 'platform/graphics/chromium/cc/CCPrioritizedTexture.h', - 'platform/graphics/chromium/cc/CCPrioritizedTextureManager.cpp', - 'platform/graphics/chromium/cc/CCPrioritizedTextureManager.h', - 'platform/graphics/chromium/cc/CCPriorityCalculator.cpp', - 'platform/graphics/chromium/cc/CCPriorityCalculator.h', - 'platform/graphics/chromium/cc/CCProxy.cpp', - 'platform/graphics/chromium/cc/CCProxy.h', - 'platform/graphics/chromium/cc/CCQuadSink.h', - 'platform/graphics/chromium/cc/CCQuadCuller.cpp', - 'platform/graphics/chromium/cc/CCQuadCuller.h', - 'platform/graphics/chromium/cc/CCRenderer.h', - 'platform/graphics/chromium/cc/CCRendererGL.cpp', - 'platform/graphics/chromium/cc/CCRendererGL.h', - 'platform/graphics/chromium/cc/CCRenderPass.cpp', - 'platform/graphics/chromium/cc/CCRenderPass.h', - 'platform/graphics/chromium/cc/CCRenderPassDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCRenderPassDrawQuad.h', - 'platform/graphics/chromium/cc/CCRenderPassSink.h', - 'platform/graphics/chromium/cc/CCRenderSurface.cpp', - 'platform/graphics/chromium/cc/CCRenderSurface.h', - 'platform/graphics/chromium/cc/CCRenderSurfaceFilters.cpp', - 'platform/graphics/chromium/cc/CCRenderSurfaceFilters.h', - 'platform/graphics/chromium/cc/CCRenderer.h', - 'platform/graphics/chromium/cc/CCRenderingStats.h', - 'platform/graphics/chromium/cc/CCResourceProvider.cpp', - 'platform/graphics/chromium/cc/CCResourceProvider.h', - 'platform/graphics/chromium/cc/CCScheduler.cpp', - 'platform/graphics/chromium/cc/CCScheduler.h', - 'platform/graphics/chromium/cc/CCSchedulerStateMachine.cpp', - 'platform/graphics/chromium/cc/CCSchedulerStateMachine.h', - 'platform/graphics/chromium/cc/CCScopedTexture.cpp', - 'platform/graphics/chromium/cc/CCScopedTexture.h', - 'platform/graphics/chromium/cc/CCScopedThreadProxy.h', - 'platform/graphics/chromium/cc/CCScrollbarAnimationController.cpp', - 'platform/graphics/chromium/cc/CCScrollbarAnimationController.h', - 'platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.cpp', - 'platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.h', - 'platform/graphics/chromium/cc/CCScrollbarLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCScrollbarLayerImpl.h', - 'platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.cpp', - 'platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.h', - 'platform/graphics/chromium/cc/CCScrollbarGeometryStub.cpp', - 'platform/graphics/chromium/cc/CCScrollbarGeometryStub.h', - 'platform/graphics/chromium/cc/CCSettings.cpp', - 'platform/graphics/chromium/cc/CCSettings.h', - 'platform/graphics/chromium/cc/CCSharedQuadState.cpp', - 'platform/graphics/chromium/cc/CCSharedQuadState.h', - 'platform/graphics/chromium/cc/CCSingleThreadProxy.cpp', - 'platform/graphics/chromium/cc/CCSingleThreadProxy.h', - 'platform/graphics/chromium/cc/CCSolidColorDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCSolidColorDrawQuad.h', - 'platform/graphics/chromium/cc/CCSolidColorLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCSolidColorLayerImpl.h', - 'platform/graphics/chromium/cc/CCStreamVideoDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCStreamVideoDrawQuad.h', - 'platform/graphics/chromium/cc/CCTexture.cpp', - 'platform/graphics/chromium/cc/CCTexture.h', - 'platform/graphics/chromium/cc/CCTextureDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCTextureDrawQuad.h', - 'platform/graphics/chromium/cc/CCTextureLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCTextureLayerImpl.h', - 'platform/graphics/chromium/cc/CCTextureUpdateController.cpp', - 'platform/graphics/chromium/cc/CCTextureUpdateController.h', - 'platform/graphics/chromium/cc/CCTextureUpdateQueue.cpp', - 'platform/graphics/chromium/cc/CCTextureUpdateQueue.h', - 'platform/graphics/chromium/cc/CCThread.h', - 'platform/graphics/chromium/cc/CCThreadProxy.cpp', - 'platform/graphics/chromium/cc/CCThreadProxy.h', - 'platform/graphics/chromium/cc/CCThreadTask.h', - 'platform/graphics/chromium/cc/CCTileDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCTileDrawQuad.h', - 'platform/graphics/chromium/cc/CCTiledLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCTiledLayerImpl.h', - 'platform/graphics/chromium/cc/CCTimeSource.h', - 'platform/graphics/chromium/cc/CCTimer.cpp', - 'platform/graphics/chromium/cc/CCTimer.h', - 'platform/graphics/chromium/cc/CCTimingFunction.cpp', - 'platform/graphics/chromium/cc/CCTimingFunction.h', - 'platform/graphics/chromium/cc/CCVideoLayerImpl.cpp', - 'platform/graphics/chromium/cc/CCVideoLayerImpl.h', - 'platform/graphics/chromium/cc/CCYUVVideoDrawQuad.cpp', - 'platform/graphics/chromium/cc/CCYUVVideoDrawQuad.h', - ], 'export_file_generator_files': [ '<(PRODUCT_DIR)/DerivedSources/WebCore/ExportFileGenerator.cpp', ], diff --git a/Source/WebCore/accessibility/gtk/AccessibilityObjectAtk.cpp b/Source/WebCore/accessibility/gtk/AccessibilityObjectAtk.cpp index 42cf02ed5..0cb7a96e7 100644 --- a/Source/WebCore/accessibility/gtk/AccessibilityObjectAtk.cpp +++ b/Source/WebCore/accessibility/gtk/AccessibilityObjectAtk.cpp @@ -84,13 +84,16 @@ AccessibilityObjectInclusion AccessibilityObject::accessibilityPlatformIncludesO // usually have no need for the anonymous block. And when the wrong objects // get included or ignored, needed accessibility signals do not get emitted. if (role == ParagraphRole || role == DivRole) { - AccessibilityObject* child = firstAnonymousBlockChild(); - if (!child) + if (textUnderElement().isEmpty()) return DefaultBehavior; - child = child->firstChild(); - if (child && (child->isLink() || !child->firstAnonymousBlockChild())) - return IncludeObject; + if (!parent->renderer() || parent->renderer()->isAnonymousBlock()) + return DefaultBehavior; + + for (RenderObject* r = renderer()->firstChild(); r; r = r->nextSibling()) { + if (r->isAnonymousBlock()) + return IncludeObject; + } } // Block spans result in objects of ATK_ROLE_PANEL which are almost always unwanted. diff --git a/Source/WebCore/accessibility/gtk/WebKitAccessibleWrapperAtk.cpp b/Source/WebCore/accessibility/gtk/WebKitAccessibleWrapperAtk.cpp index ec223aa02..b197cb243 100644 --- a/Source/WebCore/accessibility/gtk/WebKitAccessibleWrapperAtk.cpp +++ b/Source/WebCore/accessibility/gtk/WebKitAccessibleWrapperAtk.cpp @@ -555,6 +555,8 @@ static AtkRole atkRole(AccessibilityRole role) return ATK_ROLE_CANVAS; case HorizontalRuleRole: return ATK_ROLE_SEPARATOR; + case SpinButtonRole: + return ATK_ROLE_SPIN_BUTTON; default: return ATK_ROLE_UNKNOWN; } @@ -923,7 +925,7 @@ static guint16 getInterfaceMaskFromObject(AccessibilityObject* coreObject) interfaceMask |= 1 << WAI_DOCUMENT; // Value - if (role == SliderRole) + if (role == SliderRole || role == SpinButtonRole) interfaceMask |= 1 << WAI_VALUE; return interfaceMask; diff --git a/Source/WebCore/accessibility/mac/WebAccessibilityObjectWrapper.mm b/Source/WebCore/accessibility/mac/WebAccessibilityObjectWrapper.mm index 26c7aae27..a4394ba20 100644 --- a/Source/WebCore/accessibility/mac/WebAccessibilityObjectWrapper.mm +++ b/Source/WebCore/accessibility/mac/WebAccessibilityObjectWrapper.mm @@ -2430,6 +2430,10 @@ static NSString* roleValueToNSString(AccessibilityRole value) return @"normal"; } } + + // Used by DRT to find an accessible node by its element id. + if ([attributeName isEqualToString:@"AXDRTElementIdAttribute"]) + return m_object->getAttribute(idAttr); return nil; } diff --git a/Source/WebCore/css/StyleResolver.cpp b/Source/WebCore/css/StyleResolver.cpp index cf20687c8..ec0c39c49 100644 --- a/Source/WebCore/css/StyleResolver.cpp +++ b/Source/WebCore/css/StyleResolver.cpp @@ -2193,6 +2193,7 @@ void StyleResolver::adjustRenderStyle(RenderStyle* style, RenderStyle* parentSty || style->opacity() < 1.0f || style->hasTransformRelatedProperty() || style->hasMask() + || style->clipPath() || style->boxReflect() || style->hasFilter() || style->hasBlendMode() @@ -5191,7 +5192,7 @@ void StyleResolver::loadPendingSVGDocuments() if (filterOperation->getOperationType() == FilterOperation::REFERENCE) { ReferenceFilterOperation* referenceFilter = static_cast<ReferenceFilterOperation*>(filterOperation.get()); - WebKitCSSSVGDocumentValue* value = m_pendingSVGDocuments.get(referenceFilter); + WebKitCSSSVGDocumentValue* value = m_pendingSVGDocuments.get(referenceFilter).get(); if (!value) continue; CachedSVGDocument* cachedDocument = value->load(cachedResourceLoader); diff --git a/Source/WebCore/css/StyleResolver.h b/Source/WebCore/css/StyleResolver.h index 5fb858cfb..9c6fe1d3c 100644 --- a/Source/WebCore/css/StyleResolver.h +++ b/Source/WebCore/css/StyleResolver.h @@ -515,7 +515,7 @@ private: #endif #if ENABLE(CSS_FILTERS) && ENABLE(SVG) - HashMap<FilterOperation*, WebKitCSSSVGDocumentValue*> m_pendingSVGDocuments; + HashMap<FilterOperation*, RefPtr<WebKitCSSSVGDocumentValue> > m_pendingSVGDocuments; #endif #if ENABLE(STYLE_SCOPED) diff --git a/Source/WebCore/dom/ChildListMutationScope.cpp b/Source/WebCore/dom/ChildListMutationScope.cpp index f4a2da04a..44762bdaa 100644 --- a/Source/WebCore/dom/ChildListMutationScope.cpp +++ b/Source/WebCore/dom/ChildListMutationScope.cpp @@ -42,61 +42,55 @@ #include "StaticNodeList.h" #include <wtf/HashMap.h> #include <wtf/OwnPtr.h> +#include <wtf/StdLibExtras.h> namespace WebCore { -// MutationAccumulator expects that all removals from a parent take place in order -// and precede any additions. If this is violated (i.e. because of code changes elsewhere -// in WebCore) it will likely result in both (a) ASSERTions failing, and (b) mutation records -// being enqueued for delivery before the outer-most scope closes. -class ChildListMutationScope::MutationAccumulator { - WTF_MAKE_NONCOPYABLE(MutationAccumulator); -public: - MutationAccumulator(PassRefPtr<Node>, PassOwnPtr<MutationObserverInterestGroup> observers); - ~MutationAccumulator(); - - void childAdded(PassRefPtr<Node>); - void willRemoveChild(PassRefPtr<Node>); - void enqueueMutationRecord(); - -private: - void clear(); - bool isEmpty(); - bool isAddedNodeInOrder(Node*); - bool isRemovedNodeInOrder(Node*); - RefPtr<Node> m_target; - - Vector<RefPtr<Node> > m_removedNodes; - Vector<RefPtr<Node> > m_addedNodes; - RefPtr<Node> m_previousSibling; - RefPtr<Node> m_nextSibling; - RefPtr<Node> m_lastAdded; - - OwnPtr<MutationObserverInterestGroup> m_observers; -}; - -ChildListMutationScope::MutationAccumulator::MutationAccumulator(PassRefPtr<Node> target, PassOwnPtr<MutationObserverInterestGroup> observers) +typedef HashMap<Node*, ChildListMutationAccumulator*> AccumulatorMap; +static AccumulatorMap& accumulatorMap() +{ + DEFINE_STATIC_LOCAL(AccumulatorMap, map, ()); + return map; +} + +ChildListMutationAccumulator::ChildListMutationAccumulator(PassRefPtr<Node> target, PassOwnPtr<MutationObserverInterestGroup> observers) : m_target(target) + , m_lastAdded(0) , m_observers(observers) { - clear(); } -ChildListMutationScope::MutationAccumulator::~MutationAccumulator() +ChildListMutationAccumulator::~ChildListMutationAccumulator() { - ASSERT(isEmpty()); + if (!isEmpty()) + enqueueMutationRecord(); + accumulatorMap().remove(m_target.get()); +} + +PassRefPtr<ChildListMutationAccumulator> ChildListMutationAccumulator::getOrCreate(Node* target) +{ + AccumulatorMap::AddResult result = accumulatorMap().add(target, 0); + RefPtr<ChildListMutationAccumulator> accumulator; + if (!result.isNewEntry) + accumulator = result.iterator->second; + else { + accumulator = adoptRef(new ChildListMutationAccumulator(target, MutationObserverInterestGroup::createForChildListMutation(target))); + result.iterator->second = accumulator.get(); + } + return accumulator.release(); } -inline bool ChildListMutationScope::MutationAccumulator::isAddedNodeInOrder(Node* child) +inline bool ChildListMutationAccumulator::isAddedNodeInOrder(Node* child) { return isEmpty() || (m_lastAdded == child->previousSibling() && m_nextSibling == child->nextSibling()); } -void ChildListMutationScope::MutationAccumulator::childAdded(PassRefPtr<Node> prpChild) +void ChildListMutationAccumulator::childAdded(PassRefPtr<Node> prpChild) { + ASSERT(hasObservers()); + RefPtr<Node> child = prpChild; - ASSERT(isAddedNodeInOrder(child.get())); if (!isAddedNodeInOrder(child.get())) enqueueMutationRecord(); @@ -105,20 +99,20 @@ void ChildListMutationScope::MutationAccumulator::childAdded(PassRefPtr<Node> pr m_nextSibling = child->nextSibling(); } - m_addedNodes.append(child); - m_lastAdded = child; + m_lastAdded = child.get(); + m_addedNodes.append(child.release()); } -inline bool ChildListMutationScope::MutationAccumulator::isRemovedNodeInOrder(Node* child) +inline bool ChildListMutationAccumulator::isRemovedNodeInOrder(Node* child) { - return isEmpty() || m_nextSibling.get() == child; + return isEmpty() || m_nextSibling == child; } -void ChildListMutationScope::MutationAccumulator::willRemoveChild(PassRefPtr<Node> prpChild) +void ChildListMutationAccumulator::willRemoveChild(PassRefPtr<Node> prpChild) { - RefPtr<Node> child = prpChild; + ASSERT(hasObservers()); - ASSERT(m_addedNodes.isEmpty() && isRemovedNodeInOrder(child.get())); + RefPtr<Node> child = prpChild; if (!m_addedNodes.isEmpty() || !isRemovedNodeInOrder(child.get())) enqueueMutationRecord(); @@ -130,114 +124,33 @@ void ChildListMutationScope::MutationAccumulator::willRemoveChild(PassRefPtr<Nod } else m_nextSibling = child->nextSibling(); - m_removedNodes.append(child); + m_removedNodes.append(child.release()); } -void ChildListMutationScope::MutationAccumulator::enqueueMutationRecord() +void ChildListMutationAccumulator::enqueueMutationRecord() { - if (isEmpty()) { - clear(); - return; - } + ASSERT(hasObservers()); + ASSERT(!isEmpty()); - m_observers->enqueueMutationRecord(MutationRecord::createChildList( - m_target, StaticNodeList::adopt(m_addedNodes), StaticNodeList::adopt(m_removedNodes), m_previousSibling.release(), m_nextSibling.release())); - clear(); -} - -void ChildListMutationScope::MutationAccumulator::clear() -{ - if (!m_removedNodes.isEmpty()) - m_removedNodes.clear(); - if (!m_addedNodes.isEmpty()) - m_addedNodes.clear(); - m_previousSibling = 0; - m_nextSibling = 0; + RefPtr<NodeList> addedNodes = StaticNodeList::adopt(m_addedNodes); + RefPtr<NodeList> removedNodes = StaticNodeList::adopt(m_removedNodes); + RefPtr<MutationRecord> record = MutationRecord::createChildList(m_target, addedNodes.release(), removedNodes.release(), m_previousSibling.release(), m_nextSibling.release()); + m_observers->enqueueMutationRecord(record.release()); m_lastAdded = 0; + ASSERT(isEmpty()); } -bool ChildListMutationScope::MutationAccumulator::isEmpty() -{ - return m_removedNodes.isEmpty() && m_addedNodes.isEmpty(); -} - -ChildListMutationScope::MutationAccumulationRouter* ChildListMutationScope::MutationAccumulationRouter::s_instance = 0; - -ChildListMutationScope::MutationAccumulationRouter::MutationAccumulationRouter() -{ -} - -ChildListMutationScope::MutationAccumulationRouter::~MutationAccumulationRouter() -{ - ASSERT(m_scopingLevels.isEmpty()); - ASSERT(m_accumulations.isEmpty()); -} - -void ChildListMutationScope::MutationAccumulationRouter::initialize() -{ - ASSERT(!s_instance); - s_instance = adoptPtr(new ChildListMutationScope::MutationAccumulationRouter).leakPtr(); -} - - -ChildListMutationScope::MutationAccumulationRouter* ChildListMutationScope::MutationAccumulationRouter::instance() -{ - if (!s_instance) - initialize(); - - return s_instance; -} - -void ChildListMutationScope::MutationAccumulationRouter::childAdded(Node* target, Node* child) -{ - HashMap<Node*, OwnPtr<ChildListMutationScope::MutationAccumulator> >::iterator iter = m_accumulations.find(target); - ASSERT(iter != m_accumulations.end()); - if (iter == m_accumulations.end() || !iter->second) - return; - - iter->second->childAdded(child); -} - -void ChildListMutationScope::MutationAccumulationRouter::willRemoveChild(Node* target, Node* child) -{ - HashMap<Node*, OwnPtr<ChildListMutationScope::MutationAccumulator> >::iterator iter = m_accumulations.find(target); - ASSERT(iter != m_accumulations.end()); - if (iter == m_accumulations.end() || !iter->second) - return; - - iter->second->willRemoveChild(child); -} - -void ChildListMutationScope::MutationAccumulationRouter::incrementScopingLevel(Node* target) +bool ChildListMutationAccumulator::isEmpty() { - ScopingLevelMap::AddResult result = m_scopingLevels.add(target, 1); - if (!result.isNewEntry) { - ++(result.iterator->second); - return; - } - - if (OwnPtr<MutationObserverInterestGroup> observers = MutationObserverInterestGroup::createForChildListMutation(target)) - m_accumulations.set(target, adoptPtr(new ChildListMutationScope::MutationAccumulator(target, observers.release()))); + bool result = m_removedNodes.isEmpty() && m_addedNodes.isEmpty(); #ifndef NDEBUG - else - m_accumulations.set(target, nullptr); + if (result) { + ASSERT(!m_previousSibling); + ASSERT(!m_nextSibling); + ASSERT(!m_lastAdded); + } #endif -} - -void ChildListMutationScope::MutationAccumulationRouter::decrementScopingLevel(Node* target) -{ - ScopingLevelMap::iterator iter = m_scopingLevels.find(target); - ASSERT(iter != m_scopingLevels.end()); - - --(iter->second); - if (iter->second > 0) - return; - - m_scopingLevels.remove(iter); - - OwnPtr<MutationAccumulator> record(m_accumulations.take(target)); - if (record) - record->enqueueMutationRecord(); + return result; } } // namespace WebCore diff --git a/Source/WebCore/dom/ChildListMutationScope.h b/Source/WebCore/dom/ChildListMutationScope.h index e0624ef5d..a47ee55f8 100644 --- a/Source/WebCore/dom/ChildListMutationScope.h +++ b/Source/WebCore/dom/ChildListMutationScope.h @@ -39,65 +39,65 @@ #include <wtf/HashMap.h> #include <wtf/Noncopyable.h> #include <wtf/OwnPtr.h> +#include <wtf/RefCounted.h> namespace WebCore { +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*); + ~ChildListMutationAccumulator(); + + void childAdded(PassRefPtr<Node>); + void willRemoveChild(PassRefPtr<Node>); + + bool hasObservers() const { return m_observers; } + +private: + ChildListMutationAccumulator(PassRefPtr<Node>, PassOwnPtr<MutationObserverInterestGroup>); + + void enqueueMutationRecord(); + bool isEmpty(); + bool isAddedNodeInOrder(Node*); + bool isRemovedNodeInOrder(Node*); + + RefPtr<Node> m_target; + + Vector<RefPtr<Node> > m_removedNodes; + Vector<RefPtr<Node> > m_addedNodes; + RefPtr<Node> m_previousSibling; + RefPtr<Node> m_nextSibling; + Node* m_lastAdded; + + OwnPtr<MutationObserverInterestGroup> m_observers; +}; + class ChildListMutationScope { WTF_MAKE_NONCOPYABLE(ChildListMutationScope); public: explicit ChildListMutationScope(Node* target) - : m_target(target->document()->hasMutationObserversOfType(MutationObserver::ChildList) ? target : 0) { - if (m_target) - MutationAccumulationRouter::instance()->incrementScopingLevel(m_target); - } - - ~ChildListMutationScope() - { - if (m_target) - MutationAccumulationRouter::instance()->decrementScopingLevel(m_target); + if (target->document()->hasMutationObserversOfType(MutationObserver::ChildList)) + m_accumulator = ChildListMutationAccumulator::getOrCreate(target); } void childAdded(Node* child) { - if (m_target) - MutationAccumulationRouter::instance()->childAdded(m_target, child); + if (m_accumulator && m_accumulator->hasObservers()) + m_accumulator->childAdded(child); } void willRemoveChild(Node* child) { - if (m_target) - MutationAccumulationRouter::instance()->willRemoveChild(m_target, child); + if (m_accumulator && m_accumulator->hasObservers()) + m_accumulator->willRemoveChild(child); } private: - class MutationAccumulator; - - class MutationAccumulationRouter { - WTF_MAKE_NONCOPYABLE(MutationAccumulationRouter); - public: - ~MutationAccumulationRouter(); - - static MutationAccumulationRouter* instance(); - - void incrementScopingLevel(Node*); - void decrementScopingLevel(Node*); - - void childAdded(Node* target, Node* child); - void willRemoveChild(Node* target, Node* child); - - private: - MutationAccumulationRouter(); - static void initialize(); - - typedef HashMap<Node*, unsigned> ScopingLevelMap; - ScopingLevelMap m_scopingLevels; - HashMap<Node*, OwnPtr<MutationAccumulator> > m_accumulations; - - static MutationAccumulationRouter* s_instance; - }; - - Node* m_target; + RefPtr<ChildListMutationAccumulator> m_accumulator; }; } // namespace WebCore diff --git a/Source/WebCore/dom/ContainerNode.cpp b/Source/WebCore/dom/ContainerNode.cpp index 7e02284ce..cd118f17d 100644 --- a/Source/WebCore/dom/ContainerNode.cpp +++ b/Source/WebCore/dom/ContainerNode.cpp @@ -103,7 +103,7 @@ void ContainerNode::takeAllChildrenFrom(ContainerNode* oldParent) // FIXME: We need a no mutation event version of adoptNode. RefPtr<Node> child = document()->adoptNode(children[i].release(), ec); ASSERT(!ec); - parserAddChild(child.get()); + parserAppendChild(child.get()); // 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? @@ -600,7 +600,7 @@ bool ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, bo return true; } -void ContainerNode::parserAddChild(PassRefPtr<Node> newChild) +void ContainerNode::parserAppendChild(PassRefPtr<Node> newChild) { ASSERT(newChild); ASSERT(!newChild->parentNode()); // Use appendChild if you need to handle reparenting (and want DOM mutation events). diff --git a/Source/WebCore/dom/ContainerNode.h b/Source/WebCore/dom/ContainerNode.h index f9ec37798..c147d0155 100644 --- a/Source/WebCore/dom/ContainerNode.h +++ b/Source/WebCore/dom/ContainerNode.h @@ -60,7 +60,7 @@ public: // These methods are only used during parsing. // They don't send DOM mutation events or handle reparenting. // However, arbitrary code may be run by beforeload handlers. - void parserAddChild(PassRefPtr<Node>); + void parserAppendChild(PassRefPtr<Node>); void parserRemoveChild(Node*); void parserInsertBefore(PassRefPtr<Node> newChild, Node* refChild); diff --git a/Source/WebCore/dom/DOMImplementation.cpp b/Source/WebCore/dom/DOMImplementation.cpp index 3bbf9b600..8b5eeb284 100644 --- a/Source/WebCore/dom/DOMImplementation.cpp +++ b/Source/WebCore/dom/DOMImplementation.cpp @@ -317,9 +317,9 @@ PassRefPtr<Document> DOMImplementation::createDocument(const String& namespaceUR // FIXME: Shouldn't this call appendChild instead? if (doctype) - doc->parserAddChild(doctype); + doc->parserAppendChild(doctype); if (documentElement) - doc->parserAddChild(documentElement.release()); + doc->parserAppendChild(documentElement.release()); return doc.release(); } diff --git a/Source/WebCore/dom/Document.cpp b/Source/WebCore/dom/Document.cpp index ab48ca382..3fa6b41ab 100644 --- a/Source/WebCore/dom/Document.cpp +++ b/Source/WebCore/dom/Document.cpp @@ -127,6 +127,7 @@ #include "PointerLockController.h" #include "PopStateEvent.h" #include "ProcessingInstruction.h" +#include "QualifiedName.h" #include "RegisteredEventListener.h" #include "RenderArena.h" #include "RenderNamedFlowThread.h" @@ -5768,6 +5769,10 @@ void Document::setFullScreenRendererBackgroundColor(Color backgroundColor) void Document::fullScreenChangeDelayTimerFired(Timer<Document>*) { + // Since we dispatch events in this function, it's possible that the + // document will be detached and GC'd. We protect it here to make sure we + // can finish the function successfully. + RefPtr<Document> protectDocument(this); Deque<RefPtr<Node> > changeQueue; m_fullScreenChangeEventTargetQueue.swap(changeQueue); @@ -5775,6 +5780,9 @@ void Document::fullScreenChangeDelayTimerFired(Timer<Document>*) RefPtr<Node> node = changeQueue.takeFirst(); if (!node) node = documentElement(); + // The dispatchEvent below may have blown away our documentElement. + if (!node) + continue; // If the element was removed from our tree, also message the documentElement. Since we may // have a document hierarchy, check that node isn't in another document. @@ -5791,6 +5799,9 @@ void Document::fullScreenChangeDelayTimerFired(Timer<Document>*) RefPtr<Node> node = errorQueue.takeFirst(); if (!node) node = documentElement(); + // The dispatchEvent below may have blown away our documentElement. + if (!node) + continue; // If the element was removed from our tree, also message the documentElement. Since we may // have a document hierarchy, check that node isn't in another document. @@ -6304,23 +6315,16 @@ PassRefPtr<UndoManager> Document::undoManager() #endif class ImmutableAttributeDataCacheKey { - WTF_MAKE_FAST_ALLOCATED; public: - ImmutableAttributeDataCacheKey() - : m_localName(0) - , m_attributes(0) - , m_attributeCount(0) - { } - - ImmutableAttributeDataCacheKey(const AtomicString& localName, const Attribute* attributes, unsigned attributeCount) - : m_localName(localName.impl()) + ImmutableAttributeDataCacheKey(const QualifiedName& tagName, const Attribute* attributes, unsigned attributeCount) + : m_tagQName(tagName) , m_attributes(attributes) , m_attributeCount(attributeCount) { } bool operator!=(const ImmutableAttributeDataCacheKey& other) const { - if (m_localName != other.m_localName) + if (m_tagQName != other.m_tagQName) return true; if (m_attributeCount != other.m_attributeCount) return true; @@ -6330,16 +6334,21 @@ public: unsigned hash() const { unsigned attributeHash = StringHasher::hashMemory(m_attributes, m_attributeCount * sizeof(Attribute)); - return WTF::pairIntHash(m_localName->existingHash(), attributeHash); + return WTF::pairIntHash(m_tagQName.localName().impl()->existingHash(), attributeHash); } private: - AtomicStringImpl* m_localName; + QualifiedName m_tagQName; const Attribute* m_attributes; unsigned m_attributeCount; }; struct ImmutableAttributeDataCacheEntry { + ImmutableAttributeDataCacheEntry(const ImmutableAttributeDataCacheKey& k, PassRefPtr<ElementAttributeData> v) + : key(k) + , value(v) + { } + ImmutableAttributeDataCacheKey key; RefPtr<ElementAttributeData> value; }; @@ -6348,7 +6357,7 @@ PassRefPtr<ElementAttributeData> Document::cachedImmutableAttributeData(const El { ASSERT(!attributes.isEmpty()); - ImmutableAttributeDataCacheKey cacheKey(element->localName(), attributes.data(), attributes.size()); + ImmutableAttributeDataCacheKey cacheKey(element->tagQName(), attributes.data(), attributes.size()); unsigned cacheHash = cacheKey.hash(); ImmutableAttributeDataCache::iterator cacheIterator = m_immutableAttributeDataCache.add(cacheHash, nullptr).iterator; @@ -6364,11 +6373,7 @@ PassRefPtr<ElementAttributeData> Document::cachedImmutableAttributeData(const El if (!cacheHash || cacheIterator->second) return attributeData.release(); - OwnPtr<ImmutableAttributeDataCacheEntry> newEntry = adoptPtr(new ImmutableAttributeDataCacheEntry); - newEntry->key = ImmutableAttributeDataCacheKey(element->localName(), const_cast<const ElementAttributeData*>(attributeData.get())->attributeItem(0), attributeData->length()); - newEntry->value = attributeData; - - cacheIterator->second = newEntry.release(); + cacheIterator->second = adoptPtr(new ImmutableAttributeDataCacheEntry(ImmutableAttributeDataCacheKey(element->tagQName(), attributeData->immutableAttributeArray(), attributeData->length()), attributeData)); return attributeData.release(); } diff --git a/Source/WebCore/dom/Element.cpp b/Source/WebCore/dom/Element.cpp index 3a7c54196..15804a3fa 100644 --- a/Source/WebCore/dom/Element.cpp +++ b/Source/WebCore/dom/Element.cpp @@ -843,13 +843,10 @@ void Element::parserSetAttributes(const Vector<Attribute>& attributeVector, Frag } // When the document is in parsing state, we cache immutable ElementAttributeData objects with the - // input attribute vector as key. (This cache is held by Document.) + // input attribute vector (and the tag name) as key. (This cache is held by Document.) if (!document() || !document()->parsing()) m_attributeData = ElementAttributeData::createImmutable(filteredAttributes); - else if (!isHTMLElement()) { - // FIXME: Support attribute data sharing for non-HTML elements. - m_attributeData = ElementAttributeData::createImmutable(filteredAttributes); - } else + else m_attributeData = document()->cachedImmutableAttributeData(this, filteredAttributes); // Iterate over the set of attributes we already have on the stack in case diff --git a/Source/WebCore/dom/ElementAttributeData.h b/Source/WebCore/dom/ElementAttributeData.h index e18d8b333..50a85dc76 100644 --- a/Source/WebCore/dom/ElementAttributeData.h +++ b/Source/WebCore/dom/ElementAttributeData.h @@ -46,6 +46,10 @@ public: static PassRefPtr<ElementAttributeData> create(); static PassRefPtr<ElementAttributeData> createImmutable(const Vector<Attribute>&); + // Override RefCounted's deref() to ensure operator delete is called on + // the appropriate subclass type. + void deref(); + void clearClass() { m_classNames.clear(); } void setClass(const AtomicString& className, bool shouldFoldCase) const { m_classNames.set(className, shouldFoldCase); } const SpaceSplitString& classNames() const { return m_classNames; } @@ -97,6 +101,7 @@ public: void reportMemoryUsage(MemoryObjectInfo*) const; bool isMutable() const { return m_isMutable; } + const Attribute* immutableAttributeArray() const; protected: ElementAttributeData() @@ -133,7 +138,6 @@ private: Vector<Attribute, 4>& mutableAttributeVector(); const Vector<Attribute, 4>& mutableAttributeVector() const; - const Attribute* immutableAttributeArray() const; }; class ImmutableElementAttributeData : public ElementAttributeData { @@ -256,18 +260,15 @@ inline Attribute* ElementAttributeData::attributeItem(unsigned index) return &mutableAttributeVector().at(index); } -} - -namespace WTF { - -template <> inline void deleteOwnedPtr<WebCore::ElementAttributeData>(WebCore::ElementAttributeData* ptr) +inline void ElementAttributeData::deref() { - if (!ptr) + if (!derefBase()) return; - if (ptr->isMutable()) - delete static_cast<WebCore::MutableElementAttributeData*>(ptr); + + if (m_isMutable) + delete static_cast<MutableElementAttributeData*>(this); else - delete static_cast<WebCore::ImmutableElementAttributeData*>(ptr); + delete static_cast<ImmutableElementAttributeData*>(this); } } diff --git a/Source/WebCore/dom/Position.cpp b/Source/WebCore/dom/Position.cpp index 4fcf442e2..77ecf5f89 100644 --- a/Source/WebCore/dom/Position.cpp +++ b/Source/WebCore/dom/Position.cpp @@ -718,6 +718,7 @@ Position Position::upstream(EditingBoundaryCrossingRule rule) const // and upstream() will return the left one. // Also, downstream() will return the last position in the last atomic node in boundary for all of the positions // in boundary after the last candidate, where endsOfNodeAreVisuallyDistinctPositions(boundary). +// FIXME: This function should never be called when the line box tree is dirty. See https://bugs.webkit.org/show_bug.cgi?id=97264 Position Position::downstream(EditingBoundaryCrossingRule rule) const { Node* startNode = deprecatedNode(); diff --git a/Source/WebCore/editing/markup.cpp b/Source/WebCore/editing/markup.cpp index 10eea016b..3fecd9175 100644 --- a/Source/WebCore/editing/markup.cpp +++ b/Source/WebCore/editing/markup.cpp @@ -1026,7 +1026,7 @@ PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String& RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc); fragment->parseHTML(sourceString, fakeBody.get()); } else if (sourceMIMEType == "text/plain") - fragment->parserAddChild(Text::create(outputDoc, sourceString)); + fragment->parserAppendChild(Text::create(outputDoc, sourceString)); else { bool successfulParse = fragment->parseXML(sourceString, 0); if (!successfulParse) diff --git a/Source/WebCore/html/BaseButtonInputType.cpp b/Source/WebCore/html/BaseButtonInputType.cpp index d1ed27ba5..5fde8d799 100644 --- a/Source/WebCore/html/BaseButtonInputType.cpp +++ b/Source/WebCore/html/BaseButtonInputType.cpp @@ -36,62 +36,11 @@ #include "HTMLNames.h" #include "KeyboardEvent.h" #include "RenderButton.h" -#include "RenderTextFragment.h" -#include "ShadowRoot.h" -#include "Text.h" namespace WebCore { using namespace HTMLNames; -class TextForButtonInputType : public Text { -public: - static PassRefPtr<TextForButtonInputType> create(Document*, const String&); - -private: - TextForButtonInputType(Document*, const String&); - virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE; -}; - -PassRefPtr<TextForButtonInputType> TextForButtonInputType::create(Document* document, const String& data) -{ - return adoptRef(new TextForButtonInputType(document, data)); -} - -TextForButtonInputType::TextForButtonInputType(Document* document, const String& data) - : Text(document, data) -{ -} - -RenderObject* TextForButtonInputType::createRenderer(RenderArena* arena, RenderStyle*) -{ - return new (arena) RenderTextFragment(document(), dataImpl()); -} - -BaseButtonInputType::BaseButtonInputType(HTMLInputElement* element) - : BaseClickableWithKeyInputType(element) -{ -} - -void BaseButtonInputType::createShadowSubtree() -{ - ASSERT(element()->userAgentShadowRoot()); - - RefPtr<TextForButtonInputType> text = TextForButtonInputType::create(element()->document(), defaultValue()); - element()->userAgentShadowRoot()->appendChild(text); -} - -void BaseButtonInputType::destroyShadowSubtree() -{ - InputType::destroyShadowSubtree(); -} - -void BaseButtonInputType::valueAttributeChanged() -{ - String value = element()->valueWithDefault(); - toText(element()->userAgentShadowRoot()->firstChild())->setData(value, ASSERT_NO_EXCEPTION); -} - bool BaseButtonInputType::shouldSaveAndRestoreFormControlState() const { return false; diff --git a/Source/WebCore/html/BaseButtonInputType.h b/Source/WebCore/html/BaseButtonInputType.h index 3b8384c4e..4dfbb043f 100644 --- a/Source/WebCore/html/BaseButtonInputType.h +++ b/Source/WebCore/html/BaseButtonInputType.h @@ -38,14 +38,9 @@ namespace WebCore { // Base of button, file, image, reset, and submit types. class BaseButtonInputType : public BaseClickableWithKeyInputType { protected: - BaseButtonInputType(HTMLInputElement*); + BaseButtonInputType(HTMLInputElement* element) : BaseClickableWithKeyInputType(element) { } private: - virtual void createShadowSubtree() OVERRIDE; - virtual void destroyShadowSubtree() OVERRIDE; - - virtual void valueAttributeChanged() OVERRIDE; - virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE; virtual bool appendFormData(FormDataList&, bool) const OVERRIDE; virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE; diff --git a/Source/WebCore/html/FileInputType.cpp b/Source/WebCore/html/FileInputType.cpp index cc19f2a35..89fcc878e 100644 --- a/Source/WebCore/html/FileInputType.cpp +++ b/Source/WebCore/html/FileInputType.cpp @@ -62,7 +62,6 @@ private: PassRefPtr<UploadButtonElement> UploadButtonElement::create(Document* document) { RefPtr<UploadButtonElement> button = adoptRef(new UploadButtonElement(document)); - button->createShadowSubtree(); button->setType("button"); button->setValue(fileButtonChooseFileLabel()); return button.release(); @@ -71,7 +70,6 @@ PassRefPtr<UploadButtonElement> UploadButtonElement::create(Document* document) PassRefPtr<UploadButtonElement> UploadButtonElement::createForMultiple(Document* document) { RefPtr<UploadButtonElement> button = adoptRef(new UploadButtonElement(document)); - button->createShadowSubtree(); button->setType("button"); button->setValue(fileButtonChooseMultipleFilesLabel()); return button.release(); diff --git a/Source/WebCore/html/HTMLDialogElement.cpp b/Source/WebCore/html/HTMLDialogElement.cpp index 537432960..7d4d6451b 100644 --- a/Source/WebCore/html/HTMLDialogElement.cpp +++ b/Source/WebCore/html/HTMLDialogElement.cpp @@ -62,6 +62,15 @@ void HTMLDialogElement::show() setBooleanAttribute(openAttr, true); } +void HTMLDialogElement::showModal(ExceptionCode& ec) +{ + if (fastHasAttribute(openAttr) || !inDocument()) { + ec = INVALID_STATE_ERR; + return; + } + setBooleanAttribute(openAttr, true); +} + bool HTMLDialogElement::isPresentationAttribute(const QualifiedName& name) const { // FIXME: Workaround for <https://bugs.webkit.org/show_bug.cgi?id=91058>: modifying an attribute for which there is an attribute selector diff --git a/Source/WebCore/html/HTMLDialogElement.h b/Source/WebCore/html/HTMLDialogElement.h index 7a7b0119f..e01045bce 100644 --- a/Source/WebCore/html/HTMLDialogElement.h +++ b/Source/WebCore/html/HTMLDialogElement.h @@ -41,6 +41,7 @@ public: void close(ExceptionCode&); void show(); + void showModal(ExceptionCode&); private: HTMLDialogElement(const QualifiedName&, Document*); diff --git a/Source/WebCore/html/HTMLDialogElement.idl b/Source/WebCore/html/HTMLDialogElement.idl index 442f93fd8..3c70c0c53 100644 --- a/Source/WebCore/html/HTMLDialogElement.idl +++ b/Source/WebCore/html/HTMLDialogElement.idl @@ -31,6 +31,7 @@ module html { attribute [Reflect] boolean open; void close() raises(DOMException); void show(); + void showModal() raises(DOMException); }; } diff --git a/Source/WebCore/html/HTMLElement.cpp b/Source/WebCore/html/HTMLElement.cpp index 641c0b890..caf4ac939 100644 --- a/Source/WebCore/html/HTMLElement.cpp +++ b/Source/WebCore/html/HTMLElement.cpp @@ -30,7 +30,6 @@ #include "CSSPropertyNames.h" #include "CSSValueKeywords.h" #include "CSSValuePool.h" -#include "ChildListMutationScope.h" #include "DOMSettableTokenList.h" #include "DocumentFragment.h" #include "Event.h" diff --git a/Source/WebCore/html/HTMLInputElement.cpp b/Source/WebCore/html/HTMLInputElement.cpp index 4cfc2b7d8..d1ea76cae 100644 --- a/Source/WebCore/html/HTMLInputElement.cpp +++ b/Source/WebCore/html/HTMLInputElement.cpp @@ -677,7 +677,6 @@ void HTMLInputElement::parseAttribute(const Attribute& attribute) updatePlaceholderVisibility(false); setNeedsStyleRecalc(); } - m_inputType->valueAttributeChanged(); setFormControlValueMatchesRenderer(false); setNeedsValidityCheck(); m_valueAttributeWasUpdatedAfterParsing = !m_parsingInProgress; diff --git a/Source/WebCore/html/HTMLMediaElement.cpp b/Source/WebCore/html/HTMLMediaElement.cpp index 5f5674517..66b8c4655 100644 --- a/Source/WebCore/html/HTMLMediaElement.cpp +++ b/Source/WebCore/html/HTMLMediaElement.cpp @@ -3675,6 +3675,7 @@ void HTMLMediaElement::stop() userCancelledLoad(); // Stop the playback without generating events + m_playing = false; setPausedInternal(true); if (renderer()) diff --git a/Source/WebCore/html/HTMLViewSourceDocument.cpp b/Source/WebCore/html/HTMLViewSourceDocument.cpp index 80cdd69cd..3de813770 100644 --- a/Source/WebCore/html/HTMLViewSourceDocument.cpp +++ b/Source/WebCore/html/HTMLViewSourceDocument.cpp @@ -70,24 +70,24 @@ PassRefPtr<DocumentParser> HTMLViewSourceDocument::createParser() void HTMLViewSourceDocument::createContainingTable() { RefPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(this); - parserAddChild(html); + parserAppendChild(html); html->attach(); RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(this); - html->parserAddChild(body); + html->parserAppendChild(body); body->attach(); // Create a line gutter div that can be used to make sure the gutter extends down the height of the whole // document. RefPtr<HTMLDivElement> div = HTMLDivElement::create(this); div->setAttribute(classAttr, "webkit-line-gutter-backdrop"); - body->parserAddChild(div); + body->parserAppendChild(div); div->attach(); RefPtr<HTMLTableElement> table = HTMLTableElement::create(this); - body->parserAddChild(table); + body->parserAppendChild(table); table->attach(); m_tbody = HTMLTableSectionElement::create(tbodyTag, this); - table->parserAddChild(m_tbody); + table->parserAppendChild(m_tbody); m_tbody->attach(); m_current = m_tbody; } @@ -186,7 +186,7 @@ PassRefPtr<Element> HTMLViewSourceDocument::addSpanWithClassName(const AtomicStr RefPtr<HTMLElement> span = HTMLElement::create(spanTag, this); span->setAttribute(classAttr, className); - m_current->parserAddChild(span); + m_current->parserAppendChild(span); span->attach(); return span.release(); } @@ -195,19 +195,19 @@ void HTMLViewSourceDocument::addLine(const AtomicString& className) { // Create a table row. RefPtr<HTMLTableRowElement> trow = HTMLTableRowElement::create(this); - m_tbody->parserAddChild(trow); + m_tbody->parserAppendChild(trow); trow->attach(); // 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"); - trow->parserAddChild(td); + trow->parserAppendChild(td); td->attach(); // Create a second cell for the line contents td = HTMLTableCellElement::create(tdTag, this); td->setAttribute(classAttr, "webkit-line-content"); - trow->parserAddChild(td); + trow->parserAppendChild(td); td->attach(); m_current = m_td = td; @@ -229,7 +229,7 @@ void HTMLViewSourceDocument::finishLine() { if (!m_current->hasChildNodes()) { RefPtr<HTMLBRElement> br = HTMLBRElement::create(this); - m_current->parserAddChild(br); + m_current->parserAppendChild(br); br->attach(); } m_current = m_tbody; @@ -255,7 +255,7 @@ void HTMLViewSourceDocument::addText(const String& text, const AtomicString& cla continue; } RefPtr<Text> t = Text::create(this, substring); - m_current->parserAddChild(t); + m_current->parserAppendChild(t); t->attach(); if (i < size - 1) finishLine(); @@ -285,7 +285,7 @@ PassRefPtr<Element> HTMLViewSourceDocument::addBase(const AtomicString& href) { RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(baseTag, this); base->setAttribute(hrefAttr, href); - m_current->parserAddChild(base); + m_current->parserAppendChild(base); base->attach(); return base.release(); } @@ -305,7 +305,7 @@ PassRefPtr<Element> HTMLViewSourceDocument::addLink(const AtomicString& url, boo anchor->setAttribute(classAttr, classValue); anchor->setAttribute(targetAttr, "_blank"); anchor->setAttribute(hrefAttr, url); - m_current->parserAddChild(anchor); + m_current->parserAppendChild(anchor); anchor->attach(); return anchor.release(); } diff --git a/Source/WebCore/html/InputType.cpp b/Source/WebCore/html/InputType.cpp index 1a078f250..38d79eea8 100644 --- a/Source/WebCore/html/InputType.cpp +++ b/Source/WebCore/html/InputType.cpp @@ -889,10 +889,6 @@ void InputType::updatePlaceholderText() { } -void InputType::valueAttributeChanged() -{ -} - void InputType::multipleAttributeChanged() { } diff --git a/Source/WebCore/html/InputType.h b/Source/WebCore/html/InputType.h index 29d8cc30c..87a4c12a8 100644 --- a/Source/WebCore/html/InputType.h +++ b/Source/WebCore/html/InputType.h @@ -278,7 +278,6 @@ public: virtual String fixedPlaceholder(); virtual void updateInnerTextValue(); virtual void updatePlaceholderText(); - virtual void valueAttributeChanged(); virtual void multipleAttributeChanged(); virtual void disabledAttributeChanged(); virtual void readonlyAttributeChanged(); diff --git a/Source/WebCore/html/TimeInputType.cpp b/Source/WebCore/html/TimeInputType.cpp index c1597ecbb..4b5bb1f15 100644 --- a/Source/WebCore/html/TimeInputType.cpp +++ b/Source/WebCore/html/TimeInputType.cpp @@ -46,6 +46,7 @@ #include "ElementShadow.h" #include "FormController.h" #include "KeyboardEvent.h" +#include "Localizer.h" #include "ShadowRoot.h" #endif @@ -304,14 +305,25 @@ void TimeInputType::updateInnerTextValue() return; Localizer& localizer = element()->document()->getLocalizer(element()->computeInheritedLanguage()); - const StepRange stepRange(createStepRange(AnyIsDefaultStep)); + DateTimeEditElement::LayoutParameters layoutParameters(localizer, createStepRange(AnyIsDefaultStep)); + DateComponents date; - if (parseToDateComponents(element()->value(), &date)) - m_dateTimeEditElement->setValueAsDate(stepRange, date, localizer); - else { - setMillisecondToDateComponents(stepRange.minimum().toDouble(), &date); - m_dateTimeEditElement->setEmptyValue(stepRange, date, localizer); + const bool hasValue = parseToDateComponents(element()->value(), &date); + if (!hasValue) + setMillisecondToDateComponents(layoutParameters.stepRange.minimum().toDouble(), &date); + + if (date.second() || layoutParameters.shouldHaveSecondField()) { + layoutParameters.dateTimeFormat = localizer.timeFormat(); + layoutParameters.fallbackDateTimeFormat = "HH:mm:ss"; + } else { + layoutParameters.dateTimeFormat = localizer.shortTimeFormat(); + layoutParameters.fallbackDateTimeFormat = "HH:mm"; } + + if (hasValue) + m_dateTimeEditElement->setValueAsDate(layoutParameters, date); + else + m_dateTimeEditElement->setEmptyValue(layoutParameters, date); } #else TimeInputType::TimeInputType(HTMLInputElement* element) diff --git a/Source/WebCore/html/canvas/WebGLRenderingContext.cpp b/Source/WebCore/html/canvas/WebGLRenderingContext.cpp index 24b9c33f9..582ed5d39 100644 --- a/Source/WebCore/html/canvas/WebGLRenderingContext.cpp +++ b/Source/WebCore/html/canvas/WebGLRenderingContext.cpp @@ -1544,22 +1544,8 @@ void WebGLRenderingContext::deleteBuffer(WebGLBuffer* buffer) return; if (m_boundArrayBuffer == buffer) m_boundArrayBuffer = 0; - RefPtr<WebGLBuffer> elementArrayBuffer = m_boundVertexArrayObject->getElementArrayBuffer(); - if (elementArrayBuffer == buffer) - m_boundVertexArrayObject->setElementArrayBuffer(0); - if (!isGLES2Compliant()) { - WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(0); - if (buffer == state.bufferBinding) { - state.bufferBinding = m_vertexAttrib0Buffer; - state.bytesPerElement = 0; - state.size = 4; - state.type = GraphicsContext3D::FLOAT; - state.normalized = false; - state.stride = 16; - state.originalStride = 0; - state.offset = 0; - } - } + + m_boundVertexArrayObject->unbindBuffer(buffer); } void WebGLRenderingContext::deleteFramebuffer(WebGLFramebuffer* framebuffer) @@ -4383,17 +4369,7 @@ void WebGLRenderingContext::vertexAttribPointer(GC3Duint index, GC3Dint size, GC } GC3Dsizei bytesPerElement = size * typeSize; - GC3Dsizei validatedStride = stride ? stride : bytesPerElement; - - WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(index); - state.bufferBinding = m_boundArrayBuffer; - state.bytesPerElement = bytesPerElement; - state.size = size; - state.type = type; - state.normalized = normalized; - state.stride = validatedStride; - state.originalStride = stride; - state.offset = static_cast<GC3Dintptr>(offset); + m_boundVertexArrayObject->setVertexAttribState(index, bytesPerElement, size, type, normalized, stride, static_cast<GC3Dintptr>(offset), m_boundArrayBuffer); m_context->vertexAttribPointer(index, size, type, normalized, stride, static_cast<GC3Dintptr>(offset)); cleanupAfterGraphicsCall(false); } diff --git a/Source/WebCore/html/canvas/WebGLRenderingContext.h b/Source/WebCore/html/canvas/WebGLRenderingContext.h index 6023b4462..45df6a582 100644 --- a/Source/WebCore/html/canvas/WebGLRenderingContext.h +++ b/Source/WebCore/html/canvas/WebGLRenderingContext.h @@ -322,6 +322,7 @@ public: friend class WebGLDebugShaders; friend class WebGLCompressedTextureS3TC; friend class WebGLRenderingContextErrorMessageCallback; + friend class WebGLVertexArrayObjectOES; WebGLRenderingContext(HTMLCanvasElement*, PassRefPtr<GraphicsContext3D>, GraphicsContext3D::Attributes); void initializeNewContext(); diff --git a/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.cpp b/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.cpp index 4aa03b8fe..a98d092e8 100644 --- a/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.cpp +++ b/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.cpp @@ -72,6 +72,75 @@ void WebGLVertexArrayObjectOES::deleteObjectImpl(GraphicsContext3D* context3d, P extensions->deleteVertexArrayOES(object); break; } + + if (m_boundElementArrayBuffer) + m_boundElementArrayBuffer->onDetached(context3d); + + for (size_t i = 0; i < m_vertexAttribState.size(); ++i) { + VertexAttribState& state = m_vertexAttribState[i]; + if (state.bufferBinding) + state.bufferBinding->onDetached(context3d); + } +} + +void WebGLVertexArrayObjectOES::setElementArrayBuffer(PassRefPtr<WebGLBuffer> buffer) +{ + if (buffer) + buffer->onAttached(); + if (m_boundElementArrayBuffer) + m_boundElementArrayBuffer->onDetached(context()->graphicsContext3D()); + m_boundElementArrayBuffer = buffer; + +} + +void WebGLVertexArrayObjectOES::setVertexAttribState( + GC3Duint index, GC3Dsizei bytesPerElement, GC3Dint size, GC3Denum type, GC3Dboolean normalized, GC3Dsizei stride, GC3Dintptr offset, PassRefPtr<WebGLBuffer> buffer) +{ + GC3Dsizei validatedStride = stride ? stride : bytesPerElement; + + VertexAttribState& state = m_vertexAttribState[index]; + + if (buffer) + buffer->onAttached(); + if (state.bufferBinding) + state.bufferBinding->onDetached(context()->graphicsContext3D()); + + state.bufferBinding = buffer; + state.bytesPerElement = bytesPerElement; + state.size = size; + state.type = type; + state.normalized = normalized; + state.stride = validatedStride; + state.originalStride = stride; + state.offset = offset; +} + +void WebGLVertexArrayObjectOES::unbindBuffer(PassRefPtr<WebGLBuffer> buffer) +{ + if (m_boundElementArrayBuffer == buffer) { + m_boundElementArrayBuffer->onDetached(context()->graphicsContext3D()); + m_boundElementArrayBuffer = 0; + } + + for (size_t i = 0; i < m_vertexAttribState.size(); ++i) { + VertexAttribState& state = m_vertexAttribState[i]; + if (state.bufferBinding == buffer) { + buffer->onDetached(context()->graphicsContext3D()); + + if (!i && !context()->isGLES2Compliant()) { + state.bufferBinding = context()->m_vertexAttrib0Buffer; + state.bufferBinding->onAttached(); + state.bytesPerElement = 0; + state.size = 4; + state.type = GraphicsContext3D::FLOAT; + state.normalized = false; + state.stride = 16; + state.originalStride = 0; + state.offset = 0; + } else + state.bufferBinding = 0; + } + } } } diff --git a/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.h b/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.h index 75ae42ff7..b660de588 100644 --- a/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.h +++ b/Source/WebCore/html/canvas/WebGLVertexArrayObjectOES.h @@ -76,9 +76,11 @@ public: void setHasEverBeenBound() { m_hasEverBeenBound = true; } PassRefPtr<WebGLBuffer> getElementArrayBuffer() const { return m_boundElementArrayBuffer; } - void setElementArrayBuffer(PassRefPtr<WebGLBuffer> buffer) { m_boundElementArrayBuffer = buffer; } + void setElementArrayBuffer(PassRefPtr<WebGLBuffer>); VertexAttribState& getVertexAttribState(int index) { return m_vertexAttribState[index]; } + void setVertexAttribState(GC3Duint, GC3Dsizei, GC3Dint, GC3Denum, GC3Dboolean, GC3Dsizei, GC3Dintptr, PassRefPtr<WebGLBuffer>); + void unbindBuffer(PassRefPtr<WebGLBuffer>); private: WebGLVertexArrayObjectOES(WebGLRenderingContext*, VaoType); diff --git a/Source/WebCore/html/parser/HTMLConstructionSite.cpp b/Source/WebCore/html/parser/HTMLConstructionSite.cpp index fc9d7c664..0d66be471 100644 --- a/Source/WebCore/html/parser/HTMLConstructionSite.cpp +++ b/Source/WebCore/html/parser/HTMLConstructionSite.cpp @@ -80,7 +80,7 @@ static inline void executeTask(HTMLConstructionSiteTask& task) if (task.nextChild) task.parent->parserInsertBefore(task.child.get(), task.nextChild.get()); else - task.parent->parserAddChild(task.child.get()); + task.parent->parserAppendChild(task.child.get()); // JavaScript run from beforeload (or DOM Mutation or event handlers) // might have removed the child, in which case we should not attach it. diff --git a/Source/WebCore/html/parser/HTMLTreeBuilder.cpp b/Source/WebCore/html/parser/HTMLTreeBuilder.cpp index 3e9b303c6..131cdbff6 100644 --- a/Source/WebCore/html/parser/HTMLTreeBuilder.cpp +++ b/Source/WebCore/html/parser/HTMLTreeBuilder.cpp @@ -1488,7 +1488,7 @@ void HTMLTreeBuilder::callTheAdoptionAgency(AtomicHTMLToken* token) // 9.9 if (ContainerNode* parent = lastNode->element()->parentNode()) parent->parserRemoveChild(lastNode->element()); - node->element()->parserAddChild(lastNode->element()); + node->element()->parserAppendChild(lastNode->element()); if (lastNode->element()->parentElement()->attached() && !lastNode->element()->attached()) lastNode->element()->lazyAttach(); // 9.10 @@ -1500,7 +1500,7 @@ void HTMLTreeBuilder::callTheAdoptionAgency(AtomicHTMLToken* token) if (commonAncestor->causesFosterParenting()) m_tree.fosterParent(lastNode->element()); else { - commonAncestor->node()->parserAddChild(lastNode->element()); + commonAncestor->node()->parserAppendChild(lastNode->element()); ASSERT(lastNode->stackItem()->isElementNode()); ASSERT(lastNode->element()->parentNode()); if (lastNode->element()->parentNode()->attached() && !lastNode->element()->attached()) @@ -1512,10 +1512,10 @@ void HTMLTreeBuilder::callTheAdoptionAgency(AtomicHTMLToken* token) newItem->element()->takeAllChildrenFrom(furthestBlock->element()); // 13. Element* furthestBlockElement = furthestBlock->element(); - // FIXME: All this creation / parserAddChild / attach business should + // FIXME: All this creation / parserAppendChild / attach business should // be in HTMLConstructionSite. My guess is that steps 11--15 // should all be in some HTMLConstructionSite function. - furthestBlockElement->parserAddChild(newItem->element()); + furthestBlockElement->parserAppendChild(newItem->element()); // FIXME: Why is this attach logic necessary? Style resolve should attach us if needed. if (furthestBlockElement->attached() && !newItem->element()->attached()) { // Notice that newItem->element() might already be attached if, for example, one of the reparented diff --git a/Source/WebCore/html/shadow/CalendarPickerElement.cpp b/Source/WebCore/html/shadow/CalendarPickerElement.cpp index 28d78d1d5..7513f5b71 100644 --- a/Source/WebCore/html/shadow/CalendarPickerElement.cpp +++ b/Source/WebCore/html/shadow/CalendarPickerElement.cpp @@ -37,7 +37,9 @@ #include "ChromeClient.h" #include "Event.h" #include "FrameView.h" +#include "HTMLDataListElement.h" #include "HTMLInputElement.h" +#include "HTMLOptionElement.h" #include "Page.h" #include "RenderDetailsMarker.h" @@ -140,7 +142,16 @@ void CalendarPickerElement::openPopup() parameters.step = step.toDouble(); parameters.anchorRectInRootView = document()->view()->contentsToRootView(hostInput()->pixelSnappedBoundingBox()); parameters.currentValue = input->value(); - // FIXME: parameters.suggestionValues and suggestionLabels will be used when we support datalist. + if (HTMLDataListElement* dataList = input->dataList()) { + RefPtr<HTMLCollection> options = dataList->options(); + for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) { + if (!input->isValidValue(option->value())) + continue; + parameters.suggestionValues.append(input->sanitizeValue(option->value())); + parameters.localizedSuggestionValues.append(input->localizeValue(option->value())); + parameters.suggestionLabels.append(option->value() == option->label() ? String() : option->label()); + } + } m_chooser = chrome->client()->openDateTimeChooser(this, parameters); } diff --git a/Source/WebCore/html/shadow/DateTimeEditElement.cpp b/Source/WebCore/html/shadow/DateTimeEditElement.cpp index e9aa858cc..07befd874 100644 --- a/Source/WebCore/html/shadow/DateTimeEditElement.cpp +++ b/Source/WebCore/html/shadow/DateTimeEditElement.cpp @@ -35,11 +35,8 @@ #include "EventHandler.h" #include "HTMLNames.h" #include "KeyboardEvent.h" -#include "LocalizedDate.h" -#include "LocalizedNumber.h" #include "Localizer.h" #include "MouseEvent.h" -#include "StepRange.h" #include "Text.h" #include <wtf/DateMath.h> #include <wtf/text/StringBuilder.h> @@ -52,14 +49,12 @@ class DateTimeEditBuilder : private DateTimeFormat::TokenHandler { WTF_MAKE_NONCOPYABLE(DateTimeEditBuilder); public: - DateTimeEditBuilder(DateTimeEditElement&, const StepRange&, const DateComponents&, Localizer&); + DateTimeEditBuilder(DateTimeEditElement&, const DateTimeEditElement::LayoutParameters&, const DateComponents&); bool build(const String&); - bool needSecondField() const; private: bool needMillisecondField() const; - bool needMinuteField() const; bool shouldMillisecondFieldReadOnly() const; bool shouldMinuteFieldReadOnly() const; bool shouldSecondFieldReadOnly() const; @@ -74,11 +69,11 @@ private: Localizer& m_localizer; }; -DateTimeEditBuilder::DateTimeEditBuilder(DateTimeEditElement& elemnt, const StepRange& stepRange, const DateComponents& dateValue, Localizer& localizer) +DateTimeEditBuilder::DateTimeEditBuilder(DateTimeEditElement& elemnt, const DateTimeEditElement::LayoutParameters& layoutParameters, const DateComponents& dateValue) : m_editElement(elemnt) , m_dateValue(dateValue) - , m_stepRange(stepRange) - , m_localizer(localizer) + , m_stepRange(layoutParameters.stepRange) + , m_localizer(layoutParameters.localizer) { } @@ -95,20 +90,6 @@ bool DateTimeEditBuilder::needMillisecondField() const || !m_stepRange.step().remainder(static_cast<int>(msPerSecond)).isZero(); } -bool DateTimeEditBuilder::needMinuteField() const -{ - return m_dateValue.minute() - || !m_stepRange.minimum().remainder(static_cast<int>(msPerHour)).isZero() - || !m_stepRange.step().remainder(static_cast<int>(msPerHour)).isZero(); -} - -bool DateTimeEditBuilder::needSecondField() const -{ - return m_dateValue.second() - || !m_stepRange.minimum().remainder(static_cast<int>(msPerMinute)).isZero() - || !m_stepRange.step().remainder(static_cast<int>(msPerMinute)).isZero(); -} - void DateTimeEditBuilder::visitField(DateTimeFormat::FieldType fieldType, int) { Document* const document = m_editElement.document(); @@ -191,6 +172,15 @@ void DateTimeEditBuilder::visitLiteral(const String& text) // ---------------------------- + +bool DateTimeEditElement::LayoutParameters::shouldHaveSecondField() const +{ + return !stepRange.minimum().remainder(static_cast<int>(msPerMinute)).isZero() + || !stepRange.step().remainder(static_cast<int>(msPerMinute)).isZero(); +} + +// ---------------------------- + DateTimeEditElement::EditControlOwner::~EditControlOwner() { } @@ -340,18 +330,17 @@ bool DateTimeEditElement::isReadOnly() const return m_editControlOwner && m_editControlOwner->isEditControlOwnerReadOnly(); } -void DateTimeEditElement::layout(const StepRange& stepRange, const DateComponents& dateValue, Localizer& localizer) +void DateTimeEditElement::layout(const LayoutParameters& layoutParameters, const DateComponents& dateValue) { size_t focusedFieldIndex = this->focusedFieldIndex(); DateTimeFieldElement* const focusedField = fieldAt(focusedFieldIndex); const AtomicString focusedFieldId = focusedField ? focusedField->shadowPseudoId() : nullAtom; - DateTimeEditBuilder builder(*this, stepRange, dateValue, localizer); - const String dateTimeFormat = builder.needSecondField() ? localizer.timeFormat() : localizer.shortTimeFormat(); + DateTimeEditBuilder builder(*this, layoutParameters, dateValue); Node* lastChildToBeRemoved = lastChild(); - if (!builder.build(dateTimeFormat) || m_fields.isEmpty()) { + if (!builder.build(layoutParameters.dateTimeFormat) || m_fields.isEmpty()) { lastChildToBeRemoved = lastChild(); - builder.build(builder.needSecondField() ? "HH:mm:ss" : "HH:mm"); + builder.build(layoutParameters.fallbackDateTimeFormat); } if (focusedFieldIndex != invalidFieldIndex) { @@ -407,9 +396,9 @@ void DateTimeEditElement::defaultEventHandler(Event* event) HTMLDivElement::defaultEventHandler(event); } -void DateTimeEditElement::setValueAsDate(const StepRange& stepRange, const DateComponents& date, Localizer& localizer) +void DateTimeEditElement::setValueAsDate(const LayoutParameters& layoutParameters, const DateComponents& date) { - layout(stepRange, date, localizer); + layout(layoutParameters, date); for (size_t fieldIndex = 0; fieldIndex < m_fields.size(); ++fieldIndex) m_fields[fieldIndex]->setValueAsDate(date); } @@ -420,9 +409,9 @@ void DateTimeEditElement::setValueAsDateTimeFieldsState(const DateTimeFieldsStat m_fields[fieldIndex]->setValueAsDateTimeFieldsState(dateTimeFieldsState, dateForReadOnlyField); } -void DateTimeEditElement::setEmptyValue(const StepRange& stepRange, const DateComponents& dateForReadOnlyField, Localizer& localizer) +void DateTimeEditElement::setEmptyValue(const LayoutParameters& layoutParameters, const DateComponents& dateForReadOnlyField) { - layout(stepRange, dateForReadOnlyField, localizer); + layout(layoutParameters, dateForReadOnlyField); for (size_t fieldIndex = 0; fieldIndex < m_fields.size(); ++fieldIndex) m_fields[fieldIndex]->setEmptyValue(dateForReadOnlyField, DateTimeFieldElement::DispatchNoEvent); } diff --git a/Source/WebCore/html/shadow/DateTimeEditElement.h b/Source/WebCore/html/shadow/DateTimeEditElement.h index c17bd7a7a..e547cbdea 100644 --- a/Source/WebCore/html/shadow/DateTimeEditElement.h +++ b/Source/WebCore/html/shadow/DateTimeEditElement.h @@ -29,11 +29,10 @@ #if ENABLE(INPUT_TYPE_TIME_MULTIPLE_FIELDS) #include "DateTimeFieldElement.h" #include "SpinButtonElement.h" +#include "StepRange.h" namespace WebCore { -class DateComponents; -class DateTimeEditLayouter; class DateTimeFieldsState; class KeyboardEvent; class Localizer; @@ -60,6 +59,21 @@ public: virtual bool isEditControlOwnerReadOnly() const = 0; }; + struct LayoutParameters { + String dateTimeFormat; + String fallbackDateTimeFormat; + Localizer& localizer; + const StepRange& stepRange; + + LayoutParameters(Localizer& localizer, const StepRange& stepRange) + : localizer(localizer) + , stepRange(stepRange) + { + } + + bool shouldHaveSecondField() const; + }; + static PassRefPtr<DateTimeEditElement> create(Document*, EditControlOwner&); virtual ~DateTimeEditElement(); @@ -71,8 +85,8 @@ public: void readOnlyStateChanged(); void removeEditControlOwner() { m_editControlOwner = 0; } void resetFields(); - void setEmptyValue(const StepRange&, const DateComponents& dateForReadOnlyField, Localizer&); - void setValueAsDate(const StepRange&, const DateComponents&, Localizer&); + void setEmptyValue(const LayoutParameters&, const DateComponents& dateForReadOnlyField); + void setValueAsDate(const LayoutParameters&, const DateComponents&); void setValueAsDateTimeFieldsState(const DateTimeFieldsState&, const DateComponents& dateForReadOnlyField); DateTimeFieldsState valueAsDateTimeFieldsState() const; double valueAsDouble() const; @@ -99,7 +113,7 @@ private: size_t focusedFieldIndex() const; bool isDisabled() const; bool isReadOnly() const; - void layout(const StepRange&, const DateComponents&, Localizer&); + void layout(const LayoutParameters&, const DateComponents&); void updateUIState(); // DateTimeFieldElement::FieldOwner functions. diff --git a/Source/WebCore/html/track/WebVTTParser.cpp b/Source/WebCore/html/track/WebVTTParser.cpp index fe47d2258..297e5996b 100644 --- a/Source/WebCore/html/track/WebVTTParser.cpp +++ b/Source/WebCore/html/track/WebVTTParser.cpp @@ -351,7 +351,7 @@ void WebVTTParser::constructTreeFromToken(Document* document) case WebVTTTokenTypes::Character: { String content(m_token.characters().data(), m_token.characters().size()); RefPtr<Text> child = Text::create(document, content); - m_currentNode->parserAddChild(child); + m_currentNode->parserAppendChild(child); break; } case WebVTTTokenTypes::StartTag: { @@ -368,7 +368,7 @@ void WebVTTParser::constructTreeFromToken(Document* document) child->setAttribute(classAttr, AtomicString(m_token.classes().data(), m_token.classes().size())); if (child->hasTagName(qTag)) child->setAttribute(titleAttr, AtomicString(m_token.annotation().data(), m_token.annotation().size())); - m_currentNode->parserAddChild(child); + m_currentNode->parserAppendChild(child); m_currentNode = child; } break; @@ -385,7 +385,7 @@ void WebVTTParser::constructTreeFromToken(Document* document) unsigned position = 0; double time = collectTimeStamp(m_token.characters().data(), &position); if (time != malformedTime) - m_currentNode->parserAddChild(ProcessingInstruction::create(document, "timestamp", String(m_token.characters().data(), m_token.characters().size()))); + m_currentNode->parserAppendChild(ProcessingInstruction::create(document, "timestamp", String(m_token.characters().data(), m_token.characters().size()))); break; } default: diff --git a/Source/WebCore/inspector/InspectorOverlayPage.html b/Source/WebCore/inspector/InspectorOverlayPage.html index 8bc9ef667..20c421813 100644 --- a/Source/WebCore/inspector/InspectorOverlayPage.html +++ b/Source/WebCore/inspector/InspectorOverlayPage.html @@ -94,6 +94,7 @@ body.platform-linux { const lightGridColor = "rgba(0,0,0,0.2)"; const darkGridColor = "rgba(0,0,0,0.5)"; const transparentColor = "rgba(0, 0, 0, 0)"; +const gridBackgroundColor = "rgba(255, 255, 255, 0.6)"; function drawPausedInDebuggerMessage(message) { @@ -103,74 +104,119 @@ function drawPausedInDebuggerMessage(message) document.body.classList.add("dimmed"); } -function _drawGrid(highlight) +function _drawGrid(highlight, rulerAtRight, rulerAtBottom) { context.save(); var width = canvas.width; var height = canvas.height; - context.fillStyle = "rgba(255, 255, 255, 0.6)"; - context.fillRect(0, 0, canvas.width, 15); - context.fillRect(0, 15, 15, canvas.height); - - context.translate(-highlight.scrollX, 0.5 - highlight.scrollY); - context.lineWidth = 1; - const gridSubStep = 5; const gridStep = 50; - context.strokeStyle = lightGridColor; - - for (var y = gridSubStep; y < highlight.scrollY + height; y += gridSubStep) { - if (!(y % gridStep)) - continue; - context.beginPath(); - context.moveTo(highlight.scrollX, y); - context.lineTo(highlight.scrollX + gridSubStep, y); - context.stroke(); + { + // Draw X grid background + context.save(); + context.fillStyle = gridBackgroundColor; + if (rulerAtBottom) + context.fillRect(0, height - 15, width, height); + else + context.fillRect(0, 0, width, 15); + + // Clip out backgrounds intersection + context.globalCompositeOperation = "destination-out"; + context.fillStyle = "red"; + if (rulerAtRight) + context.fillRect(width - 15, 0, width, height); + else + context.fillRect(0, 0, 15, height); + context.restore(); + + // Draw Y grid background + context.fillStyle = gridBackgroundColor; + if (rulerAtRight) + context.fillRect(width - 15, 0, width, height); + else + context.fillRect(0, 0, 15, height); } + context.lineWidth = 1; context.strokeStyle = darkGridColor; context.fillStyle = darkGridColor; - for (var y = gridStep; y < height + highlight.scrollY; y += gridStep) { - context.beginPath(); - context.moveTo(highlight.scrollX, y); - var markLength = (y % (gridStep * 2)) ? 5 : 8; - context.lineTo(highlight.scrollX + markLength, y); - context.stroke(); - if (!(y % (gridStep * 2))) { + { + // Draw labels. + context.save(); + context.translate(-highlight.scrollX, 0.5 - highlight.scrollY); + for (var y = 2 * gridStep; y < height + highlight.scrollY; y += 2 * gridStep) { context.save(); context.translate(highlight.scrollX, y); context.rotate(-Math.PI / 2); - context.fillText(y, 2, 13); + context.fillText(y, 2, rulerAtRight ? width - 7 : 13); context.restore(); } + context.translate(0.5, -0.5); + for (var x = 2 * gridStep; x < width + highlight.scrollX; x += 2 * gridStep) { + context.save(); + context.fillText(x, x + 2, rulerAtBottom ? highlight.scrollY + height - 7 : highlight.scrollY + 13); + context.restore(); + } + context.restore(); } - context.translate(0.5, -0.5); - - context.strokeStyle = lightGridColor; - for (var x = gridSubStep; x < highlight.scrollX + width; x += gridSubStep) { - if (!(x % gridStep)) - continue; - context.beginPath(); - context.moveTo(x, highlight.scrollY); - context.lineTo(x, highlight.scrollY + gridSubStep); - context.stroke(); + { + // Draw vertical grid + context.save(); + if (rulerAtRight) { + context.translate(width, 0); + context.scale(-1, 1); + } + context.translate(-highlight.scrollX, 0.5 - highlight.scrollY); + for (var y = gridStep; y < height + highlight.scrollY; y += gridStep) { + context.beginPath(); + context.moveTo(highlight.scrollX, y); + var markLength = (y % (gridStep * 2)) ? 5 : 8; + context.lineTo(highlight.scrollX + markLength, y); + context.stroke(); + } + context.strokeStyle = lightGridColor; + for (var y = gridSubStep; y < highlight.scrollY + height; y += gridSubStep) { + if (!(y % gridStep)) + continue; + context.beginPath(); + context.moveTo(highlight.scrollX, y); + context.lineTo(highlight.scrollX + gridSubStep, y); + context.stroke(); + } + context.restore(); } - context.strokeStyle = darkGridColor; - context.fillStyle = darkGridColor; - for (var x = gridStep; x < width + highlight.scrollX; x += gridStep) { - context.beginPath(); - context.moveTo(x, highlight.scrollY); - var markLength = (x % (gridStep * 2)) ? 5 : 8; - context.lineTo(x, highlight.scrollY + markLength); - context.stroke(); - if (!(x % (gridStep * 2))) - context.fillText(x, x + 2, highlight.scrollY + 13); + { + // Draw horizontal grid + context.save(); + if (rulerAtBottom) { + context.translate(0, height); + context.scale(1, -1); + } + context.translate(0.5 - highlight.scrollX, -highlight.scrollY); + for (var x = gridStep; x < width + highlight.scrollX; x += gridStep) { + context.beginPath(); + context.moveTo(x, highlight.scrollY); + var markLength = (x % (gridStep * 2)) ? 5 : 8; + context.lineTo(x, highlight.scrollY + markLength); + context.stroke(); + } + context.strokeStyle = lightGridColor; + for (var x = gridSubStep; x < highlight.scrollX + width; x += gridSubStep) { + if (!(x % gridStep)) + continue; + context.beginPath(); + context.moveTo(x, highlight.scrollY); + context.lineTo(x, highlight.scrollY + gridSubStep); + context.stroke(); + } + context.restore(); } + context.restore(); } @@ -310,38 +356,62 @@ function _drawElementTitle(highlight) elementTitle.style.left = (boxX + 3) + "px"; } -function _drawRulers(highlight) +function _drawRulers(highlight, rulerAtRight, rulerAtBottom) { context.save(); + var width = canvas.width; + var height = canvas.height; context.strokeStyle = "rgba(128, 128, 128, 0.3)"; context.lineWidth = 1; context.translate(0.5, 0.5); var leftmostXForY = {}; + var rightmostXForY = {}; var topmostYForX = {}; + var bottommostYForX = {}; for (var i = 0; i < highlight.quads.length; ++i) { var quad = highlight.quads[i]; for (var j = 0; j < quad.length; ++j) { var x = quad[j].x; var y = quad[j].y; - topmostYForX[Math.round(x)] = Math.min(topmostYForX[x] || Number.MAX_VALUE, Math.round(quad[j].y)); leftmostXForY[Math.round(y)] = Math.min(leftmostXForY[y] || Number.MAX_VALUE, Math.round(quad[j].x)); + rightmostXForY[Math.round(y)] = Math.max(rightmostXForY[y] || Number.MIN_VALUE, Math.round(quad[j].x)); + topmostYForX[Math.round(x)] = Math.min(topmostYForX[x] || Number.MAX_VALUE, Math.round(quad[j].y)); + bottommostYForX[Math.round(x)] = Math.max(bottommostYForX[x] || Number.MIN_VALUE, Math.round(quad[j].y)); } } - for (var y in leftmostXForY) { - context.beginPath(); - context.moveTo(0, y); - context.lineTo(leftmostXForY[y], y); - context.stroke(); + if (rulerAtRight) { + for (var y in rightmostXForY) { + context.beginPath(); + context.moveTo(width, y); + context.lineTo(rightmostXForY[y], y); + context.stroke(); + } + } else { + for (var y in leftmostXForY) { + context.beginPath(); + context.moveTo(0, y); + context.lineTo(leftmostXForY[y], y); + context.stroke(); + } } - for (var x in topmostYForX) { - context.beginPath(); - context.moveTo(x, 0); - context.lineTo(x, topmostYForX[x]); - context.stroke(); - } + if (rulerAtBottom) { + for (var x in bottommostYForX) { + context.beginPath(); + context.moveTo(x, height); + context.lineTo(x, topmostYForX[x]); + context.stroke(); + } + } else { + for (var x in topmostYForX) { + context.beginPath(); + context.moveTo(x, 0); + context.lineTo(x, topmostYForX[x]); + context.stroke(); + } + } context.restore(); } @@ -349,7 +419,7 @@ function _drawRulers(highlight) function drawNodeHighlight(highlight) { if (!highlight.quads.length) { - _drawGrid(highlight); + _drawGrid(highlight, false, false); return; } @@ -390,9 +460,25 @@ function drawNodeHighlight(highlight) if (hasContent) drawOutlinedQuad(contentQuad, highlight.contentColor, highlight.contentOutlineColor); - _drawGrid(highlight); + var width = canvas.width; + var height = canvas.height; + var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE; maxY = Number.MIN_VALUE; + for (var i = 0; i < highlight.quads.length; ++i) { + var quad = highlight.quads[i]; + for (var j = 0; j < quad.length; ++j) { + minX = Math.min(minX, quad[j].x); + maxX = Math.max(maxX, quad[j].x); + minY = Math.min(minY, quad[j].y); + maxY = Math.max(maxY, quad[j].y); + } + } + + var rulerAtRight = minX < 20 && maxX + 20 < width; + var rulerAtBottom = minY < 20 && maxY + 20 < height; + + _drawGrid(highlight, rulerAtRight, rulerAtBottom); + _drawRulers(highlight, rulerAtRight, rulerAtBottom); _drawElementTitle(highlight); - _drawRulers(highlight); context.restore(); } diff --git a/Source/WebCore/inspector/front-end/DefaultTextEditor.js b/Source/WebCore/inspector/front-end/DefaultTextEditor.js index 3a45c6a77..f90b902e3 100644 --- a/Source/WebCore/inspector/front-end/DefaultTextEditor.js +++ b/Source/WebCore/inspector/front-end/DefaultTextEditor.js @@ -204,6 +204,7 @@ WebInspector.DefaultTextEditor.prototype = { { this._mainPanel.addDecoration(lineNumber, element); this._gutterPanel.addDecoration(lineNumber, element); + this._syncDecorationsForLine(lineNumber); }, /** @@ -214,6 +215,7 @@ WebInspector.DefaultTextEditor.prototype = { { this._mainPanel.removeDecoration(lineNumber, element); this._gutterPanel.removeDecoration(lineNumber, element); + this._syncDecorationsForLine(lineNumber); }, /** diff --git a/Source/WebCore/inspector/front-end/FileUtils.js b/Source/WebCore/inspector/front-end/FileUtils.js index 65b49cb91..a0bea203e 100644 --- a/Source/WebCore/inspector/front-end/FileUtils.js +++ b/Source/WebCore/inspector/front-end/FileUtils.js @@ -40,8 +40,6 @@ WebInspector.OutputStreamDelegate.prototype = { onChunkTransferred: function(source) { }, - onTransferFinished: function(source) { }, - onError: function(source, event) { } } @@ -53,16 +51,13 @@ WebInspector.OutputStream = function() } WebInspector.OutputStream.prototype = { - startTransfer: function() { }, - /** - * @param {string} chunk + * @param {string} data + * @param {function(WebInspector.OutputStream)=} callback */ - transferChunk: function(chunk) { }, - - finishTransfer: function() { }, + write: function(data, callback) { }, - dispose: function() { } + close: function() { } } /** @@ -92,7 +87,6 @@ WebInspector.ChunkedFileReader.prototype = { this._reader = new FileReader(); this._reader.onload = this._onChunkLoaded.bind(this); this._reader.onerror = this._delegate.onError.bind(this._delegate, this); - this._output.startTransfer(); this._delegate.onTransferStarted(this); this._loadChunk(); }, @@ -131,7 +125,7 @@ WebInspector.ChunkedFileReader.prototype = { var data = event.target.result; this._loadedSize += data.length; - this._output.transferChunk(data); + this._output.write(data); if (this._isCanceled) return; this._delegate.onChunkTransferred(this); @@ -139,7 +133,7 @@ WebInspector.ChunkedFileReader.prototype = { if (this._loadedSize === this._fileSize) { this._file = null; this._reader = null; - this._output.finishTransfer(); + this._output.close(); this._delegate.onTransferFinished(this); return; } @@ -185,7 +179,6 @@ WebInspector.ChunkedXHRReader.prototype = { this._xhr.onerror = this._delegate.onError.bind(this._delegate, this); this._xhr.send(null); - this._output.startTransfer(); this._delegate.onTransferStarted(this); }, @@ -226,7 +219,7 @@ WebInspector.ChunkedXHRReader.prototype = { return; this._loadedSize += data.length; - this._output.transferChunk(data); + this._output.write(data); if (this._isCanceled) return; this._delegate.onChunkTransferred(this); @@ -242,7 +235,7 @@ WebInspector.ChunkedXHRReader.prototype = { if (this._isCanceled) return; - this._output.finishTransfer(); + this._output.close(); this._delegate.onTransferFinished(this); } } @@ -297,66 +290,63 @@ WebInspector.findBalancedCurlyBrackets = function(source, startIndex, lastIndex) /** * @constructor * @implements {WebInspector.OutputStream} - * @param {string} fileName - * @param {!WebInspector.OutputStreamDelegate} delegate */ -WebInspector.FileOutputStream = function(fileName, delegate) +WebInspector.FileOutputStream = function() { - this._fileName = fileName; - this._delegate = delegate; } WebInspector.FileOutputStream.prototype = { /** - * @override + * @param {string} fileName + * @param {function(WebInspector.FileOutputStream, string=)} callback */ - startTransfer: function() + open: function(fileName, callback) { - WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, this._onTransferStarted, this); + this._closed = false; + this._writeCallbacks = []; + this._fileName = fileName; + function callbackWrapper() + { + WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.SavedURL, callbackWrapper, this); + WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); + callback(this); + } + WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.SavedURL, callbackWrapper, this); WebInspector.fileManager.save(this._fileName, "", true); }, /** - * @override - * @param {string} chunk + * @param {string} data + * @param {function(WebInspector.OutputStream)=} callback */ - transferChunk: function(chunk) + write: function(data, callback) { - WebInspector.fileManager.append(this._fileName, chunk); - }, - - /** - * @override - */ - finishTransfer: function() - { - WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onChunkTransferred, this); - this._delegate.onTransferFinished(this); + this._writeCallbacks.push(callback); + WebInspector.fileManager.append(this._fileName, data); }, - dispose: function() + close: function() { - }, - - /** - * @param {WebInspector.Event} event - */ - _onTransferStarted: function(event) - { - if (event.data !== this._fileName) + this._closed = true; + if (this._writeCallbacks.length) return; - this._delegate.onTransferStarted(this); - WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.SavedURL, this._onTransferStarted, this); - WebInspector.fileManager.addEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onChunkTransferred, this); + WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); }, /** - * @param {WebInspector.Event} event + * @param {Event} event */ - _onChunkTransferred: function(event) + _onAppendDone: function(event) { if (event.data !== this._fileName) return; - this._delegate.onChunkTransferred(this); + if (!this._writeCallbacks.length) { + if (this._closed) + WebInspector.fileManager.removeEventListener(WebInspector.FileManager.EventTypes.AppendedToURL, this._onAppendDone, this); + return; + } + var callback = this._writeCallbacks.shift(); + if (callback) + callback(this); } } diff --git a/Source/WebCore/inspector/front-end/HAREntry.js b/Source/WebCore/inspector/front-end/HAREntry.js index eea5339a3..22e07f88e 100644 --- a/Source/WebCore/inspector/front-end/HAREntry.js +++ b/Source/WebCore/inspector/front-end/HAREntry.js @@ -164,7 +164,7 @@ WebInspector.HAREntry.prototype = { text: this._request.requestFormData }; if (this._request.formParameters) - res.params = this._buildParameters(this._request.formParameters); + res.params = this._buildParameters(this._request.formParameters); return res; }, @@ -279,19 +279,24 @@ WebInspector.HARLog.prototype = { */ build: function() { - var webKitVersion = /AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent); - return { version: "1.2", - creator: { - name: "WebInspector", - version: webKitVersion ? webKitVersion[1] : "n/a" - }, + creator: this._creator(), pages: this._buildPages(), entries: this._requests.map(this._convertResource.bind(this)) } }, + _creator: function() + { + var webKitVersion = /AppleWebKit\/([^ ]+)/.exec(window.navigator.userAgent); + + return { + name: "WebInspector", + version: webKitVersion ? webKitVersion[1] : "n/a" + }; + }, + /** * @return {Array} */ @@ -348,3 +353,87 @@ WebInspector.HARLog.prototype = { return WebInspector.HAREntry._toMilliseconds(time - startTime); } } + +/** + * @constructor + */ +WebInspector.HARWriter = function() +{ +} + +WebInspector.HARWriter.prototype = { + /** + * @param {WebInspector.OutputStream} stream + * @param {Array.<WebInspector.NetworkRequest>} requests + * @param {WebInspector.Progress} progress + */ + write: function(stream, requests, progress) + { + this._stream = stream; + this._harLog = (new WebInspector.HARLog(requests)).build(); + this._pendingRequests = 1; // Guard against completing resource transfer before all requests are made. + var entries = this._harLog.entries; + for (var i = 0; i < entries.length; ++i) { + var content = requests[i].content; + if (typeof content === "undefined" && requests[i].finished) { + ++this._pendingRequests; + requests[i].requestContent(this._onContentAvailable.bind(this, entries[i])); + } else if (content !== null) + entries[i].response.content.text = content; + } + var compositeProgress = new WebInspector.CompositeProgress(progress); + this._writeProgress = compositeProgress.createSubProgress(); + if (--this._pendingRequests) { + this._requestsProgress = compositeProgress.createSubProgress(); + this._requestsProgress.setTitle(WebInspector.UIString("Collecting content…")); + this._requestsProgress.setTotalWork(this._pendingRequests); + } else + this._beginWrite(); + }, + + /** + * @param {Object} entry + * @param {string|null} content + * @param {boolean} contentEncoded + * @param {string=} mimeType + */ + _onContentAvailable: function(entry, content, contentEncoded, mimeType) + { + if (content !== null) + entry.response.content.text = content; + if (this._requestsProgress) + this._requestsProgress.worked(); + if (!--this._pendingRequests) { + this._requestsProgress.done(); + this._beginWrite(); + } + }, + + _beginWrite: function() + { + const jsonIndent = 2; + this._text = JSON.stringify({log: this._harLog}, null, jsonIndent); + this._writeProgress.setTitle(WebInspector.UIString("Writing file…")); + this._writeProgress.setTotalWork(this._text.length); + this._bytesWritten = 0; + this._writeNextChunk(this._stream); + }, + + /** + * @param {WebInspector.OutputStream} stream + * @param {string=} error + */ + _writeNextChunk: function(stream, error) + { + if (this._bytesWritten >= this._text.length || error) { + stream.close(); + this._writeProgress.done(); + return; + } + const chunkSize = 100000; + var text = this._text.substring(this._bytesWritten, this._bytesWritten + chunkSize); + this._bytesWritten += text.length; + stream.write(text, this._writeNextChunk.bind(this)); + this._writeProgress.setWorked(this._bytesWritten); + } +} diff --git a/Source/WebCore/inspector/front-end/HeapSnapshotLoader.js b/Source/WebCore/inspector/front-end/HeapSnapshotLoader.js index e4e6f225e..8725482a5 100644 --- a/Source/WebCore/inspector/front-end/HeapSnapshotLoader.js +++ b/Source/WebCore/inspector/front-end/HeapSnapshotLoader.js @@ -38,10 +38,6 @@ WebInspector.HeapSnapshotLoader = function() } WebInspector.HeapSnapshotLoader.prototype = { - startTransfer: function() - { - }, - dispose: function() { this._reset(); @@ -54,7 +50,7 @@ WebInspector.HeapSnapshotLoader.prototype = { this._snapshot = {}; }, - finishTransfer: function() + close: function() { if (this._json) this._parseStringsArray(); @@ -117,7 +113,7 @@ WebInspector.HeapSnapshotLoader.prototype = { /** * @param {string} chunk */ - transferChunk: function(chunk) + write: function(chunk) { this._json += chunk; switch (this._state) { @@ -128,8 +124,6 @@ WebInspector.HeapSnapshotLoader.prototype = { throw new Error("Snapshot token not found"); this._json = this._json.slice(snapshotTokenIndex + snapshotToken.length + 1); this._state = "parse-snapshot-info"; - this.transferChunk(""); - break; } case "parse-snapshot-info": { var closingBracketIndex = WebInspector.findBalancedCurlyBrackets(this._json); @@ -138,8 +132,6 @@ WebInspector.HeapSnapshotLoader.prototype = { this._snapshot.snapshot = /** @type {HeapSnapshotHeader} */JSON.parse(this._json.slice(0, closingBracketIndex)); this._json = this._json.slice(closingBracketIndex); this._state = "find-nodes"; - this.transferChunk(""); - break; } case "find-nodes": { var nodesToken = "\"nodes\""; @@ -155,8 +147,6 @@ WebInspector.HeapSnapshotLoader.prototype = { this._array = new Uint32Array(nodes_length); this._arrayIndex = 0; this._state = "parse-nodes"; - this.transferChunk(""); - break; } case "parse-nodes": { if (this._parseUintArray()) @@ -164,8 +154,6 @@ WebInspector.HeapSnapshotLoader.prototype = { this._snapshot.nodes = this._array; this._state = "find-edges"; this._array = null; - this.transferChunk(""); - break; } case "find-edges": { var edgesToken = "\"edges\""; @@ -181,8 +169,6 @@ WebInspector.HeapSnapshotLoader.prototype = { this._array = new Uint32Array(edges_length); this._arrayIndex = 0; this._state = "parse-edges"; - this.transferChunk(""); - break; } case "parse-edges": { if (this._parseUintArray()) @@ -190,8 +176,6 @@ WebInspector.HeapSnapshotLoader.prototype = { this._snapshot.edges = this._array; this._array = null; this._state = "find-strings"; - this.transferChunk(""); - break; } case "find-strings": { var stringsToken = "\"strings\""; diff --git a/Source/WebCore/inspector/front-end/HeapSnapshotProxy.js b/Source/WebCore/inspector/front-end/HeapSnapshotProxy.js index a63caa735..1b24ba20f 100644 --- a/Source/WebCore/inspector/front-end/HeapSnapshotProxy.js +++ b/Source/WebCore/inspector/front-end/HeapSnapshotProxy.js @@ -368,7 +368,6 @@ WebInspector.HeapSnapshotLoaderProxy.prototype = { startTransfer: function() { this._started = true; - this.callMethod(null, "startTransfer"); }, isStarted: function() @@ -387,12 +386,12 @@ WebInspector.HeapSnapshotLoaderProxy.prototype = { /** * @param {string} chunk */ - transferChunk: function(chunk) + write: function(chunk) { - this.callMethod(null, "transferChunk", chunk); + this.callMethod(null, "write", chunk); }, - finishTransfer: function() + close: function() { function buildSnapshot() { @@ -411,7 +410,7 @@ WebInspector.HeapSnapshotLoaderProxy.prototype = { this._started = false; this._pendingSnapshotConsumers = []; } - this.callMethod(buildSnapshot.bind(this), "finishTransfer"); + this.callMethod(buildSnapshot.bind(this), "close"); } }; diff --git a/Source/WebCore/inspector/front-end/HeapSnapshotView.js b/Source/WebCore/inspector/front-end/HeapSnapshotView.js index d98ea7424..35ed79677 100644 --- a/Source/WebCore/inspector/front-end/HeapSnapshotView.js +++ b/Source/WebCore/inspector/front-end/HeapSnapshotView.js @@ -812,7 +812,7 @@ WebInspector.HeapProfileHeader = function(type, title, uid, maxJSObjectId) WebInspector.ProfileHeader.call(this, type, title, uid); this.maxJSObjectId = maxJSObjectId; /** - * @type {WebInspector.OutputStream} + * @type {WebInspector.FileOutputStream} */ this._receiver = null; /** @@ -856,23 +856,21 @@ WebInspector.HeapProfileHeader.prototype = { return; } - if (!this._receiver) - this._setupWorker(); - var loaderProxy = /** @type {WebInspector.HeapSnapshotLoaderProxy} */ this._receiver; - this._numberOfChunks = 0; - if (!loaderProxy.isStarted()) { - loaderProxy.startTransfer(); + if (!this._receiver) { + this._setupWorker(); this.sidebarElement.subtitle = WebInspector.UIString("Loading\u2026"); this.sidebarElement.wait = true; ProfilerAgent.getProfile(this.profileType().id, this.uid); } + var loaderProxy = /** @type {WebInspector.HeapSnapshotLoaderProxy} */ this._receiver; loaderProxy.addConsumer(callback); }, _setupWorker: function() { - function setProfileWait(event) { + function setProfileWait(event) + { this.sidebarElement.wait = event.data; } var worker = new WebInspector.HeapSnapshotWorker(); @@ -885,7 +883,7 @@ WebInspector.HeapProfileHeader.prototype = { dispose: function() { if (this._receiver) - this._receiver.dispose(); + this._receiver.close(); else if (this._snapshotProxy) this._snapshotProxy.dispose(); }, @@ -908,11 +906,18 @@ WebInspector.HeapProfileHeader.prototype = { transferChunk: function(chunk) { ++this._numberOfChunks; - this._receiver.transferChunk(chunk); + this._receiver.write(chunk, callback.bind(this)); + function callback() + { + this._saveStatusUpdate(++this._savedChunks); + if (this._totalNumberOfChunks === this._savedChunks) + this._snapshotReceived(null); + } }, _snapshotReceived: function(snapshotProxy) { + this._receiver.close(); this._receiver = null; if (snapshotProxy) this._snapshotProxy = snapshotProxy; @@ -927,8 +932,8 @@ WebInspector.HeapProfileHeader.prototype = { { this._totalNumberOfChunks = this._numberOfChunks; this.sidebarElement.subtitle = WebInspector.UIString("Parsing\u2026"); - if (!transferFinished) - this._receiver.finishTransfer(); + if (!transferFinished && this._receiver) + this._receiver.close(); }, /** @@ -945,21 +950,16 @@ WebInspector.HeapProfileHeader.prototype = { */ saveToFile: function() { - this._fileName = this._fileName || "Heap-" + new Date().toISO8601Compact() + ".heapsnapshot"; - var delegate = new WebInspector.HeapSnapshotSaveToFileDelegate(this); - this._receiver = this._createFileWriter(this._fileName, delegate); this._numberOfChunks = 0; - this._receiver.startTransfer(); - }, - - /** - * @param {!string} fileName - * @param {!WebInspector.OutputStreamDelegate} delegate - * @return {WebInspector.OutputStream} - */ - _createFileWriter: function(fileName, delegate) - { - return new WebInspector.FileOutputStream(fileName, delegate); + function onOpen() + { + this._savedChunks = 0; + this._saveStatusUpdate(0); + ProfilerAgent.getProfile(this.profileType().id, this.uid); + } + this._fileName = this._fileName || "Heap-" + new Date().toISO8601Compact() + ".heapsnapshot"; + this._receiver = new WebInspector.FileOutputStream(); + this._receiver.open(this._fileName, onOpen.bind(this)); }, /** @@ -1036,35 +1036,3 @@ WebInspector.HeapSnapshotLoadFromFileDelegate.prototype = { } } } - -/** - * @constructor - * @implements {WebInspector.OutputStreamDelegate} - */ -WebInspector.HeapSnapshotSaveToFileDelegate = function(snapshotHeader) -{ - this._snapshotHeader = snapshotHeader; - this._savedChunks = 0; -} - -WebInspector.HeapSnapshotSaveToFileDelegate.prototype = { - onTransferStarted: function(source) - { - this._snapshotHeader._saveStatusUpdate(0); - ProfilerAgent.getProfile(this._snapshotHeader.profileType().id, this._snapshotHeader.uid); - }, - - onChunkTransferred: function(source) - { - this._snapshotHeader._saveStatusUpdate(++this._savedChunks); - }, - - onTransferFinished: function(source) - { - this._snapshotHeader._snapshotReceived(null); - }, - - onError: function(source, event) - { - } -} diff --git a/Source/WebCore/inspector/front-end/NetworkPanel.js b/Source/WebCore/inspector/front-end/NetworkPanel.js index c7b900632..5fb8982ac 100644 --- a/Source/WebCore/inspector/front-end/NetworkPanel.js +++ b/Source/WebCore/inspector/front-end/NetworkPanel.js @@ -65,7 +65,7 @@ WebInspector.NetworkLogView = function() this._currentMatchedRequestIndex = -1; this._createStatusbarButtons(); - this._createFilterStatusBarItems(); + this._createStatusBarItems(); this._linkifier = new WebInspector.Linkifier(); WebInspector.networkManager.addEventListener(WebInspector.NetworkManager.EventTypes.RequestStarted, this._onRequestStarted, this); @@ -118,7 +118,7 @@ WebInspector.NetworkLogView.prototype = { get statusBarItems() { - return [this._largerRequestsButton.element, this._preserveLogToggle.element, this._clearButton.element, this._filterBarElement]; + return [this._largerRequestsButton.element, this._preserveLogToggle.element, this._clearButton.element, this._filterBarElement, this._progressBarContainer]; }, get useLargeRows() @@ -325,7 +325,7 @@ WebInspector.NetworkLogView.prototype = { this._updateOffscreenRows(); }, - _createFilterStatusBarItems: function() + _createStatusBarItems: function() { var filterBarElement = document.createElement("div"); filterBarElement.className = "scope-bar status-bar-item"; @@ -358,6 +358,8 @@ WebInspector.NetworkLogView.prototype = { createFilterElement.call(this, type.name(), type.categoryTitle()); } this._filterBarElement = filterBarElement; + this._progressBarContainer = document.createElement("div"); + this._progressBarContainer.className = "status-bar-item"; }, _createSummaryBar: function() @@ -944,15 +946,12 @@ WebInspector.NetworkLogView.prototype = { contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy request headers" : "Copy Request Headers"), this._copyRequestHeaders.bind(this, request)); if (request.responseHeadersText) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy response headers" : "Copy Response Headers"), this._copyResponseHeaders.bind(this, request)); - contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy entry as HAR" : "Copy Entry as HAR"), this._copyRequest.bind(this, request)); } contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy all as HAR" : "Copy All as HAR"), this._copyAll.bind(this)); if (InspectorFrontendHost.canSave()) { contextMenu.appendSeparator(); - if (request) - contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Save entry as HAR" : "Save Entry as HAR"), this._exportRequest.bind(this, request)); - contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Save all as HAR" : "Save All as HAR"), this._exportAll.bind(this)); + contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Save as HAR with content" : "Save as HAR with Content"), this._exportAll.bind(this)); } if (this._canClearBrowserCache || this._canClearBrowserCookies) @@ -963,7 +962,7 @@ WebInspector.NetworkLogView.prototype = { contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Clear browser cookies" : "Clear Browser Cookies"), this._clearBrowserCookies.bind(this)); - if (request.type === WebInspector.resourceTypes.XHR) { + if (request && request.type === WebInspector.resourceTypes.XHR) { contextMenu.appendSeparator(); contextMenu.appendItem(WebInspector.UIString("Replay XHR"), this._replayXHR.bind(this, request.requestId)); contextMenu.appendSeparator(); @@ -986,12 +985,6 @@ WebInspector.NetworkLogView.prototype = { InspectorFrontendHost.copyText(JSON.stringify(harArchive, null, 2)); }, - _copyRequest: function(request) - { - var har = (new WebInspector.HAREntry(request)).build(); - InspectorFrontendHost.copyText(JSON.stringify(har, null, 2)); - }, - _copyLocation: function(request) { InspectorFrontendHost.copyText(request.url); @@ -1009,17 +1002,16 @@ WebInspector.NetworkLogView.prototype = { _exportAll: function() { - var harArchive = { - log: (new WebInspector.HARLog(this._requests)).build() - }; - - WebInspector.fileManager.save(WebInspector.inspectedPageDomain + ".har", JSON.stringify(harArchive, null, 2), true); - }, - - _exportRequest: function(request) - { - var har = (new WebInspector.HAREntry(request)).build(); - WebInspector.fileManager.save(request.displayName + ".har", JSON.stringify(har, null, 2), true); + var filename = WebInspector.inspectedPageDomain + ".har"; + var stream = new WebInspector.FileOutputStream(); + stream.open(filename, openCallback.bind(this)); + function openCallback() + { + var progressIndicator = new WebInspector.ProgressIndicator(); + this._progressBarContainer.appendChild(progressIndicator.element); + var harWriter = new WebInspector.HARWriter(); + harWriter.write(stream, this._requests, progressIndicator); + } }, _clearBrowserCache: function(event) diff --git a/Source/WebCore/inspector/front-end/TimelineModel.js b/Source/WebCore/inspector/front-end/TimelineModel.js index 74e635b2d..deecb6e7d 100644 --- a/Source/WebCore/inspector/front-end/TimelineModel.js +++ b/Source/WebCore/inspector/front-end/TimelineModel.js @@ -193,19 +193,22 @@ WebInspector.TimelineModel.prototype = { return new WebInspector.ChunkedFileReader(file, WebInspector.TimelineModel.TransferChunkLengthBytes, delegate); }, - saveToFile: function() + _createFileWriter: function(fileName, callback) { - var now = new Date(); - var fileName = "TimelineRawData-" + now.toISO8601Compact() + ".json"; - - var delegate = new WebInspector.TimelineModelWriteToFileDelegate(this._records, window.navigator.appVersion); - var writer = this._createFileWriter(fileName, delegate); - writer.startTransfer(); + var stream = new WebInspector.FileOutputStream(); + stream.open(fileName, callback); }, - _createFileWriter: function(fileName, delegate) + saveToFile: function() { - return new WebInspector.FileOutputStream(fileName, delegate); + var now = new Date(); + var fileName = "TimelineRawData-" + now.toISO8601Compact() + ".json"; + function callback(stream) + { + var saver = new WebInspector.TimelineSaver(stream); + saver.save(this._records, window.navigator.appVersion); + } + this._createFileWriter(fileName, callback.bind(this)); }, reset: function() @@ -262,20 +265,14 @@ WebInspector.TimelineModelLoader = function(model, reader, progress) this._reader = reader; this._progress = progress; this._buffer = ""; + this._firstChunk = true; } WebInspector.TimelineModelLoader.prototype = { - startTransfer: function() - { - this._model.reset(); - this._firstChunk = true; - return true; - }, - /** * @param {string} chunk */ - transferChunk: function(chunk) + write: function(chunk) { var data = this._buffer + chunk; var lastIndex = 0; @@ -309,6 +306,7 @@ WebInspector.TimelineModelLoader.prototype = { if (this._firstChunk) { this._version = items[0]; this._firstChunk = false; + this._model.reset(); } // Skip 0-th element - it is either version or 0. @@ -316,9 +314,7 @@ WebInspector.TimelineModelLoader.prototype = { this._model._addRecord(items[i]); }, - finishTransfer: function() { }, - - dispose: function() { } + close: function() { } } /** @@ -381,36 +377,27 @@ WebInspector.TimelineModelLoadFromFileDelegate.prototype = { /** * @constructor - * @implements WebInspector.OutputStreamDelegate - * @param {Array} records - * @param {string} version */ -WebInspector.TimelineModelWriteToFileDelegate = function(records, version) +WebInspector.TimelineSaver = function(stream) { - this._records = records; - this._recordIndex = 0; - this._prologue = "[" + JSON.stringify(new String(version)); + this._stream = stream; } -WebInspector.TimelineModelWriteToFileDelegate.prototype = { - onTransferStarted: function(writer) +WebInspector.TimelineSaver.prototype = { + /** + * @param {Array} records + * @param {string} version + */ + save: function(records, version) { - this._pushChunk(writer); - }, + this._records = records; + this._recordIndex = 0; + this._prologue = "[" + JSON.stringify(version); - onChunkTransferred: function(writer) - { - if (this._recordIndex === this._records.length) - writer.finishTransfer(); - else - this._pushChunk(writer); + this._writeNextChunk(this._stream); }, - onTransferFinished: function(writer) { }, - - onError: function(writer, event) { }, - - _pushChunk: function(writer) + _writeNextChunk: function(stream) { const separator = ",\n"; var data = []; @@ -420,9 +407,13 @@ WebInspector.TimelineModelWriteToFileDelegate.prototype = { data.push(this._prologue); length += this._prologue.length; delete this._prologue; - } else + } else { + if (this._recordIndex === this._records.length) { + stream.close(); + return; + } data.push(""); - + } while (this._recordIndex < this._records.length) { var item = JSON.stringify(this._records[this._recordIndex]); var itemLength = item.length + separator.length; @@ -434,6 +425,6 @@ WebInspector.TimelineModelWriteToFileDelegate.prototype = { } if (this._recordIndex === this._records.length) data.push(data.pop() + "]"); - writer.transferChunk(data.join(separator)); + stream.write(data.join(separator), this._writeNextChunk.bind(this)); } } diff --git a/Source/WebCore/page/ContentSecurityPolicy.cpp b/Source/WebCore/page/ContentSecurityPolicy.cpp index 2577197a1..4bb3a88a8 100644 --- a/Source/WebCore/page/ContentSecurityPolicy.cpp +++ b/Source/WebCore/page/ContentSecurityPolicy.cpp @@ -29,6 +29,7 @@ #include "Console.h" #include "DOMStringList.h" #include "Document.h" +#include "FeatureObserver.h" #include "FormData.h" #include "FormDataList.h" #include "Frame.h" @@ -1285,6 +1286,11 @@ void ContentSecurityPolicy::copyStateFrom(const ContentSecurityPolicy* other) void ContentSecurityPolicy::didReceiveHeader(const String& header, HeaderType type) { + if (m_scriptExecutionContext->isDocument()) { + Document* document = static_cast<Document*>(m_scriptExecutionContext); + FeatureObserver::observe(document->domWindow(), FeatureObserver::PrefixedContentSecurityPolicy); + } + // 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. @@ -1527,6 +1533,8 @@ void ContentSecurityPolicy::reportViolation(const String& directiveText, const S cspReport->setString("original-policy", header); if (blockedURL.isValid()) cspReport->setString("blocked-uri", document->securityOrigin()->canRequest(blockedURL) ? blockedURL.strippedForUseAsReferrer() : SecurityOrigin::create(blockedURL)->toString()); + else + cspReport->setString("blocked-uri", String()); RefPtr<InspectorObject> reportObject = InspectorObject::create(); reportObject->setObject("csp-report", cspReport.release()); diff --git a/Source/WebCore/page/FeatureObserver.h b/Source/WebCore/page/FeatureObserver.h index c32155918..9096ec596 100644 --- a/Source/WebCore/page/FeatureObserver.h +++ b/Source/WebCore/page/FeatureObserver.h @@ -43,6 +43,11 @@ public: LegacyNotifications, LegacyBlobBuilder, PrefixedIndexedDB, + WorkerStart, + SharedWorkerStart, + LegacyWebAudioNoteOn, + WebAudioStart, + PrefixedContentSecurityPolicy, // Add new features above this line. NumberOfFeatures, // This enum value must be last. }; diff --git a/Source/WebCore/platform/DateTimeChooser.h b/Source/WebCore/platform/DateTimeChooser.h index 4b43a3081..6c98e3f17 100644 --- a/Source/WebCore/platform/DateTimeChooser.h +++ b/Source/WebCore/platform/DateTimeChooser.h @@ -41,6 +41,7 @@ struct DateTimeChooserParameters { IntRect anchorRectInRootView; String currentValue; Vector<String> suggestionValues; + Vector<String> localizedSuggestionValues; Vector<String> suggestionLabels; double minimum; double maximum; diff --git a/Source/WebCore/platform/blackberry/AuthenticationChallengeManager.cpp b/Source/WebCore/platform/blackberry/AuthenticationChallengeManager.cpp new file mode 100644 index 000000000..e40a42b7e --- /dev/null +++ b/Source/WebCore/platform/blackberry/AuthenticationChallengeManager.cpp @@ -0,0 +1,253 @@ +/* + * Copyright (C) 2012 Research In Motion Limited. 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 "AuthenticationChallengeManager.h" + +#include "Credential.h" +#include "KURL.h" +#include "PageClientBlackBerry.h" +#include "ProtectionSpace.h" + +#include <BlackBerryPlatformAssert.h> +#include <BlackBerryPlatformLog.h> +#include <wtf/Assertions.h> +#include <wtf/HashMap.h> +#include <wtf/Vector.h> +#include <wtf/text/CString.h> + +namespace WebCore { + +typedef HashMap<PageClientBlackBerry*, bool> PageVisibilityMap; + +struct ChallengeInfo { + ChallengeInfo(const KURL&, const ProtectionSpace&, const Credential&, AuthenticationChallengeClient*, PageClientBlackBerry*); + + KURL url; + ProtectionSpace space; + Credential credential; + AuthenticationChallengeClient* authClient; + PageClientBlackBerry* pageClient; + bool blocked; +}; + +ChallengeInfo::ChallengeInfo(const KURL& aUrl, + const ProtectionSpace& aSpace, + const Credential& aCredential, + AuthenticationChallengeClient* anAuthClient, + PageClientBlackBerry* aPageClient) + : url(aUrl) + , space(aSpace) + , credential(aCredential) + , authClient(anAuthClient) + , pageClient(aPageClient) + , blocked(false) +{ +} + +class AuthenticationChallengeManagerPrivate { +public: + AuthenticationChallengeManagerPrivate(); + + bool resumeAuthenticationChallenge(PageClientBlackBerry*); + void startAuthenticationChallenge(ChallengeInfo*); + bool pageExists(PageClientBlackBerry*); + + ChallengeInfo* m_activeChallenge; + PageVisibilityMap m_pageVisibilityMap; + Vector<OwnPtr<ChallengeInfo> > m_challenges; +}; + +AuthenticationChallengeManagerPrivate::AuthenticationChallengeManagerPrivate() + : m_activeChallenge(0) +{ +} + +bool AuthenticationChallengeManagerPrivate::resumeAuthenticationChallenge(PageClientBlackBerry* client) +{ + ASSERT(!m_activeChallenge); + + for (size_t i = 0; i < m_challenges.size(); ++i) { + if (m_challenges[i]->pageClient == client && m_challenges[i]->blocked) { + startAuthenticationChallenge(m_challenges[i].get()); + return true; + } + } + + return false; +} + +void AuthenticationChallengeManagerPrivate::startAuthenticationChallenge(ChallengeInfo* info) +{ + m_activeChallenge = info; + m_activeChallenge->blocked = false; + m_activeChallenge->pageClient->authenticationChallenge(m_activeChallenge->url, + m_activeChallenge->space, + m_activeChallenge->credential); +} + +bool AuthenticationChallengeManagerPrivate::pageExists(PageClientBlackBerry* client) +{ + return m_pageVisibilityMap.find(client) != m_pageVisibilityMap.end(); +} + +AuthenticationChallengeManager::AuthenticationChallengeManager() + : d(adoptPtr(new AuthenticationChallengeManagerPrivate)) +{ +} + +void AuthenticationChallengeManager::pageCreated(PageClientBlackBerry* client) +{ + d->m_pageVisibilityMap.add(client, true); +} + +void AuthenticationChallengeManager::pageDeleted(PageClientBlackBerry* client) +{ + d->m_pageVisibilityMap.remove(client); + + if (d->m_activeChallenge && d->m_activeChallenge->pageClient == client) + d->m_activeChallenge = 0; + + Vector<OwnPtr<ChallengeInfo> > existing; + d->m_challenges.swap(existing); + + for (size_t i = 0; i < existing.size(); ++i) { + if (existing[i]->pageClient != client) + d->m_challenges.append(existing[i].release()); + } +} + +void AuthenticationChallengeManager::pageVisibilityChanged(PageClientBlackBerry* client, bool visible) +{ + PageVisibilityMap::iterator iter = d->m_pageVisibilityMap.find(client); + + ASSERT(iter != d->m_pageVisibilityMap.end()); + if (iter == d->m_pageVisibilityMap.end()) { + d->m_pageVisibilityMap.add(client, visible); + return; + } + + if (iter->second == visible) + return; + + iter->second = visible; + if (!visible) + return; + + if (d->m_activeChallenge) + return; + + d->resumeAuthenticationChallenge(client); +} + +void AuthenticationChallengeManager::authenticationChallenge(const KURL& url, + const ProtectionSpace& space, + const Credential& credential, + AuthenticationChallengeClient* authClient, + PageClientBlackBerry* pageClient) +{ + BLACKBERRY_ASSERT(authClient); + BLACKBERRY_ASSERT(pageClient); + + ChallengeInfo* info = new ChallengeInfo(url, space, credential, authClient, pageClient); + d->m_challenges.append(adoptPtr(info)); + + if (d->m_activeChallenge || !pageClient->isVisible()) { + info->blocked = true; + return; + } + + d->startAuthenticationChallenge(info); +} + +void AuthenticationChallengeManager::cancelAuthenticationChallenge(AuthenticationChallengeClient* client) +{ + BLACKBERRY_ASSERT(client); + + if (d->m_activeChallenge && d->m_activeChallenge->authClient == client) + d->m_activeChallenge = 0; + + Vector<OwnPtr<ChallengeInfo> > existing; + d->m_challenges.swap(existing); + + ChallengeInfo* next = 0; + PageClientBlackBerry* page = 0; + + for (size_t i = 0; i < existing.size(); ++i) { + if (existing[i]->authClient != client) { + if (page && !next && existing[i]->pageClient == page) + next = existing[i].get(); + d->m_challenges.append(existing[i].release()); + } else if (d->m_activeChallenge == existing[i].get()) + page = existing[i]->pageClient; + } + + if (next) + d->startAuthenticationChallenge(next); +} + +void AuthenticationChallengeManager::notifyChallengeResult(const KURL& url, + const ProtectionSpace& space, + AuthenticationChallengeResult result, + const Credential& credential) +{ + d->m_activeChallenge = 0; + + Vector<OwnPtr<ChallengeInfo> > existing; + d->m_challenges.swap(existing); + + ChallengeInfo* next = 0; + PageClientBlackBerry* page = 0; + + for (size_t i = 0; i < existing.size(); ++i) { + if (existing[i]->space != space) { + if (page && !next && existing[i]->pageClient == page) + next = existing[i].get(); + d->m_challenges.append(existing[i].release()); + } else { + page = existing[i]->pageClient; + existing[i]->authClient->notifyChallengeResult(existing[i]->url, space, result, credential); + + // After calling notifyChallengeResult(), page could be destroyed or something. + if (!d->pageExists(page) || !page->isVisible()) + page = 0; + } + } + + if (next) + d->startAuthenticationChallenge(next); +} + +// Keep following code at the end of this file!!! +static AuthenticationChallengeManager* s_manager = 0; + +AuthenticationChallengeManager* AuthenticationChallengeManager::instance() +{ + ASSERT(s_manager); + return s_manager; +} + +void AuthenticationChallengeManager::init() +{ + ASSERT(!s_manager); + s_manager = new AuthenticationChallengeManager(); +} + +// No more code after this line, all new code should come before s_manager declaration!!! + +} // namespace WebCore diff --git a/Source/WebCore/platform/blackberry/AuthenticationChallengeManager.h b/Source/WebCore/platform/blackberry/AuthenticationChallengeManager.h index 52224f511..20e799bb3 100644 --- a/Source/WebCore/platform/blackberry/AuthenticationChallengeManager.h +++ b/Source/WebCore/platform/blackberry/AuthenticationChallengeManager.h @@ -19,8 +19,13 @@ #ifndef AuthenticationChallengeManager_h #define AuthenticationChallengeManager_h +#include <wtf/OwnPtr.h> + +class PageClientBlackBerry; + namespace WebCore { +class AuthenticationChallengeManagerPrivate; class Credential; class KURL; class ProtectionSpace; @@ -35,6 +40,36 @@ public: virtual void notifyChallengeResult(const KURL&, const ProtectionSpace&, AuthenticationChallengeResult, const Credential&) = 0; }; +class AuthenticationChallengeManager { +public: + static void init(); + static AuthenticationChallengeManager* instance(); + + void pageCreated(PageClientBlackBerry*); + void pageDeleted(PageClientBlackBerry*); + void pageVisibilityChanged(PageClientBlackBerry*, bool visible); + + void authenticationChallenge(const KURL&, + const ProtectionSpace&, + const Credential&, + AuthenticationChallengeClient*, + PageClientBlackBerry*); + + void cancelAuthenticationChallenge(AuthenticationChallengeClient*); + + void notifyChallengeResult(const KURL&, + const ProtectionSpace&, + AuthenticationChallengeResult, + const Credential&); + +private: + AuthenticationChallengeManager(); + ~AuthenticationChallengeManager(); + + OwnPtr<AuthenticationChallengeManagerPrivate> d; +}; + + } // namespace WebCore #endif // AuthenticationChallengeManager_h diff --git a/Source/WebCore/platform/blackberry/PageClientBlackBerry.h b/Source/WebCore/platform/blackberry/PageClientBlackBerry.h index bdb2f1607..f2c7c0e65 100644 --- a/Source/WebCore/platform/blackberry/PageClientBlackBerry.h +++ b/Source/WebCore/platform/blackberry/PageClientBlackBerry.h @@ -72,7 +72,7 @@ public: virtual int showAlertDialog(BlackBerry::WebKit::WebPageClient::AlertType) = 0; virtual bool isActive() const = 0; virtual bool isVisible() const = 0; - virtual void authenticationChallenge(const WebCore::KURL&, const WebCore::ProtectionSpace&, const WebCore::Credential&, WebCore::AuthenticationChallengeClient*) = 0; + virtual void authenticationChallenge(const WebCore::KURL&, const WebCore::ProtectionSpace&, const WebCore::Credential&) = 0; virtual SaveCredentialType notifyShouldSaveCredential(bool) = 0; virtual void syncProxyCredential(const WebCore::Credential&) = 0; }; diff --git a/Source/WebCore/platform/chromium/PlatformSupport.h b/Source/WebCore/platform/chromium/PlatformSupport.h index 366a35cb9..eb1970b8a 100644 --- a/Source/WebCore/platform/chromium/PlatformSupport.h +++ b/Source/WebCore/platform/chromium/PlatformSupport.h @@ -101,13 +101,6 @@ public: #endif #if OS(DARWIN) static bool loadFont(NSFont* srcFont, CGFontRef*, uint32_t* fontID); -#elif OS(UNIX) - struct FontFamily { - String name; - bool isBold; - bool isItalic; - }; - static void getFontFamilyForCharacters(const UChar*, size_t numCharacters, const char* preferredLocale, FontFamily*); #endif // IndexedDB ---------------------------------------------------------- diff --git a/Source/WebCore/platform/chromium/support/CCThreadImpl.cpp b/Source/WebCore/platform/chromium/support/CCThreadImpl.cpp deleted file mode 100644 index cce19525c..000000000 --- a/Source/WebCore/platform/chromium/support/CCThreadImpl.cpp +++ /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. - * - * 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 "CCThreadImpl.h" - -#include "CCCompletionEvent.h" -#include <public/Platform.h> -#include <public/WebThread.h> - -using WebCore::CCThread; -using WebCore::CCCompletionEvent; - -namespace WebKit { - -// Task that, when runs, places the current thread ID into the provided -// pointer and signals a completion event. -// -// Does not provide a PassOwnPtr<GetThreadIDTask>::create method because -// the resulting object is always handed into a WebThread, which does not understand -// PassOwnPtrs. -class GetThreadIDTask : public WebThread::Task { -public: - GetThreadIDTask(ThreadIdentifier* result, CCCompletionEvent* completion) - : m_completion(completion) - , m_result(result) { } - - virtual ~GetThreadIDTask() { } - - virtual void run() - { - *m_result = currentThread(); - m_completion->signal(); - } - -private: - CCCompletionEvent* m_completion; - ThreadIdentifier* m_result; -}; - -// General adapter from a CCThread::Task to a WebThread::Task. -class CCThreadTaskAdapter : public WebThread::Task { -public: - CCThreadTaskAdapter(PassOwnPtr<CCThread::Task> task) : m_task(task) { } - - virtual ~CCThreadTaskAdapter() { } - - virtual void run() - { - m_task->performTask(); - } - -private: - OwnPtr<CCThread::Task> m_task; -}; - -PassOwnPtr<CCThread> CCThreadImpl::create(WebThread* thread) -{ - return adoptPtr(new CCThreadImpl(thread)); -} - -CCThreadImpl::~CCThreadImpl() -{ -} - -void CCThreadImpl::postTask(PassOwnPtr<CCThread::Task> task) -{ - m_thread->postTask(new CCThreadTaskAdapter(task)); -} - -void CCThreadImpl::postDelayedTask(PassOwnPtr<CCThread::Task> task, long long delayMs) -{ - m_thread->postDelayedTask(new CCThreadTaskAdapter(task), delayMs); -} - -ThreadIdentifier CCThreadImpl::threadID() const -{ - return m_threadID; -} - -CCThreadImpl::CCThreadImpl(WebThread* thread) - : m_thread(thread) -{ - if (thread == WebKit::Platform::current()->currentThread()) { - m_threadID = currentThread(); - return; - } - - // Get the threadId for the newly-created thread by running a task - // on that thread, blocking on the result. - m_threadID = currentThread(); - CCCompletionEvent completion; - m_thread->postTask(new GetThreadIDTask(&m_threadID, &completion)); - completion.wait(); -} - -} // namespace WebKit diff --git a/Source/WebCore/platform/chromium/support/CCThreadImpl.h b/Source/WebCore/platform/chromium/support/CCThreadImpl.h deleted file mode 100644 index 308ba8029..000000000 --- a/Source/WebCore/platform/chromium/support/CCThreadImpl.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCThread.h" -#include <wtf/OwnPtr.h> -#include <wtf/Threading.h> - -#ifndef CCThreadImpl_h -#define CCThreadImpl_h - -namespace WebKit { - -class WebThread; - -// Implements CCThread in terms of WebThread. -class CCThreadImpl : public WebCore::CCThread { -public: - static PassOwnPtr<WebCore::CCThread> create(WebThread*); - virtual ~CCThreadImpl(); - virtual void postTask(PassOwnPtr<WebCore::CCThread::Task>); - virtual void postDelayedTask(PassOwnPtr<WebCore::CCThread::Task>, long long delayMs); - WTF::ThreadIdentifier threadID() const; - -private: - explicit CCThreadImpl(WebThread*); - - WebThread* m_thread; - WTF::ThreadIdentifier m_threadID; -}; - -} // namespace WebKit - -#endif diff --git a/Source/WebCore/platform/chromium/support/Extensions3DChromium.cpp b/Source/WebCore/platform/chromium/support/Extensions3DChromium.cpp index 9412274c7..17c302183 100644 --- a/Source/WebCore/platform/chromium/support/Extensions3DChromium.cpp +++ b/Source/WebCore/platform/chromium/support/Extensions3DChromium.cpp @@ -97,20 +97,22 @@ void Extensions3DChromium::unmapTexSubImage2DCHROMIUM(const void* data) Platform3DObject Extensions3DChromium::createVertexArrayOES() { - return 0; + return m_private->webContext()->createVertexArrayOES(); } -void Extensions3DChromium::deleteVertexArrayOES(Platform3DObject) +void Extensions3DChromium::deleteVertexArrayOES(Platform3DObject array) { + m_private->webContext()->deleteVertexArrayOES(array); } -GC3Dboolean Extensions3DChromium::isVertexArrayOES(Platform3DObject) +GC3Dboolean Extensions3DChromium::isVertexArrayOES(Platform3DObject array) { - return 0; + return m_private->webContext()->isVertexArrayOES(array); } -void Extensions3DChromium::bindVertexArrayOES(Platform3DObject) +void Extensions3DChromium::bindVertexArrayOES(Platform3DObject array) { + m_private->webContext()->bindVertexArrayOES(array); } String Extensions3DChromium::getTranslatedShaderSourceANGLE(Platform3DObject shader) diff --git a/Source/WebCore/platform/chromium/support/WebCompositorImpl.cpp b/Source/WebCore/platform/chromium/support/WebCompositorImpl.cpp deleted file mode 100644 index 43579ce15..000000000 --- a/Source/WebCore/platform/chromium/support/WebCompositorImpl.cpp +++ /dev/null @@ -1,119 +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 "WebCompositorImpl.h" - -#include "CCLayerTreeHost.h" -#include "CCProxy.h" -#include "CCSettings.h" -#include "CCThreadImpl.h" -#include <public/Platform.h> -#include <wtf/ThreadingPrimitives.h> - -using namespace WebCore; - -namespace WebKit { - -bool WebCompositorImpl::s_initialized = false; -CCThread* WebCompositorImpl::s_mainThread = 0; -CCThread* WebCompositorImpl::s_implThread = 0; - -void WebCompositor::initialize(WebThread* implThread) -{ - WebCompositorImpl::initialize(implThread); -} - -bool WebCompositor::isThreadingEnabled() -{ - return WebCompositorImpl::isThreadingEnabled(); -} - -void WebCompositor::shutdown() -{ - WebCompositorImpl::shutdown(); - CCSettings::reset(); -} - -void WebCompositor::setPerTilePaintingEnabled(bool enabled) -{ - ASSERT(!WebCompositorImpl::initialized()); - CCSettings::setPerTilePaintingEnabled(enabled); -} - -void WebCompositor::setPartialSwapEnabled(bool enabled) -{ - ASSERT(!WebCompositorImpl::initialized()); - CCSettings::setPartialSwapEnabled(enabled); -} - -void WebCompositor::setAcceleratedAnimationEnabled(bool enabled) -{ - ASSERT(!WebCompositorImpl::initialized()); - CCSettings::setAcceleratedAnimationEnabled(enabled); -} - -void WebCompositorImpl::initialize(WebThread* implThread) -{ - ASSERT(!s_initialized); - s_initialized = true; - - s_mainThread = CCThreadImpl::create(WebKit::Platform::current()->currentThread()).leakPtr(); - CCProxy::setMainThread(s_mainThread); - if (implThread) { - s_implThread = CCThreadImpl::create(implThread).leakPtr(); - CCProxy::setImplThread(s_implThread); - } else - CCProxy::setImplThread(0); -} - -bool WebCompositorImpl::isThreadingEnabled() -{ - return s_implThread; -} - -bool WebCompositorImpl::initialized() -{ - return s_initialized; -} - -void WebCompositorImpl::shutdown() -{ - ASSERT(s_initialized); - ASSERT(!CCLayerTreeHost::anyLayerTreeHostInstanceExists()); - - if (s_implThread) { - delete s_implThread; - s_implThread = 0; - } - delete s_mainThread; - s_mainThread = 0; - CCProxy::setImplThread(0); - CCProxy::setMainThread(0); - s_initialized = false; -} - -} diff --git a/Source/WebCore/platform/chromium/support/WebCompositorImpl.h b/Source/WebCore/platform/chromium/support/WebCompositorImpl.h deleted file mode 100644 index 67e3a67e1..000000000 --- a/Source/WebCore/platform/chromium/support/WebCompositorImpl.h +++ /dev/null @@ -1,62 +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 WebCompositorImpl_h -#define WebCompositorImpl_h - -#include <public/WebCompositor.h> - -#include <wtf/HashSet.h> -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> - -namespace WebCore { -class CCThread; -} - -namespace WebKit { - -class WebThread; - -class WebCompositorImpl : public WebCompositor { - WTF_MAKE_NONCOPYABLE(WebCompositorImpl); -public: - static bool initialized(); - -private: - - friend class WebCompositor; - static void initialize(WebThread* implThread); - static bool isThreadingEnabled(); - static void shutdown(); - - static bool s_initialized; - static WebCore::CCThread* s_mainThread; - static WebCore::CCThread* s_implThread; -}; - -} - -#endif // WebCompositorImpl_h diff --git a/Source/WebCore/platform/graphics/FontCache.cpp b/Source/WebCore/platform/graphics/FontCache.cpp index b46263a96..9cab2fa0e 100644 --- a/Source/WebCore/platform/graphics/FontCache.cpp +++ b/Source/WebCore/platform/graphics/FontCache.cpp @@ -229,7 +229,7 @@ FontPlatformData* FontCache::getCachedFontPlatformData(const FontDescription& fo } #if ENABLE(OPENTYPE_VERTICAL) -typedef HashMap<FontCache::FontFileKey, OwnPtr<OpenTypeVerticalData>> FontVerticalDataCache; +typedef HashMap<FontCache::FontFileKey, OwnPtr<OpenTypeVerticalData> > FontVerticalDataCache; FontVerticalDataCache& fontVerticalDataCacheInstance() { diff --git a/Source/WebCore/platform/graphics/FontCache.h b/Source/WebCore/platform/graphics/FontCache.h index 0e28ef851..12fb8a328 100644 --- a/Source/WebCore/platform/graphics/FontCache.h +++ b/Source/WebCore/platform/graphics/FontCache.h @@ -33,6 +33,7 @@ #include <limits.h> #include <wtf/Forward.h> #include <wtf/Vector.h> +#include <wtf/text/WTFString.h> #include <wtf/unicode/Unicode.h> #if OS(WINDOWS) @@ -113,6 +114,13 @@ public: OpenTypeVerticalData* getVerticalData(const FontFileKey&, const FontPlatformData&); #endif + struct SimpleFontFamily { + String name; + bool isBold; + bool isItalic; + }; + static void getFontFamilyForCharacters(const UChar* characters, size_t numCharacters, const char* preferredLocale, SimpleFontFamily*); + private: FontCache(); ~FontCache(); diff --git a/Source/WebCore/platform/graphics/SimpleFontData.h b/Source/WebCore/platform/graphics/SimpleFontData.h index 215e9be59..66208837c 100644 --- a/Source/WebCore/platform/graphics/SimpleFontData.h +++ b/Source/WebCore/platform/graphics/SimpleFontData.h @@ -229,9 +229,6 @@ private: mutable OwnPtr<GlyphMetricsMap<FloatRect> > m_glyphToBoundsMap; mutable GlyphMetricsMap<float> m_glyphToWidthMap; -#if ENABLE(OPENTYPE_VERTICAL) - const OpenTypeVerticalData* m_verticalData; -#endif bool m_treatAsFixedPitch; bool m_isCustomFont; // Whether or not we are custom font loaded via @font-face @@ -239,6 +236,9 @@ private: bool m_isTextOrientationFallback; bool m_isBrokenIdeographFallback; +#if ENABLE(OPENTYPE_VERTICAL) + const OpenTypeVerticalData* m_verticalData; +#endif bool m_hasVerticalGlyphs; Glyph m_spaceGlyph; diff --git a/Source/WebCore/platform/graphics/blackberry/FontCacheBlackberry.cpp b/Source/WebCore/platform/graphics/blackberry/FontCacheBlackberry.cpp new file mode 100644 index 000000000..6f9896ad6 --- /dev/null +++ b/Source/WebCore/platform/graphics/blackberry/FontCacheBlackberry.cpp @@ -0,0 +1,120 @@ +/* + * 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 "FontCache.h" + +#include "FontRenderStyle.h" + +#include <fontconfig/fontconfig.h> +#include <string.h> +#include <unicode/utf16.h> +#include <wtf/text/CString.h> + +namespace WebCore { + +void FontCache::getFontFamilyForCharacters(const UChar* characters, size_t numCharacters, const char*, FontCache::SimpleFontFamily* family) +{ + FcCharSet* cset = FcCharSetCreate(); + for (size_t i = 0; i < numCharacters; ++i) { + if (U16_IS_SURROGATE(characters[i]) + && U16_IS_SURROGATE_LEAD(characters[i]) + && i != numCharacters - 1 + && U16_IS_TRAIL(characters[i + 1])) { + FcCharSetAddChar(cset, U16_GET_SUPPLEMENTARY(characters[i], characters[i+1])); + i++; + } else + FcCharSetAddChar(cset, characters[i]); + } + FcPattern* pattern = FcPatternCreate(); + + FcValue fcvalue; + fcvalue.type = FcTypeCharSet; + fcvalue.u.c = cset; + FcPatternAdd(pattern, FC_CHARSET, fcvalue, FcFalse); + + fcvalue.type = FcTypeBool; + fcvalue.u.b = FcTrue; + FcPatternAdd(pattern, FC_SCALABLE, fcvalue, FcFalse); + + FcConfigSubstitute(0, pattern, FcMatchPattern); + FcDefaultSubstitute(pattern); + + FcResult result; + FcFontSet* fontSet = FcFontSort(0, pattern, 0, 0, &result); + FcPatternDestroy(pattern); + FcCharSetDestroy(cset); + + if (!fontSet) { + family->name = String(); + family->isBold = false; + family->isItalic = false; + return; + } + + // Older versions of fontconfig have a bug where they cannot select + // only scalable fonts so we have to manually filter the results. + for (int i = 0; i < fontSet->nfont; ++i) { + FcPattern* current = fontSet->fonts[i]; + FcBool isScalable; + + if (FcPatternGetBool(current, FC_SCALABLE, 0, &isScalable) != FcResultMatch + || !isScalable) + continue; + + // fontconfig can also return fonts which are unreadable + FcChar8* cFilename; + if (FcPatternGetString(current, FC_FILE, 0, &cFilename) != FcResultMatch) + continue; + + if (access(reinterpret_cast<char*>(cFilename), R_OK)) + continue; + + FcChar8* familyName; + if (FcPatternGetString(current, FC_FAMILY, 0, &familyName) == FcResultMatch) { + const char* charFamily = reinterpret_cast<char*>(familyName); + family->name = String::fromUTF8(charFamily, strlen(charFamily)); + } + + int weight; + if (FcPatternGetInteger(current, FC_WEIGHT, 0, &weight) == FcResultMatch) + family->isBold = weight >= FC_WEIGHT_BOLD; + else + family->isBold = false; + + int slant; + if (FcPatternGetInteger(current, FC_SLANT, 0, &slant) == FcResultMatch) + family->isItalic = slant != FC_SLANT_ROMAN; + else + family->isItalic = false; + + FcFontSetDestroy(fontSet); + return; + } + + FcFontSetDestroy(fontSet); +} + +}; // namespace WebCore diff --git a/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.cpp b/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.cpp index b4e5ce33c..d696ad199 100644 --- a/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.cpp +++ b/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.cpp @@ -21,6 +21,7 @@ #if ENABLE(VIDEO) #include "MediaPlayerPrivateBlackBerry.h" +#include "AuthenticationChallengeManager.h" #include "CookieManager.h" #include "Credential.h" #include "CredentialStorage.h" @@ -114,6 +115,7 @@ MediaPlayerPrivate::MediaPlayerPrivate(MediaPlayer* player) , m_userDrivenSeekTimer(this, &MediaPlayerPrivate::userDrivenSeekTimerFired) , m_lastSeekTime(0) , m_lastSeekTimePending(false) + , m_isAuthenticationChallenging(false) , m_waitMetadataTimer(this, &MediaPlayerPrivate::waitMetadataTimerFired) , m_waitMetadataPopDialogCounter(0) { @@ -121,6 +123,9 @@ MediaPlayerPrivate::MediaPlayerPrivate(MediaPlayer* player) MediaPlayerPrivate::~MediaPlayerPrivate() { + if (m_isAuthenticationChallenging) + AuthenticationChallengeManager::instance()->cancelAuthenticationChallenge(this); + if (isFullscreen()) { m_webCorePlayer->mediaPlayerClient()->mediaPlayerExitFullscreen(); } @@ -151,6 +156,7 @@ void MediaPlayerPrivate::load(const String& url) } void* tabId = m_webCorePlayer->mediaPlayerClient()->mediaPlayerHostWindow()->platformPageClient(); + int playerID = m_webCorePlayer->mediaPlayerClient()->mediaPlayerHostWindow()->platformPageClient()->playerID(); deleteGuardedObject(m_platformPlayer); #if USE(ACCELERATED_COMPOSITING) @@ -163,9 +169,9 @@ void MediaPlayerPrivate::load(const String& url) if (!url.isEmpty()) cookiePairs = cookieManager().getCookie(KURL(ParsedURLString, url.utf8().data()), WithHttpOnlyCookies); if (!cookiePairs.isEmpty() && cookiePairs.utf8().data()) - m_platformPlayer->load(modifiedUrl.utf8().data(), m_webCorePlayer->userAgent().utf8().data(), cookiePairs.utf8().data()); + m_platformPlayer->load(playerID, modifiedUrl.utf8().data(), m_webCorePlayer->userAgent().utf8().data(), cookiePairs.utf8().data()); else - m_platformPlayer->load(modifiedUrl.utf8().data(), m_webCorePlayer->userAgent().utf8().data(), 0); + m_platformPlayer->load(playerID, modifiedUrl.utf8().data(), m_webCorePlayer->userAgent().utf8().data(), 0); } void MediaPlayerPrivate::cancelLoad() @@ -400,7 +406,7 @@ void MediaPlayerPrivate::resizeSourceDimensions() return; // If we have an HTMLVideoElement but the source has no video, then we need to resize the media element. - if (!hasVideo()) { + if (!hasVideo() && PlatformPlayer::MediaOK == m_platformPlayer->error()) { LayoutRect rect = m_webCorePlayer->mediaPlayerClient()->mediaPlayerContentBoxRect(); static const int playbookMinAudioElementWidth = 300; @@ -709,12 +715,18 @@ void MediaPlayerPrivate::onAuthenticationNeeded(MMRAuthChallenge& authChallenge) return; } - if (frameView() && frameView()->hostWindow()) - frameView()->hostWindow()->platformPageClient()->authenticationChallenge(url, protectionSpace, credential, this); + m_isAuthenticationChallenging = true; + AuthenticationChallengeManager::instance()->authenticationChallenge(url, + protectionSpace, + credential, + this, + m_webCorePlayer->mediaPlayerClient()->mediaPlayerHostWindow()->platformPageClient()); } void MediaPlayerPrivate::notifyChallengeResult(const KURL& url, const ProtectionSpace& protectionSpace, AuthenticationChallengeResult result, const Credential& credential) { + m_isAuthenticationChallenging = false; + if (result != AuthenticationChallengeSuccess || !url.isValid()) return; diff --git a/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.h b/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.h index 289669261..5a083b59e 100644 --- a/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.h +++ b/Source/WebCore/platform/graphics/blackberry/MediaPlayerPrivateBlackBerry.h @@ -174,6 +174,7 @@ private: Timer<MediaPlayerPrivate> m_userDrivenSeekTimer; float m_lastSeekTime; bool m_lastSeekTimePending; + bool m_isAuthenticationChallenging; void waitMetadataTimerFired(Timer<MediaPlayerPrivate>*); Timer<MediaPlayerPrivate> m_waitMetadataTimer; int m_waitMetadataPopDialogCounter; diff --git a/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.cpp b/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.cpp index d4e5eba1f..09cead825 100644 --- a/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.cpp +++ b/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.cpp @@ -129,86 +129,4 @@ void PlatformSupport::getRenderStyleForStrike(const char* family, int sizeAndSty FcPatternDestroy(match); } -void PlatformSupport::getFontFamilyForCharacters(const UChar* characters, size_t numCharacters, const char*, FontFamily* family) -{ - FcCharSet* cset = FcCharSetCreate(); - for (size_t i = 0; i < numCharacters; ++i) { - if (U16_IS_SURROGATE(characters[i]) - && U16_IS_SURROGATE_LEAD(characters[i]) - && i != numCharacters - 1 - && U16_IS_TRAIL(characters[i + 1])) { - FcCharSetAddChar(cset, U16_GET_SUPPLEMENTARY(characters[i], characters[i+1])); - i++; - } else - FcCharSetAddChar(cset, characters[i]); - } - FcPattern* pattern = FcPatternCreate(); - - FcValue fcvalue; - fcvalue.type = FcTypeCharSet; - fcvalue.u.c = cset; - FcPatternAdd(pattern, FC_CHARSET, fcvalue, FcFalse); - - fcvalue.type = FcTypeBool; - fcvalue.u.b = FcTrue; - FcPatternAdd(pattern, FC_SCALABLE, fcvalue, FcFalse); - - FcConfigSubstitute(0, pattern, FcMatchPattern); - FcDefaultSubstitute(pattern); - - FcResult result; - FcFontSet* fontSet = FcFontSort(0, pattern, 0, 0, &result); - FcPatternDestroy(pattern); - FcCharSetDestroy(cset); - - if (!fontSet) { - family->name = String(); - family->isBold = false; - family->isItalic = false; - return; - } - - // Older versions of fontconfig have a bug where they cannot select - // only scalable fonts so we have to manually filter the results. - for (int i = 0; i < fontSet->nfont; ++i) { - FcPattern* current = fontSet->fonts[i]; - FcBool isScalable; - - if (FcPatternGetBool(current, FC_SCALABLE, 0, &isScalable) != FcResultMatch - || !isScalable) - continue; - - // fontconfig can also return fonts which are unreadable - FcChar8* cFilename; - if (FcPatternGetString(current, FC_FILE, 0, &cFilename) != FcResultMatch) - continue; - - if (access(reinterpret_cast<char*>(cFilename), R_OK)) - continue; - - FcChar8* familyName; - if (FcPatternGetString(current, FC_FAMILY, 0, &familyName) == FcResultMatch) { - const char* charFamily = reinterpret_cast<char*>(familyName); - family->name = String::fromUTF8(charFamily, strlen(charFamily)); - } - - int weight; - if (FcPatternGetInteger(current, FC_WEIGHT, 0, &weight) == FcResultMatch) - family->isBold = weight >= FC_WEIGHT_BOLD; - else - family->isBold = false; - - int slant; - if (FcPatternGetInteger(current, FC_SLANT, 0, &slant) == FcResultMatch) - family->isItalic = slant != FC_SLANT_ROMAN; - else - family->isItalic = false; - - FcFontSetDestroy(fontSet); - return; - } - - FcFontSetDestroy(fontSet); -} - }; // namespace WebCore diff --git a/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.h b/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.h index 3be9b0743..d0c043bdc 100644 --- a/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.h +++ b/Source/WebCore/platform/graphics/blackberry/skia/PlatformSupport.h @@ -42,12 +42,6 @@ struct FontRenderStyle; class PlatformSupport { public: static void getRenderStyleForStrike(const char* family, int sizeAndStyle, FontRenderStyle* result); - struct FontFamily { - String name; - bool isBold; - bool isItalic; - }; - static void getFontFamilyForCharacters(const UChar*, size_t numCharacters, const char* preferredLocale, FontFamily*); }; } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/cairo/ImageBufferCairo.cpp b/Source/WebCore/platform/graphics/cairo/ImageBufferCairo.cpp index fc87ade99..8ccb8d9bc 100644 --- a/Source/WebCore/platform/graphics/cairo/ImageBufferCairo.cpp +++ b/Source/WebCore/platform/graphics/cairo/ImageBufferCairo.cpp @@ -268,7 +268,7 @@ static cairo_status_t writeFunction(void* output, const unsigned char* data, uns static bool encodeImage(cairo_surface_t* image, const String& mimeType, Vector<char>* output) { - ASSERT(mimeType == "image/png"); // Only PNG output is supported for now. + ASSERT_UNUSED(mimeType, mimeType == "image/png"); // Only PNG output is supported for now. return cairo_surface_write_to_png_stream(image, writeFunction, output) == CAIRO_STATUS_SUCCESS; } diff --git a/Source/WebCore/platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.cpp b/Source/WebCore/platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.cpp deleted file mode 100644 index c1210e545..000000000 --- a/Source/WebCore/platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.cpp +++ /dev/null @@ -1,110 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "BitmapCanvasLayerTextureUpdater.h" - -#include "LayerPainterChromium.h" -#include "PlatformColor.h" -#include "skia/ext/platform_canvas.h" - -namespace WebCore { - -BitmapCanvasLayerTextureUpdater::Texture::Texture(BitmapCanvasLayerTextureUpdater* textureUpdater, PassOwnPtr<CCPrioritizedTexture> texture) - : LayerTextureUpdater::Texture(texture) - , m_textureUpdater(textureUpdater) -{ -} - -BitmapCanvasLayerTextureUpdater::Texture::~Texture() -{ -} - -void BitmapCanvasLayerTextureUpdater::Texture::updateRect(CCResourceProvider* resourceProvider, const IntRect& sourceRect, const IntSize& destOffset) -{ - textureUpdater()->updateTextureRect(resourceProvider, texture(), sourceRect, destOffset); -} - -PassRefPtr<BitmapCanvasLayerTextureUpdater> BitmapCanvasLayerTextureUpdater::create(PassOwnPtr<LayerPainterChromium> painter) -{ - return adoptRef(new BitmapCanvasLayerTextureUpdater(painter)); -} - -BitmapCanvasLayerTextureUpdater::BitmapCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium> painter) - : CanvasLayerTextureUpdater(painter) - , m_opaque(false) -{ -} - -BitmapCanvasLayerTextureUpdater::~BitmapCanvasLayerTextureUpdater() -{ -} - -PassOwnPtr<LayerTextureUpdater::Texture> BitmapCanvasLayerTextureUpdater::createTexture(CCPrioritizedTextureManager* manager) -{ - return adoptPtr(new Texture(this, CCPrioritizedTexture::create(manager))); -} - -LayerTextureUpdater::SampledTexelFormat BitmapCanvasLayerTextureUpdater::sampledTexelFormat(GC3Denum textureFormat) -{ - // The component order may be bgra if we uploaded bgra pixels to rgba textures. - return PlatformColor::sameComponentOrder(textureFormat) ? - LayerTextureUpdater::SampledTexelFormatRGBA : LayerTextureUpdater::SampledTexelFormatBGRA; -} - -void BitmapCanvasLayerTextureUpdater::prepareToUpdate(const IntRect& contentRect, const IntSize& tileSize, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, CCRenderingStats& stats) -{ - if (m_canvasSize != contentRect.size()) { - m_canvasSize = contentRect.size(); - m_canvas = adoptPtr(skia::CreateBitmapCanvas(m_canvasSize.width(), m_canvasSize.height(), m_opaque)); - } - - paintContents(m_canvas.get(), contentRect, contentsWidthScale, contentsHeightScale, resultingOpaqueRect, stats); -} - -void BitmapCanvasLayerTextureUpdater::updateTextureRect(CCResourceProvider* resourceProvider, CCPrioritizedTexture* texture, const IntRect& sourceRect, const IntSize& destOffset) -{ - const SkBitmap& bitmap = m_canvas->getDevice()->accessBitmap(false); - bitmap.lockPixels(); - - texture->upload(resourceProvider, static_cast<const uint8_t*>(bitmap.getPixels()), contentRect(), sourceRect, destOffset); - bitmap.unlockPixels(); -} - -void BitmapCanvasLayerTextureUpdater::setOpaque(bool opaque) -{ - if (opaque != m_opaque) { - m_canvas.clear(); - m_canvasSize = IntSize(); - } - m_opaque = opaque; -} - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.h b/Source/WebCore/platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.h deleted file mode 100644 index d54521f9b..000000000 --- a/Source/WebCore/platform/graphics/chromium/BitmapCanvasLayerTextureUpdater.h +++ /dev/null @@ -1,78 +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 BitmapCanvasLayerTextureUpdater_h -#define BitmapCanvasLayerTextureUpdater_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CanvasLayerTextureUpdater.h" - -class SkCanvas; - -namespace WebCore { - -class LayerPainterChromium; - -// This class rasterizes the contentRect into a skia bitmap canvas. It then updates -// textures by copying from the canvas into the texture, using MapSubImage if -// possible. -class BitmapCanvasLayerTextureUpdater : public CanvasLayerTextureUpdater { -public: - class Texture : public LayerTextureUpdater::Texture { - public: - Texture(BitmapCanvasLayerTextureUpdater*, PassOwnPtr<CCPrioritizedTexture>); - virtual ~Texture(); - - virtual void updateRect(CCResourceProvider*, const IntRect& sourceRect, const IntSize& destOffset) OVERRIDE; - - private: - BitmapCanvasLayerTextureUpdater* textureUpdater() { return m_textureUpdater; } - - BitmapCanvasLayerTextureUpdater* m_textureUpdater; - }; - - static PassRefPtr<BitmapCanvasLayerTextureUpdater> create(PassOwnPtr<LayerPainterChromium>); - virtual ~BitmapCanvasLayerTextureUpdater(); - - virtual PassOwnPtr<LayerTextureUpdater::Texture> createTexture(CCPrioritizedTextureManager*) OVERRIDE; - virtual SampledTexelFormat sampledTexelFormat(GC3Denum textureFormat) OVERRIDE; - virtual void prepareToUpdate(const IntRect& contentRect, const IntSize& tileSize, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, CCRenderingStats&) OVERRIDE; - void updateTextureRect(CCResourceProvider*, CCPrioritizedTexture*, const IntRect& sourceRect, const IntSize& destOffset); - - virtual void setOpaque(bool) OVERRIDE; - -private: - explicit BitmapCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium>); - - OwnPtr<SkCanvas> m_canvas; - IntSize m_canvasSize; - bool m_opaque; -}; - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) -#endif // BitmapCanvasLayerTextureUpdater_h diff --git a/Source/WebCore/platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.cpp b/Source/WebCore/platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.cpp deleted file mode 100644 index 39580ff4b..000000000 --- a/Source/WebCore/platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.cpp +++ /dev/null @@ -1,105 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "BitmapSkPictureCanvasLayerTextureUpdater.h" - -#include "CCRenderingStats.h" -#include "LayerPainterChromium.h" -#include "PlatformColor.h" -#include "SkCanvas.h" -#include "SkDevice.h" -#include <wtf/CurrentTime.h> - -namespace WebCore { - -BitmapSkPictureCanvasLayerTextureUpdater::Texture::Texture(BitmapSkPictureCanvasLayerTextureUpdater* textureUpdater, PassOwnPtr<CCPrioritizedTexture> texture) - : CanvasLayerTextureUpdater::Texture(texture) - , m_textureUpdater(textureUpdater) -{ -} - -void BitmapSkPictureCanvasLayerTextureUpdater::Texture::prepareRect(const IntRect& sourceRect, CCRenderingStats& stats) -{ - m_bitmap.setConfig(SkBitmap::kARGB_8888_Config, sourceRect.width(), sourceRect.height()); - m_bitmap.allocPixels(); - m_bitmap.setIsOpaque(m_textureUpdater->layerIsOpaque()); - SkDevice device(m_bitmap); - SkCanvas canvas(&device); - double paintBeginTime = monotonicallyIncreasingTime(); - textureUpdater()->paintContentsRect(&canvas, sourceRect, stats); - stats.totalPaintTimeInSeconds += monotonicallyIncreasingTime() - paintBeginTime; -} - -void BitmapSkPictureCanvasLayerTextureUpdater::Texture::updateRect(CCResourceProvider* resourceProvider, const IntRect& sourceRect, const IntSize& destOffset) -{ - m_bitmap.lockPixels(); - texture()->upload(resourceProvider, static_cast<uint8_t*>(m_bitmap.getPixels()), sourceRect, sourceRect, destOffset); - m_bitmap.unlockPixels(); - m_bitmap.reset(); -} - -PassRefPtr<BitmapSkPictureCanvasLayerTextureUpdater> BitmapSkPictureCanvasLayerTextureUpdater::create(PassOwnPtr<LayerPainterChromium> painter) -{ - return adoptRef(new BitmapSkPictureCanvasLayerTextureUpdater(painter)); -} - -BitmapSkPictureCanvasLayerTextureUpdater::BitmapSkPictureCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium> painter) - : SkPictureCanvasLayerTextureUpdater(painter) -{ -} - -BitmapSkPictureCanvasLayerTextureUpdater::~BitmapSkPictureCanvasLayerTextureUpdater() -{ -} - -PassOwnPtr<LayerTextureUpdater::Texture> BitmapSkPictureCanvasLayerTextureUpdater::createTexture(CCPrioritizedTextureManager* manager) -{ - return adoptPtr(new Texture(this, CCPrioritizedTexture::create(manager))); -} - -LayerTextureUpdater::SampledTexelFormat BitmapSkPictureCanvasLayerTextureUpdater::sampledTexelFormat(GC3Denum textureFormat) -{ - // The component order may be bgra if we uploaded bgra pixels to rgba textures. - return PlatformColor::sameComponentOrder(textureFormat) ? - LayerTextureUpdater::SampledTexelFormatRGBA : LayerTextureUpdater::SampledTexelFormatBGRA; -} - -void BitmapSkPictureCanvasLayerTextureUpdater::paintContentsRect(SkCanvas* canvas, const IntRect& sourceRect, CCRenderingStats& stats) -{ - // Translate the origin of contentRect to that of sourceRect. - canvas->translate(contentRect().x() - sourceRect.x(), - contentRect().y() - sourceRect.y()); - double rasterizeBeginTime = monotonicallyIncreasingTime(); - drawPicture(canvas); - stats.totalRasterizeTimeInSeconds += monotonicallyIncreasingTime() - rasterizeBeginTime; -} - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.h b/Source/WebCore/platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.h deleted file mode 100644 index 38da53cd3..000000000 --- a/Source/WebCore/platform/graphics/chromium/BitmapSkPictureCanvasLayerTextureUpdater.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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#ifndef BitmapSkPictureCanvasLayerTextureUpdater_h -#define BitmapSkPictureCanvasLayerTextureUpdater_h - -#if USE(ACCELERATED_COMPOSITING) -#include "SkBitmap.h" -#include "SkPictureCanvasLayerTextureUpdater.h" - -namespace WebCore { - -// This class records the contentRect into an SkPicture, then software rasterizes -// the SkPicture into bitmaps for each tile. This implements CCSettings::perTilePainting. -class BitmapSkPictureCanvasLayerTextureUpdater : public SkPictureCanvasLayerTextureUpdater { -public: - class Texture : public CanvasLayerTextureUpdater::Texture { - public: - Texture(BitmapSkPictureCanvasLayerTextureUpdater*, PassOwnPtr<CCPrioritizedTexture>); - - virtual void prepareRect(const IntRect& sourceRect, CCRenderingStats&) OVERRIDE; - virtual void updateRect(CCResourceProvider*, const IntRect& sourceRect, const IntSize& destOffset) OVERRIDE; - - private: - BitmapSkPictureCanvasLayerTextureUpdater* textureUpdater() { return m_textureUpdater; } - - SkBitmap m_bitmap; - BitmapSkPictureCanvasLayerTextureUpdater* m_textureUpdater; - }; - - static PassRefPtr<BitmapSkPictureCanvasLayerTextureUpdater> create(PassOwnPtr<LayerPainterChromium>); - virtual ~BitmapSkPictureCanvasLayerTextureUpdater(); - - virtual PassOwnPtr<LayerTextureUpdater::Texture> createTexture(CCPrioritizedTextureManager*) OVERRIDE; - virtual SampledTexelFormat sampledTexelFormat(GC3Denum textureFormat) OVERRIDE; - void paintContentsRect(SkCanvas*, const IntRect& sourceRect, CCRenderingStats&); - -private: - explicit BitmapSkPictureCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium>); -}; -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) -#endif // BitmapSkPictureCanvasLayerTextureUpdater_h diff --git a/Source/WebCore/platform/graphics/chromium/Canvas2DLayerBridge.cpp b/Source/WebCore/platform/graphics/chromium/Canvas2DLayerBridge.cpp index 5155fbd62..1250e4e87 100644 --- a/Source/WebCore/platform/graphics/chromium/Canvas2DLayerBridge.cpp +++ b/Source/WebCore/platform/graphics/chromium/Canvas2DLayerBridge.cpp @@ -27,7 +27,6 @@ #include "Canvas2DLayerBridge.h" -#include "CCRendererGL.h" // For the GLC() macro. #include "Canvas2DLayerManager.h" #include "GrContext.h" #include "GraphicsContext3D.h" @@ -67,15 +66,15 @@ Canvas2DLayerBridge::Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, if (m_useDoubleBuffering) { m_context->makeContextCurrent(); - GLC(m_context.get(), m_frontBufferTexture = m_context->createTexture()); - GLC(m_context.get(), m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_frontBufferTexture)); + m_frontBufferTexture = m_context->createTexture(); + m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_frontBufferTexture); // Do basic linear filtering on resize. - GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR)); - GLC(m_context.get(), 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_MAG_FILTER, GraphicsContext3D::LINEAR); // NPOT textures in GL ES only work when the wrap mode is set to GraphicsContext3D::CLAMP_TO_EDGE. - GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE)); - GLC(m_context.get(), m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE)); - GLC(m_context.get(), m_context->texImage2DResourceSafe(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, size.width(), size.height(), 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE)); + 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); + m_context->texImage2DResourceSafe(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, size.width(), size.height(), 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE); if (GrContext* grContext = m_context->grContext()) grContext->resetContext(); } @@ -95,7 +94,7 @@ Canvas2DLayerBridge::~Canvas2DLayerBridge() m_layer->setTextureId(0); if (m_useDoubleBuffering) { m_context->makeContextCurrent(); - GLC(m_context.get(), m_context->deleteTexture(m_frontBufferTexture)); + m_context->deleteTexture(m_frontBufferTexture); m_context->flush(); } } diff --git a/Source/WebCore/platform/graphics/chromium/CanvasLayerTextureUpdater.cpp b/Source/WebCore/platform/graphics/chromium/CanvasLayerTextureUpdater.cpp deleted file mode 100644 index b87cf4c90..000000000 --- a/Source/WebCore/platform/graphics/chromium/CanvasLayerTextureUpdater.cpp +++ /dev/null @@ -1,91 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CanvasLayerTextureUpdater.h" - -#include "CCRenderingStats.h" -#include "FloatRect.h" -#include "LayerPainterChromium.h" -#include "SkCanvas.h" -#include "SkPaint.h" -#include "SkRect.h" -#include "SkiaUtils.h" -#include "TraceEvent.h" -#include <wtf/CurrentTime.h> - -namespace WebCore { - -CanvasLayerTextureUpdater::CanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium> painter) - : m_painter(painter) -{ -} - -CanvasLayerTextureUpdater::~CanvasLayerTextureUpdater() -{ -} - -void CanvasLayerTextureUpdater::paintContents(SkCanvas* canvas, const IntRect& contentRect, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, CCRenderingStats& stats) -{ - TRACE_EVENT0("cc", "CanvasLayerTextureUpdater::paintContents"); - canvas->save(); - canvas->translate(WebCoreFloatToSkScalar(-contentRect.x()), WebCoreFloatToSkScalar(-contentRect.y())); - - IntRect layerRect = contentRect; - - if (contentsWidthScale != 1 || contentsHeightScale != 1) { - canvas->scale(WebCoreFloatToSkScalar(contentsWidthScale), WebCoreFloatToSkScalar(contentsHeightScale)); - - FloatRect rect = contentRect; - rect.scale(1 / contentsWidthScale, 1 / contentsHeightScale); - layerRect = enclosingIntRect(rect); - } - - SkPaint paint; - paint.setAntiAlias(false); - paint.setXfermodeMode(SkXfermode::kClear_Mode); - SkRect layerSkRect = SkRect::MakeXYWH(layerRect.x(), layerRect.y(), layerRect.width(), layerRect.height()); - canvas->drawRect(layerSkRect, paint); - canvas->clipRect(layerSkRect); - - FloatRect opaqueLayerRect; - double paintBeginTime = monotonicallyIncreasingTime(); - m_painter->paint(canvas, layerRect, opaqueLayerRect); - stats.totalPaintTimeInSeconds += monotonicallyIncreasingTime() - paintBeginTime; - canvas->restore(); - - FloatRect opaqueContentRect = opaqueLayerRect; - opaqueContentRect.scale(contentsWidthScale, contentsHeightScale); - resultingOpaqueRect = enclosedIntRect(opaqueContentRect); - - m_contentRect = contentRect; -} - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/CanvasLayerTextureUpdater.h b/Source/WebCore/platform/graphics/chromium/CanvasLayerTextureUpdater.h deleted file mode 100644 index c5a4fc267..000000000 --- a/Source/WebCore/platform/graphics/chromium/CanvasLayerTextureUpdater.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CanvasLayerTextureUpdater_h -#define CanvasLayerTextureUpdater_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerTextureUpdater.h" - -class SkCanvas; - -namespace WebCore { - -class LayerPainterChromium; - -// Base class for BitmapCanvasLayerTextureUpdater and -// SkPictureCanvasLayerTextureUpdater that reduces code duplication between -// their respective paintContents implementations. -class CanvasLayerTextureUpdater : public LayerTextureUpdater { -public: - virtual ~CanvasLayerTextureUpdater(); - -protected: - explicit CanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium>); - - void paintContents(SkCanvas*, const IntRect& contentRect, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, CCRenderingStats&); - const IntRect& contentRect() const { return m_contentRect; } - -private: - IntRect m_contentRect; - OwnPtr<LayerPainterChromium> m_painter; -}; - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) -#endif // CanvasLayerTextureUpdater_h diff --git a/Source/WebCore/platform/graphics/chromium/ContentLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/ContentLayerChromium.cpp deleted file mode 100644 index d578117be..000000000 --- a/Source/WebCore/platform/graphics/chromium/ContentLayerChromium.cpp +++ /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. - */ - -#include "config.h" - -#if USE(ACCELERATED_COMPOSITING) - -#include "ContentLayerChromium.h" - -#include "BitmapCanvasLayerTextureUpdater.h" -#include "BitmapSkPictureCanvasLayerTextureUpdater.h" -#include "CCLayerTreeHost.h" -#include "CCSettings.h" -#include "ContentLayerChromiumClient.h" -#include "FrameBufferSkPictureCanvasLayerTextureUpdater.h" -#include "LayerPainterChromium.h" -#include <public/Platform.h> -#include <wtf/CurrentTime.h> - -namespace WebCore { - -ContentLayerPainter::ContentLayerPainter(ContentLayerChromiumClient* client) - : m_client(client) -{ -} - -PassOwnPtr<ContentLayerPainter> ContentLayerPainter::create(ContentLayerChromiumClient* client) -{ - return adoptPtr(new ContentLayerPainter(client)); -} - -void ContentLayerPainter::paint(SkCanvas* canvas, const IntRect& contentRect, FloatRect& opaque) -{ - double paintStart = currentTime(); - m_client->paintContents(canvas, contentRect, opaque); - double paintEnd = currentTime(); - double pixelsPerSec = (contentRect.width() * contentRect.height()) / (paintEnd - paintStart); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.AccelContentPaintDurationMS", (paintEnd - paintStart) * 1000, 0, 120, 30); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.AccelContentPaintMegapixPerSecond", pixelsPerSec / 1000000, 10, 210, 30); -} - -PassRefPtr<ContentLayerChromium> ContentLayerChromium::create(ContentLayerChromiumClient* client) -{ - return adoptRef(new ContentLayerChromium(client)); -} - -ContentLayerChromium::ContentLayerChromium(ContentLayerChromiumClient* client) - : TiledLayerChromium() - , m_client(client) -{ -} - -ContentLayerChromium::~ContentLayerChromium() -{ -} - -bool ContentLayerChromium::drawsContent() const -{ - return TiledLayerChromium::drawsContent() && m_client; -} - -void ContentLayerChromium::setTexturePriorities(const CCPriorityCalculator& priorityCalc) -{ - // Update the tile data before creating all the layer's tiles. - updateTileSizeAndTilingOption(); - - TiledLayerChromium::setTexturePriorities(priorityCalc); -} - -void ContentLayerChromium::update(CCTextureUpdateQueue& queue, const CCOcclusionTracker* occlusion, CCRenderingStats& stats) -{ - createTextureUpdaterIfNeeded(); - TiledLayerChromium::update(queue, occlusion, stats); - m_needsDisplay = false; -} - -bool ContentLayerChromium::needMoreUpdates() -{ - return needsIdlePaint(); -} - -void ContentLayerChromium::createTextureUpdaterIfNeeded() -{ - if (m_textureUpdater) - return; - if (layerTreeHost()->settings().acceleratePainting) - m_textureUpdater = FrameBufferSkPictureCanvasLayerTextureUpdater::create(ContentLayerPainter::create(m_client)); - else if (CCSettings::perTilePaintingEnabled()) - m_textureUpdater = BitmapSkPictureCanvasLayerTextureUpdater::create(ContentLayerPainter::create(m_client)); - else - m_textureUpdater = BitmapCanvasLayerTextureUpdater::create(ContentLayerPainter::create(m_client)); - m_textureUpdater->setOpaque(opaque()); - - GC3Denum textureFormat = layerTreeHost()->rendererCapabilities().bestTextureFormat; - setTextureFormat(textureFormat); - setSampledTexelFormat(textureUpdater()->sampledTexelFormat(textureFormat)); -} - -void ContentLayerChromium::setOpaque(bool opaque) -{ - LayerChromium::setOpaque(opaque); - if (m_textureUpdater) - m_textureUpdater->setOpaque(opaque); -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/ContentLayerChromium.h b/Source/WebCore/platform/graphics/chromium/ContentLayerChromium.h deleted file mode 100644 index 7eb459c5b..000000000 --- a/Source/WebCore/platform/graphics/chromium/ContentLayerChromium.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: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#ifndef ContentLayerChromium_h -#define ContentLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerPainterChromium.h" -#include "TiledLayerChromium.h" - -class SkCanvas; - -namespace WebCore { - -class ContentLayerChromiumClient; -class FloatRect; -class IntRect; -class LayerTextureUpdater; - -class ContentLayerPainter : public LayerPainterChromium { - WTF_MAKE_NONCOPYABLE(ContentLayerPainter); -public: - static PassOwnPtr<ContentLayerPainter> create(ContentLayerChromiumClient*); - - virtual void paint(SkCanvas*, const IntRect& contentRect, FloatRect& opaque) OVERRIDE; - -private: - explicit ContentLayerPainter(ContentLayerChromiumClient*); - - ContentLayerChromiumClient* m_client; -}; - -// A layer that renders its contents into an SkCanvas. -class ContentLayerChromium : public TiledLayerChromium { -public: - static PassRefPtr<ContentLayerChromium> create(ContentLayerChromiumClient*); - - virtual ~ContentLayerChromium(); - - void clearClient() { m_client = 0; } - - virtual bool drawsContent() const OVERRIDE; - virtual void setTexturePriorities(const CCPriorityCalculator&) OVERRIDE; - virtual void update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) OVERRIDE; - virtual bool needMoreUpdates() OVERRIDE; - - virtual void setOpaque(bool) OVERRIDE; - -protected: - explicit ContentLayerChromium(ContentLayerChromiumClient*); - - -private: - virtual LayerTextureUpdater* textureUpdater() const OVERRIDE { return m_textureUpdater.get(); } - virtual void createTextureUpdaterIfNeeded() OVERRIDE; - - ContentLayerChromiumClient* m_client; - RefPtr<LayerTextureUpdater> m_textureUpdater; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/ContentLayerChromiumClient.h b/Source/WebCore/platform/graphics/chromium/ContentLayerChromiumClient.h deleted file mode 100644 index d956a5d71..000000000 --- a/Source/WebCore/platform/graphics/chromium/ContentLayerChromiumClient.h +++ /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 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 ContentLayerChromiumClient_h -#define ContentLayerChromiumClient_h - -class SkCanvas; - -namespace WebCore { -class FloatRect; -class IntRect; - -class ContentLayerChromiumClient { -public: - virtual void paintContents(SkCanvas*, const IntRect& clip, FloatRect& opaque) = 0; - -protected: - virtual ~ContentLayerChromiumClient() { } -}; - -} - -#endif // ContentLayerChromiumClient_h diff --git a/Source/WebCore/platform/graphics/chromium/FontCacheAndroid.cpp b/Source/WebCore/platform/graphics/chromium/FontCacheAndroid.cpp index 6f047b9c8..01d08645a 100644 --- a/Source/WebCore/platform/graphics/chromium/FontCacheAndroid.cpp +++ b/Source/WebCore/platform/graphics/chromium/FontCacheAndroid.cpp @@ -35,7 +35,6 @@ #include "FontDescription.h" #include "FontPlatformData.h" #include "NotImplemented.h" -#include "PlatformSupport.h" #include "SimpleFontData.h" #include "SkPaint.h" @@ -100,13 +99,9 @@ void FontCache::platformInit() const SimpleFontData* FontCache::getFontDataForCharacters(const Font& font, const UChar* characters, int length) { - icu::Locale locale = icu::Locale::getDefault(); - PlatformSupport::FontFamily family; - PlatformSupport::getFontFamilyForCharacters(characters, length, locale.getLanguage(), &family); - if (family.name.isEmpty()) - return 0; - - AtomicString atomicFamily(family.name); + // FIXME: We do not use fontconfig on Android, so use simple logic for now. + // https://bugs.webkit.org/show_bug.cgi?id=67587 + AtomicString atomicFamily("Arial"); return getCachedFontData(getCachedFontPlatformData(font.fontDescription(), atomicFamily, DoNotRetain), DoNotRetain); } diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCAnimationCurve.cpp b/Source/WebCore/platform/graphics/chromium/FontCacheChromiumLinux.cpp index f41bfc13a..3746b2225 100644 --- a/Source/WebCore/platform/graphics/chromium/cc/CCAnimationCurve.cpp +++ b/Source/WebCore/platform/graphics/chromium/FontCacheChromiumLinux.cpp @@ -24,20 +24,25 @@ #include "config.h" -#include "CCAnimationCurve.h" +#include "FontCache.h" + +#include <public/Platform.h> +#include <public/linux/WebFontFamily.h> +#include <public/linux/WebFontInfo.h> +#include <public/linux/WebSandboxSupport.h> namespace WebCore { -const CCFloatAnimationCurve* CCAnimationCurve::toFloatAnimationCurve() const +void FontCache::getFontFamilyForCharacters(const UChar* characters, size_t numCharacters, const char* preferredLocale, FontCache::SimpleFontFamily* family) { - ASSERT(type() == CCAnimationCurve::Float); - return static_cast<const CCFloatAnimationCurve*>(this); + WebKit::WebFontFamily webFamily; + if (WebKit::Platform::current()->sandboxSupport()) + WebKit::Platform::current()->sandboxSupport()->getFontFamilyForCharacters(characters, numCharacters, preferredLocale, &webFamily); + else + WebKit::WebFontInfo::familyForChars(characters, numCharacters, preferredLocale, &webFamily); + family->name = String::fromUTF8(webFamily.name.data(), webFamily.name.length()); + family->isBold = webFamily.isBold; + family->isItalic = webFamily.isItalic; } -const CCTransformAnimationCurve* CCAnimationCurve::toTransformAnimationCurve() const -{ - ASSERT(type() == CCAnimationCurve::Transform); - return static_cast<const CCTransformAnimationCurve*>(this); } - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.cpp b/Source/WebCore/platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.cpp deleted file mode 100644 index 4bc639009..000000000 --- a/Source/WebCore/platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.cpp +++ /dev/null @@ -1,140 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "FrameBufferSkPictureCanvasLayerTextureUpdater.h" - -#include "CCProxy.h" -#include "LayerPainterChromium.h" -#include "SkCanvas.h" -#include "SkGpuDevice.h" -#include <public/WebGraphicsContext3D.h> -#include <public/WebSharedGraphicsContext3D.h> - -using WebKit::WebGraphicsContext3D; -using WebKit::WebSharedGraphicsContext3D; - -namespace WebCore { - -static PassOwnPtr<SkCanvas> createAcceleratedCanvas(GrContext* grContext, - IntSize canvasSize, - unsigned textureId) -{ - GrPlatformTextureDesc textureDesc; - textureDesc.fFlags = kRenderTarget_GrPlatformTextureFlag; - textureDesc.fWidth = canvasSize.width(); - textureDesc.fHeight = canvasSize.height(); - textureDesc.fConfig = kSkia8888_GrPixelConfig; - textureDesc.fTextureHandle = textureId; - SkAutoTUnref<GrTexture> target(grContext->createPlatformTexture(textureDesc)); - SkAutoTUnref<SkDevice> device(new SkGpuDevice(grContext, target.get())); - return adoptPtr(new SkCanvas(device.get())); -} - -FrameBufferSkPictureCanvasLayerTextureUpdater::Texture::Texture(FrameBufferSkPictureCanvasLayerTextureUpdater* textureUpdater, PassOwnPtr<CCPrioritizedTexture> texture) - : LayerTextureUpdater::Texture(texture) - , m_textureUpdater(textureUpdater) -{ -} - -FrameBufferSkPictureCanvasLayerTextureUpdater::Texture::~Texture() -{ -} - -void FrameBufferSkPictureCanvasLayerTextureUpdater::Texture::updateRect(CCResourceProvider* resourceProvider, const IntRect& sourceRect, const IntSize& destOffset) -{ - WebGraphicsContext3D* sharedContext = CCProxy::hasImplThread() ? WebSharedGraphicsContext3D::compositorThreadContext() : WebSharedGraphicsContext3D::mainThreadContext(); - GrContext* sharedGrContext = CCProxy::hasImplThread() ? WebSharedGraphicsContext3D::compositorThreadGrContext() : WebSharedGraphicsContext3D::mainThreadGrContext(); - if (!sharedContext || !sharedGrContext) - return; - textureUpdater()->updateTextureRect(sharedContext, sharedGrContext, resourceProvider, texture(), sourceRect, destOffset); -} - -PassRefPtr<FrameBufferSkPictureCanvasLayerTextureUpdater> FrameBufferSkPictureCanvasLayerTextureUpdater::create(PassOwnPtr<LayerPainterChromium> painter) -{ - return adoptRef(new FrameBufferSkPictureCanvasLayerTextureUpdater(painter)); -} - -FrameBufferSkPictureCanvasLayerTextureUpdater::FrameBufferSkPictureCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium> painter) - : SkPictureCanvasLayerTextureUpdater(painter) -{ -} - -FrameBufferSkPictureCanvasLayerTextureUpdater::~FrameBufferSkPictureCanvasLayerTextureUpdater() -{ -} - -PassOwnPtr<LayerTextureUpdater::Texture> FrameBufferSkPictureCanvasLayerTextureUpdater::createTexture(CCPrioritizedTextureManager* manager) -{ - return adoptPtr(new Texture(this, CCPrioritizedTexture::create(manager))); -} - -LayerTextureUpdater::SampledTexelFormat FrameBufferSkPictureCanvasLayerTextureUpdater::sampledTexelFormat(GC3Denum textureFormat) -{ - // Here we directly render to the texture, so the component order is always correct. - return LayerTextureUpdater::SampledTexelFormatRGBA; -} - -void FrameBufferSkPictureCanvasLayerTextureUpdater::updateTextureRect(WebGraphicsContext3D* context, GrContext* grContext, CCResourceProvider* resourceProvider, CCPrioritizedTexture* texture, const IntRect& sourceRect, const IntSize& destOffset) -{ - texture->acquireBackingTexture(resourceProvider); - // Flush the context in which the backing texture is created so that it - // is available in other shared contexts. It is important to do here - // because the backing texture is created in one context while it is - // being written to in another. - resourceProvider->flush(); - CCResourceProvider::ScopedWriteLockGL lock(resourceProvider, texture->resourceId()); - - // Make sure ganesh uses the correct GL context. - context->makeContextCurrent(); - // Create an accelerated canvas to draw on. - OwnPtr<SkCanvas> canvas = createAcceleratedCanvas(grContext, texture->size(), lock.textureId()); - - // The compositor expects the textures to be upside-down so it can flip - // the final composited image. Ganesh renders the image upright so we - // need to do a y-flip. - canvas->translate(0.0, texture->size().height()); - canvas->scale(1.0, -1.0); - // Clip to the destination on the texture that must be updated. - canvas->clipRect(SkRect::MakeXYWH(destOffset.width(), destOffset.height(), sourceRect.width(), sourceRect.height())); - // Translate the origin of contentRect to that of destRect. - // Note that destRect is defined relative to sourceRect. - canvas->translate(contentRect().x() - sourceRect.x() + destOffset.width(), - contentRect().y() - sourceRect.y() + destOffset.height()); - drawPicture(canvas.get()); - - // Flush ganesh context so that all the rendered stuff appears on the texture. - grContext->flush(); - - // Flush the GL context so rendering results from this context are visible in the compositor's context. - context->flush(); -} - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.h b/Source/WebCore/platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.h deleted file mode 100644 index 05a9dfef3..000000000 --- a/Source/WebCore/platform/graphics/chromium/FrameBufferSkPictureCanvasLayerTextureUpdater.h +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 FrameBufferSkPictureCanvasLayerTextureUpdater_h -#define FrameBufferSkPictureCanvasLayerTextureUpdater_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "SkPictureCanvasLayerTextureUpdater.h" - -class GrContext; - -namespace WebKit { -class WebGraphicsContext3D; -class WebSharedGraphicsContext3D; -} - -namespace WebCore { - -// This class records the contentRect into an SkPicture, then uses accelerated -// drawing to update the texture. The accelerated drawing goes to an -// intermediate framebuffer and then is copied to the destination texture once done. -class FrameBufferSkPictureCanvasLayerTextureUpdater : public SkPictureCanvasLayerTextureUpdater { -public: - class Texture : public LayerTextureUpdater::Texture { - public: - Texture(FrameBufferSkPictureCanvasLayerTextureUpdater*, PassOwnPtr<CCPrioritizedTexture>); - virtual ~Texture(); - - virtual void updateRect(CCResourceProvider*, const IntRect& sourceRect, const IntSize& destOffset) OVERRIDE; - - private: - FrameBufferSkPictureCanvasLayerTextureUpdater* textureUpdater() { return m_textureUpdater; } - - FrameBufferSkPictureCanvasLayerTextureUpdater* m_textureUpdater; - }; - - static PassRefPtr<FrameBufferSkPictureCanvasLayerTextureUpdater> create(PassOwnPtr<LayerPainterChromium>); - virtual ~FrameBufferSkPictureCanvasLayerTextureUpdater(); - - virtual PassOwnPtr<LayerTextureUpdater::Texture> createTexture(CCPrioritizedTextureManager*) OVERRIDE; - virtual SampledTexelFormat sampledTexelFormat(GC3Denum textureFormat) OVERRIDE; - void updateTextureRect(WebKit::WebGraphicsContext3D*, GrContext*, CCResourceProvider*, CCPrioritizedTexture*, const IntRect& sourceRect, const IntSize& destOffset); - -private: - explicit FrameBufferSkPictureCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium>); -}; -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) -#endif // FrameBufferSkPictureCanvasLayerTextureUpdater_h diff --git a/Source/WebCore/platform/graphics/chromium/GeometryBinding.cpp b/Source/WebCore/platform/graphics/chromium/GeometryBinding.cpp deleted file mode 100644 index 960ef958e..000000000 --- a/Source/WebCore/platform/graphics/chromium/GeometryBinding.cpp +++ /dev/null @@ -1,82 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "GeometryBinding.h" - -#include "CCRendererGL.h" // For the GLC() macro. -#include "GraphicsContext3D.h" -#include <public/WebGraphicsContext3D.h> - -namespace WebCore { - -GeometryBinding::GeometryBinding(WebKit::WebGraphicsContext3D* context, const FloatRect& quadVertexRect) - : m_context(context) - , m_quadVerticesVbo(0) - , m_quadElementsVbo(0) - , m_initialized(false) -{ - // Vertex positions and texture coordinates for the 4 corners of a 1x1 quad. - float vertices[] = { quadVertexRect.x(), quadVertexRect.maxY(), 0.0f, 0.0f, 1.0f, - quadVertexRect.x(), quadVertexRect.y(), 0.0f, 0.0f, 0.0f, - quadVertexRect.maxX(), quadVertexRect.y(), 0.0f, 1.0f, 0.0f, - quadVertexRect.maxX(), quadVertexRect.maxY(), 0.0f, 1.0f, 1.0f }; - uint16_t indices[] = { 0, 1, 2, 0, 2, 3, // The two triangles that make up the layer quad. - 0, 1, 2, 3}; // A line path for drawing the layer border. - - GLC(m_context, m_quadVerticesVbo = m_context->createBuffer()); - GLC(m_context, m_quadElementsVbo = m_context->createBuffer()); - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, m_quadVerticesVbo)); - GLC(m_context, m_context->bufferData(GraphicsContext3D::ARRAY_BUFFER, sizeof(vertices), vertices, GraphicsContext3D::STATIC_DRAW)); - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ELEMENT_ARRAY_BUFFER, m_quadElementsVbo)); - GLC(m_context, m_context->bufferData(GraphicsContext3D::ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GraphicsContext3D::STATIC_DRAW)); - - m_initialized = true; -} - -GeometryBinding::~GeometryBinding() -{ - GLC(m_context, m_context->deleteBuffer(m_quadVerticesVbo)); - GLC(m_context, m_context->deleteBuffer(m_quadElementsVbo)); -} - -void GeometryBinding::prepareForDraw() -{ - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, quadVerticesVbo())); - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ELEMENT_ARRAY_BUFFER, quadElementsVbo())); - unsigned offset = 0; - GLC(m_context, m_context->vertexAttribPointer(positionAttribLocation(), 3, GraphicsContext3D::FLOAT, false, 5 * sizeof(float), offset)); - offset += 3 * sizeof(float); - GLC(m_context, m_context->vertexAttribPointer(texCoordAttribLocation(), 2, GraphicsContext3D::FLOAT, false, 5 * sizeof(float), offset)); - GLC(m_context, m_context->enableVertexAttribArray(positionAttribLocation())); - GLC(m_context, m_context->enableVertexAttribArray(texCoordAttribLocation())); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/GeometryBinding.h b/Source/WebCore/platform/graphics/chromium/GeometryBinding.h deleted file mode 100644 index 0af146c94..000000000 --- a/Source/WebCore/platform/graphics/chromium/GeometryBinding.h +++ /dev/null @@ -1,69 +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 GeometryBinding_h -#define GeometryBinding_h - -#include "FloatRect.h" - -#if USE(ACCELERATED_COMPOSITING) - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class GeometryBinding { -public: - GeometryBinding(WebKit::WebGraphicsContext3D*, const FloatRect& quadVertexRect); - ~GeometryBinding(); - - bool initialized() const { return m_initialized; } - - WebKit::WebGraphicsContext3D* context() const { return m_context; } - unsigned quadVerticesVbo() const { return m_quadVerticesVbo; } - unsigned quadElementsVbo() const { return m_quadElementsVbo; } - - void prepareForDraw(); - - // All layer shaders share the same attribute locations for the vertex - // positions and texture coordinates. This allows switching shaders without - // rebinding attribute arrays. - static int positionAttribLocation() { return 0; } - static int texCoordAttribLocation() { return 1; } - -private: - WebKit::WebGraphicsContext3D* m_context; - unsigned m_quadVerticesVbo; - unsigned m_quadElementsVbo; - bool m_initialized; -}; - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/GraphicsLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/GraphicsLayerChromium.cpp index 0aa145b01..47c03cbe9 100644 --- a/Source/WebCore/platform/graphics/chromium/GraphicsLayerChromium.cpp +++ b/Source/WebCore/platform/graphics/chromium/GraphicsLayerChromium.cpp @@ -46,7 +46,6 @@ #include "GraphicsLayerChromium.h" #include "AnimationTranslationUtil.h" -#include "ContentLayerChromium.h" #include "FloatConversion.h" #include "FloatRect.h" #include "GraphicsContext.h" @@ -70,6 +69,7 @@ #include <wtf/HashSet.h> #include <wtf/StringExtras.h> #include <wtf/text/CString.h> +#include <wtf/text/StringHash.h> #include <wtf/text/WTFString.h> using namespace std; diff --git a/Source/WebCore/platform/graphics/chromium/HeadsUpDisplayLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/HeadsUpDisplayLayerChromium.cpp deleted file mode 100644 index dc71d271c..000000000 --- a/Source/WebCore/platform/graphics/chromium/HeadsUpDisplayLayerChromium.cpp +++ /dev/null @@ -1,91 +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 "HeadsUpDisplayLayerChromium.h" - -#include "CCHeadsUpDisplayLayerImpl.h" -#include "CCLayerTreeHost.h" -#include "TraceEvent.h" - -namespace WebCore { - -PassRefPtr<HeadsUpDisplayLayerChromium> HeadsUpDisplayLayerChromium::create() -{ - return adoptRef(new HeadsUpDisplayLayerChromium()); -} - -HeadsUpDisplayLayerChromium::HeadsUpDisplayLayerChromium() - : LayerChromium() -{ - - setBounds(IntSize(512, 128)); -} - -HeadsUpDisplayLayerChromium::~HeadsUpDisplayLayerChromium() -{ -} - -void HeadsUpDisplayLayerChromium::update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) -{ - const CCLayerTreeSettings& settings = layerTreeHost()->settings(); - int maxTextureSize = layerTreeHost()->rendererCapabilities().maxTextureSize; - - IntSize bounds; - if (settings.showPlatformLayerTree || settings.showDebugRects()) { - bounds.setWidth(std::min(maxTextureSize, layerTreeHost()->deviceViewportSize().width())); - bounds.setHeight(std::min(maxTextureSize, layerTreeHost()->deviceViewportSize().height())); - } else { - bounds.setWidth(512); - bounds.setHeight(128); - } - - setBounds(bounds); -} - -void HeadsUpDisplayLayerChromium::setFontAtlas(PassOwnPtr<CCFontAtlas> fontAtlas) -{ - m_fontAtlas = fontAtlas; - setNeedsCommit(); -} - -PassOwnPtr<CCLayerImpl> HeadsUpDisplayLayerChromium::createCCLayerImpl() -{ - return CCHeadsUpDisplayLayerImpl::create(m_layerId); -} - -void HeadsUpDisplayLayerChromium::pushPropertiesTo(CCLayerImpl* layerImpl) -{ - LayerChromium::pushPropertiesTo(layerImpl); - - if (!m_fontAtlas) - return; - - CCHeadsUpDisplayLayerImpl* hudLayerImpl = static_cast<CCHeadsUpDisplayLayerImpl*>(layerImpl); - hudLayerImpl->setFontAtlas(m_fontAtlas.release()); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/HeadsUpDisplayLayerChromium.h b/Source/WebCore/platform/graphics/chromium/HeadsUpDisplayLayerChromium.h deleted file mode 100644 index 775720e0d..000000000 --- a/Source/WebCore/platform/graphics/chromium/HeadsUpDisplayLayerChromium.h +++ /dev/null @@ -1,57 +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 HeadsUpDisplayLayerChromium_h -#define HeadsUpDisplayLayerChromium_h - -#include "CCFontAtlas.h" -#include "IntSize.h" -#include "LayerChromium.h" - -namespace WebCore { - -class HeadsUpDisplayLayerChromium : public LayerChromium { -public: - static PassRefPtr<HeadsUpDisplayLayerChromium> create(); - virtual ~HeadsUpDisplayLayerChromium(); - - virtual void update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) OVERRIDE; - virtual bool drawsContent() const OVERRIDE { return true; } - - void setFontAtlas(PassOwnPtr<CCFontAtlas>); - - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl() OVERRIDE; - virtual void pushPropertiesTo(CCLayerImpl*) OVERRIDE; - -protected: - HeadsUpDisplayLayerChromium(); - -private: - OwnPtr<CCFontAtlas> m_fontAtlas; -}; - -} -#endif diff --git a/Source/WebCore/platform/graphics/chromium/IOSurfaceLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/IOSurfaceLayerChromium.cpp deleted file mode 100644 index 38dd87711..000000000 --- a/Source/WebCore/platform/graphics/chromium/IOSurfaceLayerChromium.cpp +++ /dev/null @@ -1,77 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "IOSurfaceLayerChromium.h" - -#include "CCIOSurfaceLayerImpl.h" - -namespace WebCore { - -PassRefPtr<IOSurfaceLayerChromium> IOSurfaceLayerChromium::create() -{ - return adoptRef(new IOSurfaceLayerChromium()); -} - -IOSurfaceLayerChromium::IOSurfaceLayerChromium() - : LayerChromium() - , m_ioSurfaceId(0) -{ -} - -IOSurfaceLayerChromium::~IOSurfaceLayerChromium() -{ -} - -void IOSurfaceLayerChromium::setIOSurfaceProperties(uint32_t ioSurfaceId, const IntSize& size) -{ - m_ioSurfaceId = ioSurfaceId; - m_ioSurfaceSize = size; - setNeedsCommit(); -} - -PassOwnPtr<CCLayerImpl> IOSurfaceLayerChromium::createCCLayerImpl() -{ - return CCIOSurfaceLayerImpl::create(m_layerId); -} - -bool IOSurfaceLayerChromium::drawsContent() const -{ - return m_ioSurfaceId && LayerChromium::drawsContent(); -} - -void IOSurfaceLayerChromium::pushPropertiesTo(CCLayerImpl* layer) -{ - LayerChromium::pushPropertiesTo(layer); - - CCIOSurfaceLayerImpl* textureLayer = static_cast<CCIOSurfaceLayerImpl*>(layer); - textureLayer->setIOSurfaceProperties(m_ioSurfaceId, m_ioSurfaceSize); -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/IOSurfaceLayerChromium.h b/Source/WebCore/platform/graphics/chromium/IOSurfaceLayerChromium.h deleted file mode 100644 index 17f943bfc..000000000 --- a/Source/WebCore/platform/graphics/chromium/IOSurfaceLayerChromium.h +++ /dev/null @@ -1,59 +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 IOSurfaceLayerChromium_h -#define IOSurfaceLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerChromium.h" - -namespace WebCore { - -class IOSurfaceLayerChromium : public LayerChromium { -public: - static PassRefPtr<IOSurfaceLayerChromium> create(); - virtual ~IOSurfaceLayerChromium(); - - void setIOSurfaceProperties(uint32_t ioSurfaceId, const IntSize&); - - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl() OVERRIDE; - virtual bool drawsContent() const OVERRIDE; - virtual void pushPropertiesTo(CCLayerImpl*) OVERRIDE; - -protected: - IOSurfaceLayerChromium(); - -private: - - uint32_t m_ioSurfaceId; - IntSize m_ioSurfaceSize; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/ImageLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/ImageLayerChromium.cpp deleted file mode 100644 index 1049e03ee..000000000 --- a/Source/WebCore/platform/graphics/chromium/ImageLayerChromium.cpp +++ /dev/null @@ -1,187 +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 USE(ACCELERATED_COMPOSITING) - -#include "ImageLayerChromium.h" - -#include "CCLayerTreeHost.h" -#include "LayerTextureUpdater.h" -#include "PlatformColor.h" - -namespace WebCore { - -class ImageLayerTextureUpdater : public LayerTextureUpdater { -public: - class Texture : public LayerTextureUpdater::Texture { - public: - Texture(ImageLayerTextureUpdater* textureUpdater, PassOwnPtr<CCPrioritizedTexture> texture) - : LayerTextureUpdater::Texture(texture) - , m_textureUpdater(textureUpdater) - { - } - - virtual void updateRect(CCResourceProvider* resourceProvider, const IntRect& sourceRect, const IntSize& destOffset) OVERRIDE - { - textureUpdater()->updateTextureRect(resourceProvider, texture(), sourceRect, destOffset); - } - - private: - ImageLayerTextureUpdater* textureUpdater() { return m_textureUpdater; } - - ImageLayerTextureUpdater* m_textureUpdater; - }; - - static PassRefPtr<ImageLayerTextureUpdater> create() - { - return adoptRef(new ImageLayerTextureUpdater()); - } - - virtual ~ImageLayerTextureUpdater() { } - - virtual PassOwnPtr<LayerTextureUpdater::Texture> createTexture(CCPrioritizedTextureManager* manager) - { - return adoptPtr(new Texture(this, CCPrioritizedTexture::create(manager))); - } - - virtual SampledTexelFormat sampledTexelFormat(GC3Denum textureFormat) OVERRIDE - { - return PlatformColor::sameComponentOrder(textureFormat) ? - LayerTextureUpdater::SampledTexelFormatRGBA : LayerTextureUpdater::SampledTexelFormatBGRA; - } - - void updateTextureRect(CCResourceProvider* resourceProvider, CCPrioritizedTexture* texture, const IntRect& sourceRect, const IntSize& destOffset) - { - // Source rect should never go outside the image pixels, even if this - // is requested because the texture extends outside the image. - IntRect clippedSourceRect = sourceRect; - IntRect imageRect = IntRect(0, 0, m_bitmap.width(), m_bitmap.height()); - clippedSourceRect.intersect(imageRect); - - IntSize clippedDestOffset = destOffset + IntSize(clippedSourceRect.location() - sourceRect.location()); - - SkAutoLockPixels lock(m_bitmap); - texture->upload(resourceProvider, static_cast<const uint8_t*>(m_bitmap.getPixels()), imageRect, clippedSourceRect, clippedDestOffset); - } - - void setBitmap(const SkBitmap& bitmap) - { - m_bitmap = bitmap; - } - -private: - ImageLayerTextureUpdater() { } - - SkBitmap m_bitmap; -}; - -PassRefPtr<ImageLayerChromium> ImageLayerChromium::create() -{ - return adoptRef(new ImageLayerChromium()); -} - -ImageLayerChromium::ImageLayerChromium() - : TiledLayerChromium() -{ -} - -ImageLayerChromium::~ImageLayerChromium() -{ -} - -void ImageLayerChromium::setBitmap(const SkBitmap& bitmap) -{ - // setBitmap() currently gets called whenever there is any - // style change that affects the layer even if that change doesn't - // affect the actual contents of the image (e.g. a CSS animation). - // With this check in place we avoid unecessary texture uploads. - if (bitmap.pixelRef() && bitmap.pixelRef() == m_bitmap.pixelRef()) - return; - - m_bitmap = bitmap; - setNeedsDisplay(); -} - -void ImageLayerChromium::setTexturePriorities(const CCPriorityCalculator& priorityCalc) -{ - // Update the tile data before creating all the layer's tiles. - updateTileSizeAndTilingOption(); - - TiledLayerChromium::setTexturePriorities(priorityCalc); -} - -void ImageLayerChromium::update(CCTextureUpdateQueue& queue, const CCOcclusionTracker* occlusion, CCRenderingStats& stats) -{ - createTextureUpdaterIfNeeded(); - if (m_needsDisplay) { - m_textureUpdater->setBitmap(m_bitmap); - updateTileSizeAndTilingOption(); - invalidateContentRect(IntRect(IntPoint(), contentBounds())); - m_needsDisplay = false; - } - TiledLayerChromium::update(queue, occlusion, stats); -} - -void ImageLayerChromium::createTextureUpdaterIfNeeded() -{ - if (m_textureUpdater) - return; - - m_textureUpdater = ImageLayerTextureUpdater::create(); - GC3Denum textureFormat = layerTreeHost()->rendererCapabilities().bestTextureFormat; - setTextureFormat(textureFormat); - setSampledTexelFormat(textureUpdater()->sampledTexelFormat(textureFormat)); -} - -LayerTextureUpdater* ImageLayerChromium::textureUpdater() const -{ - return m_textureUpdater.get(); -} - -IntSize ImageLayerChromium::contentBounds() const -{ - return IntSize(m_bitmap.width(), m_bitmap.height()); -} - -bool ImageLayerChromium::drawsContent() const -{ - return !m_bitmap.isNull() && TiledLayerChromium::drawsContent(); -} - -bool ImageLayerChromium::needsContentsScale() const -{ - // Contents scale is not need for image layer because this can be done in compositor more efficiently. - return false; -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/ImageLayerChromium.h b/Source/WebCore/platform/graphics/chromium/ImageLayerChromium.h deleted file mode 100644 index b50e5e715..000000000 --- a/Source/WebCore/platform/graphics/chromium/ImageLayerChromium.h +++ /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. - */ - - -#ifndef ImageLayerChromium_h -#define ImageLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "ContentLayerChromium.h" -#include "SkBitmap.h" - -namespace WebCore { - -class ImageLayerTextureUpdater; - -// A Layer that contains only an Image element. -class ImageLayerChromium : public TiledLayerChromium { -public: - static PassRefPtr<ImageLayerChromium> create(); - virtual ~ImageLayerChromium(); - - virtual bool drawsContent() const OVERRIDE; - virtual void setTexturePriorities(const CCPriorityCalculator&) OVERRIDE; - virtual void update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) OVERRIDE; - virtual bool needsContentsScale() const OVERRIDE; - - void setBitmap(const SkBitmap& image); - -private: - ImageLayerChromium(); - - void setTilingOption(TilingOption); - - virtual LayerTextureUpdater* textureUpdater() const OVERRIDE; - virtual void createTextureUpdaterIfNeeded() OVERRIDE; - virtual IntSize contentBounds() const OVERRIDE; - - SkBitmap m_bitmap; - - RefPtr<ImageLayerTextureUpdater> m_textureUpdater; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/LayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/LayerChromium.cpp deleted file mode 100644 index 2418fded7..000000000 --- a/Source/WebCore/platform/graphics/chromium/LayerChromium.cpp +++ /dev/null @@ -1,751 +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 USE(ACCELERATED_COMPOSITING) -#include "LayerChromium.h" - -#include "CCActiveAnimation.h" -#include "CCAnimationEvents.h" -#include "CCLayerAnimationController.h" -#include "CCLayerImpl.h" -#include "CCLayerTreeHost.h" -#include "CCSettings.h" -#include "TextStream.h" - -#include <public/WebAnimationDelegate.h> -#include <public/WebLayerScrollClient.h> -#include <public/WebSize.h> - -using namespace std; -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -static int s_nextLayerId = 1; - -PassRefPtr<LayerChromium> LayerChromium::create() -{ - return adoptRef(new LayerChromium()); -} - -LayerChromium::LayerChromium() - : m_needsDisplay(false) - , m_stackingOrderChanged(false) - , m_layerId(s_nextLayerId++) - , m_parent(0) - , m_layerTreeHost(0) - , m_layerAnimationController(CCLayerAnimationController::create(this)) - , m_scrollable(false) - , m_shouldScrollOnMainThread(false) - , m_haveWheelEventHandlers(false) - , m_nonFastScrollableRegionChanged(false) - , m_anchorPoint(0.5, 0.5) - , m_backgroundColor(0) - , m_debugBorderColor(0) - , m_debugBorderWidth(0) - , m_opacity(1.0) - , m_anchorPointZ(0) - , m_isContainerForFixedPositionLayers(false) - , m_fixedToContainerLayer(false) - , m_isDrawable(false) - , m_masksToBounds(false) - , m_opaque(false) - , m_doubleSided(true) - , m_useLCDText(false) - , m_preserves3D(false) - , m_useParentBackfaceVisibility(false) - , m_drawCheckerboardForMissingTiles(false) - , m_forceRenderSurface(false) - , m_replicaLayer(0) - , m_drawOpacity(0) - , m_drawOpacityIsAnimating(false) - , m_renderTarget(0) - , m_drawTransformIsAnimating(false) - , m_screenSpaceTransformIsAnimating(false) - , m_contentsScale(1.0) - , m_boundsContainPageScale(false) - , m_layerAnimationDelegate(0) - , m_layerScrollClient(0) -{ - if (m_layerId < 0) { - s_nextLayerId = 1; - m_layerId = s_nextLayerId++; - } -} - -LayerChromium::~LayerChromium() -{ - // Our parent should be holding a reference to us so there should be no - // way for us to be destroyed while we still have a parent. - ASSERT(!parent()); - - // Remove the parent reference from all children. - removeAllChildren(); -} - -void LayerChromium::setUseLCDText(bool useLCDText) -{ - m_useLCDText = useLCDText; -} - -void LayerChromium::setLayerTreeHost(CCLayerTreeHost* host) -{ - if (m_layerTreeHost == host) - return; - - m_layerTreeHost = host; - - for (size_t i = 0; i < m_children.size(); ++i) - m_children[i]->setLayerTreeHost(host); - - if (m_maskLayer) - m_maskLayer->setLayerTreeHost(host); - if (m_replicaLayer) - m_replicaLayer->setLayerTreeHost(host); - - // If this layer already has active animations, the host needs to be notified. - if (host && m_layerAnimationController->hasActiveAnimation()) - host->didAddAnimation(); -} - -void LayerChromium::setNeedsCommit() -{ - if (m_layerTreeHost) - m_layerTreeHost->setNeedsCommit(); -} - -void LayerChromium::setParent(LayerChromium* layer) -{ - ASSERT(!layer || !layer->hasAncestor(this)); - m_parent = layer; - setLayerTreeHost(m_parent ? m_parent->layerTreeHost() : 0); -} - -bool LayerChromium::hasAncestor(LayerChromium* ancestor) const -{ - for (LayerChromium* layer = parent(); layer; layer = layer->parent()) { - if (layer == ancestor) - return true; - } - return false; -} - -void LayerChromium::addChild(PassRefPtr<LayerChromium> child) -{ - insertChild(child, numChildren()); -} - -void LayerChromium::insertChild(PassRefPtr<LayerChromium> child, size_t index) -{ - index = min(index, m_children.size()); - child->removeFromParent(); - child->setParent(this); - child->m_stackingOrderChanged = true; - m_children.insert(index, child); - setNeedsCommit(); -} - -void LayerChromium::removeFromParent() -{ - if (m_parent) - m_parent->removeChild(this); -} - -void LayerChromium::removeChild(LayerChromium* child) -{ - int foundIndex = indexOfChild(child); - if (foundIndex == -1) - return; - - child->setParent(0); - m_children.remove(foundIndex); - setNeedsCommit(); -} - -void LayerChromium::replaceChild(LayerChromium* reference, PassRefPtr<LayerChromium> newLayer) -{ - ASSERT_ARG(reference, reference); - ASSERT_ARG(reference, reference->parent() == this); - - if (reference == newLayer) - return; - - int referenceIndex = indexOfChild(reference); - if (referenceIndex == -1) { - ASSERT_NOT_REACHED(); - return; - } - - reference->removeFromParent(); - - if (newLayer) { - newLayer->removeFromParent(); - insertChild(newLayer, referenceIndex); - } -} - -int LayerChromium::indexOfChild(const LayerChromium* reference) -{ - for (size_t i = 0; i < m_children.size(); i++) { - if (m_children[i] == reference) - return i; - } - return -1; -} - -void LayerChromium::setBounds(const IntSize& size) -{ - if (bounds() == size) - return; - - bool firstResize = bounds().isEmpty() && !size.isEmpty(); - - m_bounds = size; - - if (firstResize) - setNeedsDisplay(); - else - setNeedsCommit(); -} - -LayerChromium* LayerChromium::rootLayer() -{ - LayerChromium* layer = this; - while (layer->parent()) - layer = layer->parent(); - return layer; -} - -void LayerChromium::removeAllChildren() -{ - while (m_children.size()) { - LayerChromium* layer = m_children[0].get(); - ASSERT(layer->parent()); - layer->removeFromParent(); - } -} - -void LayerChromium::setChildren(const Vector<RefPtr<LayerChromium> >& children) -{ - if (children == m_children) - return; - - removeAllChildren(); - size_t listSize = children.size(); - for (size_t i = 0; i < listSize; i++) - addChild(children[i]); -} - -void LayerChromium::setAnchorPoint(const FloatPoint& anchorPoint) -{ - if (m_anchorPoint == anchorPoint) - return; - m_anchorPoint = anchorPoint; - setNeedsCommit(); -} - -void LayerChromium::setAnchorPointZ(float anchorPointZ) -{ - if (m_anchorPointZ == anchorPointZ) - return; - m_anchorPointZ = anchorPointZ; - setNeedsCommit(); -} - -void LayerChromium::setBackgroundColor(SkColor backgroundColor) -{ - if (m_backgroundColor == backgroundColor) - return; - m_backgroundColor = backgroundColor; - setNeedsCommit(); -} - -void LayerChromium::setMasksToBounds(bool masksToBounds) -{ - if (m_masksToBounds == masksToBounds) - return; - m_masksToBounds = masksToBounds; - setNeedsCommit(); -} - -void LayerChromium::setMaskLayer(LayerChromium* maskLayer) -{ - if (m_maskLayer == maskLayer) - return; - if (m_maskLayer) - m_maskLayer->setLayerTreeHost(0); - m_maskLayer = maskLayer; - if (m_maskLayer) { - m_maskLayer->setLayerTreeHost(m_layerTreeHost); - m_maskLayer->setIsMask(true); - } - setNeedsCommit(); -} - -void LayerChromium::setReplicaLayer(LayerChromium* layer) -{ - if (m_replicaLayer == layer) - return; - if (m_replicaLayer) - m_replicaLayer->setLayerTreeHost(0); - m_replicaLayer = layer; - if (m_replicaLayer) - m_replicaLayer->setLayerTreeHost(m_layerTreeHost); - setNeedsCommit(); -} - -void LayerChromium::setFilters(const WebKit::WebFilterOperations& filters) -{ - if (m_filters == filters) - return; - m_filters = filters; - setNeedsCommit(); - if (!filters.isEmpty()) - CCLayerTreeHost::setNeedsFilterContext(true); -} - -void LayerChromium::setBackgroundFilters(const WebKit::WebFilterOperations& backgroundFilters) -{ - if (m_backgroundFilters == backgroundFilters) - return; - m_backgroundFilters = backgroundFilters; - setNeedsCommit(); - if (!backgroundFilters.isEmpty()) - CCLayerTreeHost::setNeedsFilterContext(true); -} - -void LayerChromium::setOpacity(float opacity) -{ - if (m_opacity == opacity) - return; - m_opacity = opacity; - setNeedsCommit(); -} - -bool LayerChromium::opacityIsAnimating() const -{ - return m_layerAnimationController->isAnimatingProperty(CCActiveAnimation::Opacity); -} - -void LayerChromium::setOpaque(bool opaque) -{ - if (m_opaque == opaque) - return; - m_opaque = opaque; - setNeedsDisplay(); -} - -void LayerChromium::setPosition(const FloatPoint& position) -{ - if (m_position == position) - return; - m_position = position; - setNeedsCommit(); -} - -void LayerChromium::setSublayerTransform(const WebTransformationMatrix& sublayerTransform) -{ - if (m_sublayerTransform == sublayerTransform) - return; - m_sublayerTransform = sublayerTransform; - setNeedsCommit(); -} - -void LayerChromium::setTransform(const WebTransformationMatrix& transform) -{ - if (m_transform == transform) - return; - m_transform = transform; - setNeedsCommit(); -} - -bool LayerChromium::transformIsAnimating() const -{ - return m_layerAnimationController->isAnimatingProperty(CCActiveAnimation::Transform); -} - -void LayerChromium::setScrollPosition(const IntPoint& scrollPosition) -{ - if (m_scrollPosition == scrollPosition) - return; - m_scrollPosition = scrollPosition; - if (m_layerScrollClient) - m_layerScrollClient->didScroll(); - setNeedsCommit(); -} - -void LayerChromium::setMaxScrollPosition(const IntSize& maxScrollPosition) -{ - if (m_maxScrollPosition == maxScrollPosition) - return; - m_maxScrollPosition = maxScrollPosition; - setNeedsCommit(); -} - -void LayerChromium::setScrollable(bool scrollable) -{ - if (m_scrollable == scrollable) - return; - m_scrollable = scrollable; - setNeedsCommit(); -} - -void LayerChromium::setShouldScrollOnMainThread(bool shouldScrollOnMainThread) -{ - if (m_shouldScrollOnMainThread == shouldScrollOnMainThread) - return; - m_shouldScrollOnMainThread = shouldScrollOnMainThread; - setNeedsCommit(); -} - -void LayerChromium::setHaveWheelEventHandlers(bool haveWheelEventHandlers) -{ - if (m_haveWheelEventHandlers == haveWheelEventHandlers) - return; - m_haveWheelEventHandlers = haveWheelEventHandlers; - setNeedsCommit(); -} - -void LayerChromium::setNonFastScrollableRegion(const Region& region) -{ - if (m_nonFastScrollableRegion == region) - return; - m_nonFastScrollableRegion = region; - m_nonFastScrollableRegionChanged = true; - setNeedsCommit(); -} - -void LayerChromium::setDrawCheckerboardForMissingTiles(bool checkerboard) -{ - if (m_drawCheckerboardForMissingTiles == checkerboard) - return; - m_drawCheckerboardForMissingTiles = checkerboard; - setNeedsCommit(); -} - -void LayerChromium::setForceRenderSurface(bool force) -{ - if (m_forceRenderSurface == force) - return; - m_forceRenderSurface = force; - setNeedsCommit(); -} - -void LayerChromium::setDoubleSided(bool doubleSided) -{ - if (m_doubleSided == doubleSided) - return; - m_doubleSided = doubleSided; - setNeedsCommit(); -} - -void LayerChromium::setIsDrawable(bool isDrawable) -{ - if (m_isDrawable == isDrawable) - return; - - m_isDrawable = isDrawable; - setNeedsCommit(); -} - -LayerChromium* LayerChromium::parent() const -{ - return m_parent; -} - -void LayerChromium::setNeedsDisplayRect(const FloatRect& dirtyRect) -{ - m_updateRect.unite(dirtyRect); - - // Simply mark the contents as dirty. For non-root layers, the call to - // setNeedsCommit will schedule a fresh compositing pass. - // For the root layer, setNeedsCommit has no effect. - if (!dirtyRect.isEmpty()) - m_needsDisplay = true; - - setNeedsCommit(); -} - -bool LayerChromium::descendantIsFixedToContainerLayer() const -{ - for (size_t i = 0; i < m_children.size(); ++i) { - if (m_children[i]->fixedToContainerLayer() || m_children[i]->descendantIsFixedToContainerLayer()) - return true; - } - return false; -} - -void LayerChromium::setIsContainerForFixedPositionLayers(bool isContainerForFixedPositionLayers) -{ - if (m_isContainerForFixedPositionLayers == isContainerForFixedPositionLayers) - return; - m_isContainerForFixedPositionLayers = isContainerForFixedPositionLayers; - - if (m_layerTreeHost && m_layerTreeHost->commitRequested()) - return; - - // Only request a commit if we have a fixed positioned descendant. - if (descendantIsFixedToContainerLayer()) - setNeedsCommit(); -} - -void LayerChromium::setFixedToContainerLayer(bool fixedToContainerLayer) -{ - if (m_fixedToContainerLayer == fixedToContainerLayer) - return; - m_fixedToContainerLayer = fixedToContainerLayer; - setNeedsCommit(); -} - -void LayerChromium::pushPropertiesTo(CCLayerImpl* layer) -{ - layer->setAnchorPoint(m_anchorPoint); - layer->setAnchorPointZ(m_anchorPointZ); - layer->setBackgroundColor(m_backgroundColor); - layer->setBounds(m_bounds); - layer->setContentBounds(contentBounds()); - layer->setDebugBorderColor(m_debugBorderColor); - layer->setDebugBorderWidth(m_debugBorderWidth); - layer->setDebugName(m_debugName.isolatedCopy()); // We have to use isolatedCopy() here to safely pass ownership to another thread. - layer->setDoubleSided(m_doubleSided); - layer->setDrawCheckerboardForMissingTiles(m_drawCheckerboardForMissingTiles); - layer->setForceRenderSurface(m_forceRenderSurface); - layer->setDrawsContent(drawsContent()); - layer->setFilters(filters()); - layer->setBackgroundFilters(backgroundFilters()); - layer->setUseLCDText(m_useLCDText); - layer->setMasksToBounds(m_masksToBounds); - layer->setScrollable(m_scrollable); - layer->setShouldScrollOnMainThread(m_shouldScrollOnMainThread); - layer->setHaveWheelEventHandlers(m_haveWheelEventHandlers); - // Copying a Region is more expensive than most layer properties, since it involves copying two Vectors that may be - // arbitrarily large depending on page content, so we only push the property if it's changed. - if (m_nonFastScrollableRegionChanged) { - layer->setNonFastScrollableRegion(m_nonFastScrollableRegion); - m_nonFastScrollableRegionChanged = false; - } - layer->setOpaque(m_opaque); - if (!opacityIsAnimating()) - layer->setOpacity(m_opacity); - layer->setPosition(m_position); - layer->setIsContainerForFixedPositionLayers(m_isContainerForFixedPositionLayers); - layer->setFixedToContainerLayer(m_fixedToContainerLayer); - layer->setPreserves3D(preserves3D()); - layer->setUseParentBackfaceVisibility(m_useParentBackfaceVisibility); - layer->setScrollPosition(m_scrollPosition); - layer->setMaxScrollPosition(m_maxScrollPosition); - layer->setSublayerTransform(m_sublayerTransform); - if (!transformIsAnimating()) - layer->setTransform(m_transform); - - // If the main thread commits multiple times before the impl thread actually draws, then damage tracking - // will become incorrect if we simply clobber the updateRect here. The CCLayerImpl's updateRect needs to - // accumulate (i.e. union) any update changes that have occurred on the main thread. - m_updateRect.uniteIfNonZero(layer->updateRect()); - layer->setUpdateRect(m_updateRect); - - layer->setScrollDelta(layer->scrollDelta() - layer->sentScrollDelta()); - layer->setSentScrollDelta(IntSize()); - - layer->setStackingOrderChanged(m_stackingOrderChanged); - - if (maskLayer()) - maskLayer()->pushPropertiesTo(layer->maskLayer()); - if (replicaLayer()) - replicaLayer()->pushPropertiesTo(layer->replicaLayer()); - - m_layerAnimationController->pushAnimationUpdatesTo(layer->layerAnimationController()); - - // Reset any state that should be cleared for the next update. - m_stackingOrderChanged = false; - m_updateRect = FloatRect(); -} - -PassOwnPtr<CCLayerImpl> LayerChromium::createCCLayerImpl() -{ - return CCLayerImpl::create(m_layerId); -} - -void LayerChromium::setDebugBorderColor(SkColor color) -{ - m_debugBorderColor = color; - setNeedsCommit(); -} - -void LayerChromium::setDebugBorderWidth(float width) -{ - m_debugBorderWidth = width; - setNeedsCommit(); -} - -void LayerChromium::setDebugName(const String& debugName) -{ - m_debugName = debugName; - setNeedsCommit(); -} - -void LayerChromium::setContentsScale(float contentsScale) -{ - if (!needsContentsScale() || m_contentsScale == contentsScale) - return; - m_contentsScale = contentsScale; - - setNeedsDisplay(); -} - -void LayerChromium::setBoundsContainPageScale(bool boundsContainPageScale) -{ - if (boundsContainPageScale == m_boundsContainPageScale) - return; - - m_boundsContainPageScale = boundsContainPageScale; - setNeedsDisplay(); -} - -void LayerChromium::createRenderSurface() -{ - ASSERT(!m_renderSurface); - m_renderSurface = adoptPtr(new RenderSurfaceChromium(this)); - setRenderTarget(this); -} - -bool LayerChromium::descendantDrawsContent() -{ - for (size_t i = 0; i < m_children.size(); ++i) { - if (m_children[i]->drawsContent() || m_children[i]->descendantDrawsContent()) - return true; - } - return false; -} - -void LayerChromium::setOpacityFromAnimation(float opacity) -{ - // This is called due to an ongoing accelerated animation. Since this animation is - // also being run on the impl thread, there is no need to request a commit to push - // this value over, so set the value directly rather than calling setOpacity. - m_opacity = opacity; -} - -void LayerChromium::setTransformFromAnimation(const WebTransformationMatrix& transform) -{ - // This is called due to an ongoing accelerated animation. Since this animation is - // also being run on the impl thread, there is no need to request a commit to push - // this value over, so set this value directly rather than calling setTransform. - m_transform = transform; -} - -bool LayerChromium::addAnimation(PassOwnPtr<CCActiveAnimation> animation) -{ - if (!CCSettings::acceleratedAnimationEnabled()) - return false; - - m_layerAnimationController->addAnimation(animation); - if (m_layerTreeHost) { - m_layerTreeHost->didAddAnimation(); - setNeedsCommit(); - } - return true; -} - -void LayerChromium::pauseAnimation(int animationId, double timeOffset) -{ - m_layerAnimationController->pauseAnimation(animationId, timeOffset); - setNeedsCommit(); -} - -void LayerChromium::removeAnimation(int animationId) -{ - m_layerAnimationController->removeAnimation(animationId); - setNeedsCommit(); -} - -void LayerChromium::suspendAnimations(double monotonicTime) -{ - m_layerAnimationController->suspendAnimations(monotonicTime); - setNeedsCommit(); -} - -void LayerChromium::resumeAnimations(double monotonicTime) -{ - m_layerAnimationController->resumeAnimations(monotonicTime); - setNeedsCommit(); -} - -void LayerChromium::setLayerAnimationController(PassOwnPtr<CCLayerAnimationController> layerAnimationController) -{ - m_layerAnimationController = layerAnimationController; - if (m_layerAnimationController) { - m_layerAnimationController->setClient(this); - m_layerAnimationController->setForceSync(); - } - setNeedsCommit(); -} - -PassOwnPtr<CCLayerAnimationController> LayerChromium::releaseLayerAnimationController() -{ - OwnPtr<CCLayerAnimationController> toReturn = m_layerAnimationController.release(); - m_layerAnimationController = CCLayerAnimationController::create(this); - return toReturn.release(); -} - -bool LayerChromium::hasActiveAnimation() const -{ - return m_layerAnimationController->hasActiveAnimation(); -} - -void LayerChromium::notifyAnimationStarted(const CCAnimationEvent& event, double wallClockTime) -{ - m_layerAnimationController->notifyAnimationStarted(event); - if (m_layerAnimationDelegate) - m_layerAnimationDelegate->notifyAnimationStarted(wallClockTime); -} - -void LayerChromium::notifyAnimationFinished(double wallClockTime) -{ - if (m_layerAnimationDelegate) - m_layerAnimationDelegate->notifyAnimationFinished(wallClockTime); -} - -Region LayerChromium::visibleContentOpaqueRegion() const -{ - if (opaque()) - return visibleContentRect(); - return Region(); -} - -void sortLayers(Vector<RefPtr<LayerChromium> >::iterator, Vector<RefPtr<LayerChromium> >::iterator, void*) -{ - // Currently we don't use z-order to decide what to paint, so there's no need to actually sort LayerChromiums. -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/LayerChromium.h b/Source/WebCore/platform/graphics/chromium/LayerChromium.h deleted file mode 100644 index ee0ea7756..000000000 --- a/Source/WebCore/platform/graphics/chromium/LayerChromium.h +++ /dev/null @@ -1,403 +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 LayerChromium_h -#define LayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCLayerAnimationController.h" -#include "CCOcclusionTracker.h" -#include "CCPrioritizedTexture.h" -#include "FloatPoint.h" -#include "Region.h" -#include "RenderSurfaceChromium.h" -#include "SkColor.h" - -#include <public/WebFilterOperations.h> -#include <public/WebTransformationMatrix.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefCounted.h> -#include <wtf/Vector.h> -#include <wtf/text/StringHash.h> -#include <wtf/text/WTFString.h> - -namespace WebKit { -class WebAnimationDelegate; -class WebLayerScrollClient; -} - -namespace WebCore { - -class CCActiveAnimation; -struct CCAnimationEvent; -class CCLayerAnimationDelegate; -class CCLayerImpl; -class CCLayerTreeHost; -class CCTextureUpdateQueue; -class ScrollbarLayerChromium; -struct CCAnimationEvent; -struct CCRenderingStats; - -// Base class for composited layers. Special layer types are derived from -// this class. -class LayerChromium : public RefCounted<LayerChromium>, public CCLayerAnimationControllerClient { -public: - static PassRefPtr<LayerChromium> create(); - - virtual ~LayerChromium(); - - // CCLayerAnimationControllerClient implementation - virtual int id() const OVERRIDE { return m_layerId; } - virtual void setOpacityFromAnimation(float) OVERRIDE; - virtual float opacity() const OVERRIDE { return m_opacity; } - virtual void setTransformFromAnimation(const WebKit::WebTransformationMatrix&) OVERRIDE; - // A layer's transform operates layer space. That is, entirely in logical, - // non-page-scaled pixels (that is, they have page zoom baked in, but not page scale). - // The root layer is a special case -- it operates in physical pixels. - virtual const WebKit::WebTransformationMatrix& transform() const OVERRIDE { return m_transform; } - - LayerChromium* rootLayer(); - LayerChromium* parent() const; - void addChild(PassRefPtr<LayerChromium>); - void insertChild(PassRefPtr<LayerChromium>, size_t index); - void replaceChild(LayerChromium* reference, PassRefPtr<LayerChromium> newLayer); - void removeFromParent(); - void removeAllChildren(); - void setChildren(const Vector<RefPtr<LayerChromium> >&); - const Vector<RefPtr<LayerChromium> >& children() const { return m_children; } - - void setAnchorPoint(const FloatPoint&); - FloatPoint anchorPoint() const { return m_anchorPoint; } - - void setAnchorPointZ(float); - float anchorPointZ() const { return m_anchorPointZ; } - - void setBackgroundColor(SkColor); - SkColor backgroundColor() const { return m_backgroundColor; } - - // A layer's bounds are in logical, non-page-scaled pixels (however, the - // root layer's bounds are in physical pixels). - void setBounds(const IntSize&); - const IntSize& bounds() const { return m_bounds; } - virtual IntSize contentBounds() const { return bounds(); } - - void setMasksToBounds(bool); - bool masksToBounds() const { return m_masksToBounds; } - - void setMaskLayer(LayerChromium*); - LayerChromium* maskLayer() const { return m_maskLayer.get(); } - - virtual void setNeedsDisplayRect(const FloatRect& dirtyRect); - void setNeedsDisplay() { setNeedsDisplayRect(FloatRect(FloatPoint(), bounds())); } - virtual bool needsDisplay() const { return m_needsDisplay; } - - void setOpacity(float); - bool opacityIsAnimating() const; - - void setFilters(const WebKit::WebFilterOperations&); - const WebKit::WebFilterOperations& filters() const { return m_filters; } - - // Background filters are filters applied to what is behind this layer, when they are viewed through non-opaque - // regions in this layer. They are used through the WebLayer interface, and are not exposed to HTML. - void setBackgroundFilters(const WebKit::WebFilterOperations&); - const WebKit::WebFilterOperations& backgroundFilters() const { return m_backgroundFilters; } - - virtual void setOpaque(bool); - bool opaque() const { return m_opaque; } - - void setPosition(const FloatPoint&); - FloatPoint position() const { return m_position; } - - void setIsContainerForFixedPositionLayers(bool); - bool isContainerForFixedPositionLayers() const { return m_isContainerForFixedPositionLayers; } - - void setFixedToContainerLayer(bool); - bool fixedToContainerLayer() const { return m_fixedToContainerLayer; } - - void setSublayerTransform(const WebKit::WebTransformationMatrix&); - const WebKit::WebTransformationMatrix& sublayerTransform() const { return m_sublayerTransform; } - - void setTransform(const WebKit::WebTransformationMatrix&); - bool transformIsAnimating() const; - - const IntRect& visibleContentRect() const { return m_visibleContentRect; } - void setVisibleContentRect(const IntRect& visibleContentRect) { m_visibleContentRect = visibleContentRect; } - - void setScrollPosition(const IntPoint&); - const IntPoint& scrollPosition() const { return m_scrollPosition; } - - void setMaxScrollPosition(const IntSize&); - const IntSize& maxScrollPosition() const { return m_maxScrollPosition; } - - void setScrollable(bool); - bool scrollable() const { return m_scrollable; } - void setShouldScrollOnMainThread(bool); - void setHaveWheelEventHandlers(bool); - const Region& nonFastScrollableRegion() { return m_nonFastScrollableRegion; } - void setNonFastScrollableRegion(const Region&); - void setNonFastScrollableRegionChanged() { m_nonFastScrollableRegionChanged = true; } - void setLayerScrollClient(WebKit::WebLayerScrollClient* layerScrollClient) { m_layerScrollClient = layerScrollClient; } - - void setDrawCheckerboardForMissingTiles(bool); - bool drawCheckerboardForMissingTiles() const { return m_drawCheckerboardForMissingTiles; } - - bool forceRenderSurface() const { return m_forceRenderSurface; } - void setForceRenderSurface(bool); - - IntSize scrollDelta() const { return IntSize(); } - - float pageScaleDelta() const { return 1; } - - void setDoubleSided(bool); - bool doubleSided() const { return m_doubleSided; } - - void setPreserves3D(bool preserve3D) { m_preserves3D = preserve3D; } - bool preserves3D() const { return m_preserves3D; } - - void setUseParentBackfaceVisibility(bool useParentBackfaceVisibility) { m_useParentBackfaceVisibility = useParentBackfaceVisibility; } - bool useParentBackfaceVisibility() const { return m_useParentBackfaceVisibility; } - - virtual void setUseLCDText(bool); - bool useLCDText() const { return m_useLCDText; } - - virtual void setLayerTreeHost(CCLayerTreeHost*); - - void setIsDrawable(bool); - - void setReplicaLayer(LayerChromium*); - LayerChromium* replicaLayer() const { return m_replicaLayer.get(); } - - bool hasMask() const { return m_maskLayer; } - bool hasReplica() const { return m_replicaLayer; } - bool replicaHasMask() const { return m_replicaLayer && (m_maskLayer || m_replicaLayer->m_maskLayer); } - - // These methods typically need to be overwritten by derived classes. - virtual bool drawsContent() const { return m_isDrawable; } - virtual void update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) { } - virtual bool needMoreUpdates() { return false; } - virtual void setIsMask(bool) { } - virtual void bindContentsTexture() { } - virtual bool needsContentsScale() const { return false; } - - void setDebugBorderColor(SkColor); - void setDebugBorderWidth(float); - void setDebugName(const String&); - - virtual void pushPropertiesTo(CCLayerImpl*); - - void clearRenderSurface() { m_renderSurface.clear(); } - RenderSurfaceChromium* renderSurface() const { return m_renderSurface.get(); } - void createRenderSurface(); - - float drawOpacity() const { return m_drawOpacity; } - void setDrawOpacity(float opacity) { m_drawOpacity = opacity; } - - bool drawOpacityIsAnimating() const { return m_drawOpacityIsAnimating; } - void setDrawOpacityIsAnimating(bool drawOpacityIsAnimating) { m_drawOpacityIsAnimating = drawOpacityIsAnimating; } - - LayerChromium* renderTarget() const { ASSERT(!m_renderTarget || m_renderTarget->renderSurface()); return m_renderTarget; } - void setRenderTarget(LayerChromium* target) { m_renderTarget = target; } - - bool drawTransformIsAnimating() const { return m_drawTransformIsAnimating; } - void setDrawTransformIsAnimating(bool animating) { m_drawTransformIsAnimating = animating; } - bool screenSpaceTransformIsAnimating() const { return m_screenSpaceTransformIsAnimating; } - void setScreenSpaceTransformIsAnimating(bool animating) { m_screenSpaceTransformIsAnimating = animating; } - - // This moves from layer space, with origin in the center to target space with origin in the top left. - // That is, it converts from logical, non-page-scaled, to target pixels (and if the target is the - // root render surface, then this converts to physical pixels). - const WebKit::WebTransformationMatrix& drawTransform() const { return m_drawTransform; } - void setDrawTransform(const WebKit::WebTransformationMatrix& matrix) { m_drawTransform = matrix; } - // This moves from content space, with origin the top left to screen space with origin in the top left. - // It converts logical, non-page-scaled pixels to physical pixels. - const WebKit::WebTransformationMatrix& screenSpaceTransform() const { return m_screenSpaceTransform; } - void setScreenSpaceTransform(const WebKit::WebTransformationMatrix& matrix) { m_screenSpaceTransform = matrix; } - const IntRect& drawableContentRect() const { return m_drawableContentRect; } - void setDrawableContentRect(const IntRect& rect) { m_drawableContentRect = rect; } - // The contentsScale converts from logical, non-page-scaled pixels to target pixels. - // The contentsScale is 1 for the root layer as it is already in physical pixels. - float contentsScale() const { return m_contentsScale; } - void setContentsScale(float); - - // When true, the layer's contents are not scaled by the current page scale factor. - void setBoundsContainPageScale(bool); - bool boundsContainPageScale() const { return m_boundsContainPageScale; } - - // Returns true if any of the layer's descendants has content to draw. - bool descendantDrawsContent(); - - CCLayerTreeHost* layerTreeHost() const { return m_layerTreeHost; } - - // Set the priority of all desired textures in this layer. - virtual void setTexturePriorities(const CCPriorityCalculator&) { } - - bool addAnimation(PassOwnPtr<CCActiveAnimation>); - void pauseAnimation(int animationId, double timeOffset); - void removeAnimation(int animationId); - - void suspendAnimations(double monotonicTime); - void resumeAnimations(double monotonicTime); - - CCLayerAnimationController* layerAnimationController() { return m_layerAnimationController.get(); } - void setLayerAnimationController(PassOwnPtr<CCLayerAnimationController>); - PassOwnPtr<CCLayerAnimationController> releaseLayerAnimationController(); - - void setLayerAnimationDelegate(WebKit::WebAnimationDelegate* layerAnimationDelegate) { m_layerAnimationDelegate = layerAnimationDelegate; } - - bool hasActiveAnimation() const; - - virtual void notifyAnimationStarted(const CCAnimationEvent&, double wallClockTime); - virtual void notifyAnimationFinished(double wallClockTime); - - virtual Region visibleContentOpaqueRegion() const; - - virtual ScrollbarLayerChromium* toScrollbarLayerChromium() { return 0; } - -protected: - friend class CCLayerImpl; - friend class TreeSynchronizer; - - LayerChromium(); - - void setNeedsCommit(); - - // This flag is set when layer need repainting/updating. - bool m_needsDisplay; - - // Tracks whether this layer may have changed stacking order with its siblings. - bool m_stackingOrderChanged; - - // The update rect is the region of the compositor resource that was actually updated by the compositor. - // For layers that may do updating outside the compositor's control (i.e. plugin layers), this information - // is not available and the update rect will remain empty. - // Note this rect is in layer space (not content space). - FloatRect m_updateRect; - - RefPtr<LayerChromium> m_maskLayer; - - // Constructs a CCLayerImpl of the correct runtime type for this LayerChromium type. - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl(); - int m_layerId; - -private: - void setParent(LayerChromium*); - bool hasAncestor(LayerChromium*) const; - bool descendantIsFixedToContainerLayer() const; - - size_t numChildren() const { return m_children.size(); } - - // Returns the index of the child or -1 if not found. - int indexOfChild(const LayerChromium*); - - // This should only be called from removeFromParent. - void removeChild(LayerChromium*); - - Vector<RefPtr<LayerChromium> > m_children; - LayerChromium* m_parent; - - // LayerChromium instances have a weak pointer to their CCLayerTreeHost. - // This pointer value is nil when a LayerChromium is not in a tree and is - // updated via setLayerTreeHost() if a layer moves between trees. - CCLayerTreeHost* m_layerTreeHost; - - OwnPtr<CCLayerAnimationController> m_layerAnimationController; - - // Layer properties. - IntSize m_bounds; - - // Uses layer's content space. - IntRect m_visibleContentRect; - - IntPoint m_scrollPosition; - IntSize m_maxScrollPosition; - bool m_scrollable; - bool m_shouldScrollOnMainThread; - bool m_haveWheelEventHandlers; - Region m_nonFastScrollableRegion; - bool m_nonFastScrollableRegionChanged; - FloatPoint m_position; - FloatPoint m_anchorPoint; - SkColor m_backgroundColor; - SkColor m_debugBorderColor; - float m_debugBorderWidth; - String m_debugName; - float m_opacity; - WebKit::WebFilterOperations m_filters; - WebKit::WebFilterOperations m_backgroundFilters; - float m_anchorPointZ; - bool m_isContainerForFixedPositionLayers; - bool m_fixedToContainerLayer; - bool m_isDrawable; - bool m_masksToBounds; - bool m_opaque; - bool m_doubleSided; - bool m_useLCDText; - bool m_preserves3D; - bool m_useParentBackfaceVisibility; - bool m_drawCheckerboardForMissingTiles; - bool m_forceRenderSurface; - - WebKit::WebTransformationMatrix m_transform; - WebKit::WebTransformationMatrix m_sublayerTransform; - - // Replica layer used for reflections. - RefPtr<LayerChromium> m_replicaLayer; - - // Transient properties. - OwnPtr<RenderSurfaceChromium> m_renderSurface; - float m_drawOpacity; - bool m_drawOpacityIsAnimating; - - LayerChromium* m_renderTarget; - - WebKit::WebTransformationMatrix m_drawTransform; - WebKit::WebTransformationMatrix m_screenSpaceTransform; - bool m_drawTransformIsAnimating; - bool m_screenSpaceTransformIsAnimating; - - // Uses target surface space. - IntRect m_drawableContentRect; - float m_contentsScale; - bool m_boundsContainPageScale; - - WebKit::WebAnimationDelegate* m_layerAnimationDelegate; - WebKit::WebLayerScrollClient* m_layerScrollClient; -}; - -void sortLayers(Vector<RefPtr<LayerChromium> >::iterator, Vector<RefPtr<LayerChromium> >::iterator, void*); - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/LayerTextureSubImage.cpp b/Source/WebCore/platform/graphics/chromium/LayerTextureSubImage.cpp deleted file mode 100644 index 5c8960ee2..000000000 --- a/Source/WebCore/platform/graphics/chromium/LayerTextureSubImage.cpp +++ /dev/null @@ -1,130 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerTextureSubImage.h" - -#include "CCRendererGL.h" // For the GLC() macro. -#include "Extensions3DChromium.h" -#include "TraceEvent.h" -#include <public/WebGraphicsContext3D.h> - -using WebKit::WebGraphicsContext3D; - -namespace WebCore { - -LayerTextureSubImage::LayerTextureSubImage(bool useMapTexSubImage) - : m_useMapTexSubImage(useMapTexSubImage) - , m_subImageSize(0) -{ -} - -LayerTextureSubImage::~LayerTextureSubImage() -{ -} - -void LayerTextureSubImage::upload(const uint8_t* image, const IntRect& imageRect, - const IntRect& sourceRect, const IntSize& destOffset, - GC3Denum format, WebGraphicsContext3D* context) -{ - if (m_useMapTexSubImage) - uploadWithMapTexSubImage(image, imageRect, sourceRect, destOffset, format, context); - else - uploadWithTexSubImage(image, imageRect, sourceRect, destOffset, format, context); -} - -void LayerTextureSubImage::uploadWithTexSubImage(const uint8_t* image, const IntRect& imageRect, - const IntRect& sourceRect, const IntSize& destOffset, - GC3Denum format, WebGraphicsContext3D* context) -{ - TRACE_EVENT0("cc", "LayerTextureSubImage::uploadWithTexSubImage"); - - // Offset from image-rect to source-rect. - IntPoint offset(sourceRect.x() - imageRect.x(), sourceRect.y() - imageRect.y()); - - const uint8_t* pixelSource; - if (imageRect.width() == sourceRect.width() && !offset.x()) - pixelSource = &image[4 * offset.y() * imageRect.width()]; - else { - size_t neededSize = 4 * sourceRect.width() * sourceRect.height(); - if (m_subImageSize < neededSize) { - m_subImage = adoptArrayPtr(new uint8_t[neededSize]); - m_subImageSize = neededSize; - } - // Strides not equal, so do a row-by-row memcpy from the - // paint results into a temp buffer for uploading. - for (int row = 0; row < sourceRect.height(); ++row) - memcpy(&m_subImage[sourceRect.width() * 4 * row], - &image[4 * (offset.x() + (offset.y() + row) * imageRect.width())], - sourceRect.width() * 4); - - pixelSource = &m_subImage[0]; - } - - GLC(context, context->texSubImage2D(GraphicsContext3D::TEXTURE_2D, 0, destOffset.width(), destOffset.height(), sourceRect.width(), sourceRect.height(), format, GraphicsContext3D::UNSIGNED_BYTE, pixelSource)); -} - -void LayerTextureSubImage::uploadWithMapTexSubImage(const uint8_t* image, const IntRect& imageRect, - const IntRect& sourceRect, const IntSize& destOffset, - GC3Denum format, WebGraphicsContext3D* context) -{ - TRACE_EVENT0("cc", "LayerTextureSubImage::uploadWithMapTexSubImage"); - // Offset from image-rect to source-rect. - IntPoint offset(sourceRect.x() - imageRect.x(), sourceRect.y() - imageRect.y()); - - // Upload tile data via a mapped transfer buffer - uint8_t* pixelDest = static_cast<uint8_t*>(context->mapTexSubImage2DCHROMIUM(GraphicsContext3D::TEXTURE_2D, 0, destOffset.width(), destOffset.height(), sourceRect.width(), sourceRect.height(), format, GraphicsContext3D::UNSIGNED_BYTE, Extensions3DChromium::WRITE_ONLY)); - - if (!pixelDest) { - uploadWithTexSubImage(image, imageRect, sourceRect, destOffset, format, context); - return; - } - - unsigned int componentsPerPixel; - unsigned int bytesPerComponent; - if (!GraphicsContext3D::computeFormatAndTypeParameters(format, GraphicsContext3D::UNSIGNED_BYTE, &componentsPerPixel, &bytesPerComponent)) { - ASSERT_NOT_REACHED(); - return; - } - - if (imageRect.width() == sourceRect.width() && !offset.x()) - memcpy(pixelDest, &image[offset.y() * imageRect.width() * componentsPerPixel * bytesPerComponent], imageRect.width() * sourceRect.height() * componentsPerPixel * bytesPerComponent); - else { - // Strides not equal, so do a row-by-row memcpy from the - // paint results into the pixelDest - for (int row = 0; row < sourceRect.height(); ++row) - memcpy(&pixelDest[sourceRect.width() * row * componentsPerPixel * bytesPerComponent], - &image[4 * (offset.x() + (offset.y() + row) * imageRect.width())], - sourceRect.width() * componentsPerPixel * bytesPerComponent); - } - GLC(context, context->unmapTexSubImage2DCHROMIUM(pixelDest)); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/LayerTextureSubImage.h b/Source/WebCore/platform/graphics/chromium/LayerTextureSubImage.h deleted file mode 100644 index e2a739a0f..000000000 --- a/Source/WebCore/platform/graphics/chromium/LayerTextureSubImage.h +++ /dev/null @@ -1,67 +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 LayerTextureSubImage_h -#define LayerTextureSubImage_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "GraphicsTypes3D.h" -#include "IntRect.h" -#include "IntSize.h" -#include <wtf/OwnArrayPtr.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class LayerTextureSubImage { -public: - explicit LayerTextureSubImage(bool useMapSubForUpload); - ~LayerTextureSubImage(); - - void upload(const uint8_t* image, const IntRect& imageRect, - const IntRect& sourceRect, const IntSize& destOffset, - GC3Denum format, WebKit::WebGraphicsContext3D*); - -private: - void uploadWithTexSubImage(const uint8_t* image, const IntRect& imageRect, - const IntRect& sourceRect, const IntSize& destOffset, - GC3Denum format, WebKit::WebGraphicsContext3D*); - void uploadWithMapTexSubImage(const uint8_t* image, const IntRect& imageRect, - const IntRect& sourceRect, const IntSize& destOffset, - GC3Denum format, WebKit::WebGraphicsContext3D*); - - bool m_useMapTexSubImage; - size_t m_subImageSize; - OwnArrayPtr<uint8_t> m_subImage; -}; - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) -#endif // LayerTextureSubImage_h diff --git a/Source/WebCore/platform/graphics/chromium/LayerTextureUpdater.h b/Source/WebCore/platform/graphics/chromium/LayerTextureUpdater.h deleted file mode 100644 index 1ad61c8d8..000000000 --- a/Source/WebCore/platform/graphics/chromium/LayerTextureUpdater.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 LayerTextureUpdater_h -#define LayerTextureUpdater_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCPrioritizedTexture.h" -#include "GraphicsTypes3D.h" -#include <wtf/RefCounted.h> - -namespace WebCore { - -class IntRect; -class IntSize; -class TextureManager; -struct CCRenderingStats; - -class LayerTextureUpdater : public RefCounted<LayerTextureUpdater> { -public: - // Allows texture uploaders to store per-tile resources. - class Texture { - public: - virtual ~Texture() { } - - CCPrioritizedTexture* texture() { return m_texture.get(); } - void swapTextureWith(OwnPtr<CCPrioritizedTexture>& texture) { m_texture.swap(texture); } - virtual void prepareRect(const IntRect& /* sourceRect */, CCRenderingStats&) { } - virtual void updateRect(CCResourceProvider*, const IntRect& sourceRect, const IntSize& destOffset) = 0; - protected: - explicit Texture(PassOwnPtr<CCPrioritizedTexture> texture) : m_texture(texture) { } - - private: - OwnPtr<CCPrioritizedTexture> m_texture; - }; - - virtual ~LayerTextureUpdater() { } - - enum SampledTexelFormat { - SampledTexelFormatRGBA, - SampledTexelFormatBGRA, - SampledTexelFormatInvalid, - }; - virtual PassOwnPtr<Texture> createTexture(CCPrioritizedTextureManager*) = 0; - // Returns the format of the texel uploaded by this interface. - // This format should not be confused by texture internal format. - // This format specifies the component order in the sampled texel. - // If the format is TexelFormatBGRA, vec4.x is blue and vec4.z is red. - virtual SampledTexelFormat sampledTexelFormat(GC3Denum textureFormat) = 0; - // The |resultingOpaqueRect| gives back a region of the layer that was painted opaque. If the layer is marked opaque in the updater, - // then this region should be ignored in preference for the entire layer's area. - virtual void prepareToUpdate(const IntRect& contentRect, const IntSize& tileSize, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, CCRenderingStats&) { } - - // Set true by the layer when it is known that the entire output is going to be opaque. - virtual void setOpaque(bool) { } -}; - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) -#endif // LayerTextureUpdater_h diff --git a/Source/WebCore/platform/graphics/chromium/PlatformColor.h b/Source/WebCore/platform/graphics/chromium/PlatformColor.h deleted file mode 100644 index a855215bd..000000000 --- a/Source/WebCore/platform/graphics/chromium/PlatformColor.h +++ /dev/null @@ -1,79 +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 PlatformColor_h -#define PlatformColor_h - -#include "Extensions3D.h" -#include "GraphicsContext3D.h" -#include "SkTypes.h" -#include <public/WebGraphicsContext3D.h> - -namespace WebCore { - -class PlatformColor { -public: - static GraphicsContext3D::SourceDataFormat format() - { - return SK_B32_SHIFT ? GraphicsContext3D::SourceFormatRGBA8 : GraphicsContext3D::SourceFormatBGRA8; - } - - // Returns the most efficient texture format for this platform. - static GC3Denum bestTextureFormat(WebKit::WebGraphicsContext3D* context, bool supportsBGRA8888) - { - GC3Denum textureFormat = GraphicsContext3D::RGBA; - switch (format()) { - case GraphicsContext3D::SourceFormatRGBA8: - break; - case GraphicsContext3D::SourceFormatBGRA8: - if (supportsBGRA8888) - textureFormat = Extensions3D::BGRA_EXT; - break; - default: - ASSERT_NOT_REACHED(); - break; - } - return textureFormat; - } - - // Return true if the given texture format has the same component order - // as the color on this platform. - static bool sameComponentOrder(GC3Denum textureFormat) - { - switch (format()) { - case GraphicsContext3D::SourceFormatRGBA8: - return textureFormat == GraphicsContext3D::RGBA; - case GraphicsContext3D::SourceFormatBGRA8: - return textureFormat == Extensions3D::BGRA_EXT; - default: - ASSERT_NOT_REACHED(); - return false; - } - } -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/ProgramBinding.cpp b/Source/WebCore/platform/graphics/chromium/ProgramBinding.cpp deleted file mode 100644 index ccc14875f..000000000 --- a/Source/WebCore/platform/graphics/chromium/ProgramBinding.cpp +++ /dev/null @@ -1,170 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "ProgramBinding.h" - -#include "CCRendererGL.h" // For the GLC() macro. -#include "GeometryBinding.h" -#include "GraphicsContext3D.h" -#include "TraceEvent.h" -#include <public/WebGraphicsContext3D.h> -#include <wtf/text/CString.h> - -using WebKit::WebGraphicsContext3D; - -namespace WebCore { - -ProgramBindingBase::ProgramBindingBase() - : m_program(0) - , m_vertexShaderId(0) - , m_fragmentShaderId(0) - , m_initialized(false) -{ -} - -ProgramBindingBase::~ProgramBindingBase() -{ - // If you hit these asserts, you initialized but forgot to call cleanup(). - ASSERT(!m_program); - ASSERT(!m_vertexShaderId); - ASSERT(!m_fragmentShaderId); - ASSERT(!m_initialized); -} - -static bool contextLost(WebGraphicsContext3D* context) -{ - return (context->getGraphicsResetStatusARB() != GraphicsContext3D::NO_ERROR); -} - - -void ProgramBindingBase::init(WebGraphicsContext3D* context, const String& vertexShader, const String& fragmentShader) -{ - TRACE_EVENT0("cc", "ProgramBindingBase::init"); - m_vertexShaderId = loadShader(context, GraphicsContext3D::VERTEX_SHADER, vertexShader); - if (!m_vertexShaderId) { - if (!contextLost(context)) - LOG_ERROR("Failed to create vertex shader"); - return; - } - - m_fragmentShaderId = loadShader(context, GraphicsContext3D::FRAGMENT_SHADER, fragmentShader); - if (!m_fragmentShaderId) { - GLC(context, context->deleteShader(m_vertexShaderId)); - m_vertexShaderId = 0; - if (!contextLost(context)) - LOG_ERROR("Failed to create fragment shader"); - return; - } - - m_program = createShaderProgram(context, m_vertexShaderId, m_fragmentShaderId); - ASSERT(m_program || contextLost(context)); -} - -void ProgramBindingBase::link(WebGraphicsContext3D* context) -{ - GLC(context, context->linkProgram(m_program)); - cleanupShaders(context); -#ifndef NDEBUG - int linked = 0; - GLC(context, context->getProgramiv(m_program, GraphicsContext3D::LINK_STATUS, &linked)); - if (!linked) { - if (!contextLost(context)) - LOG_ERROR("Failed to link shader program"); - GLC(context, context->deleteProgram(m_program)); - return; - } -#endif -} - -void ProgramBindingBase::cleanup(WebGraphicsContext3D* context) -{ - m_initialized = false; - if (!m_program) - return; - - ASSERT(context); - GLC(context, context->deleteProgram(m_program)); - m_program = 0; - - cleanupShaders(context); -} - -unsigned ProgramBindingBase::loadShader(WebGraphicsContext3D* context, unsigned type, const String& shaderSource) -{ - unsigned shader = context->createShader(type); - if (!shader) - return 0; - String sourceString(shaderSource); - GLC(context, context->shaderSource(shader, sourceString.utf8().data())); - GLC(context, context->compileShader(shader)); -#ifndef NDEBUG - int compiled = 0; - GLC(context, context->getShaderiv(shader, GraphicsContext3D::COMPILE_STATUS, &compiled)); - if (!compiled) { - GLC(context, context->deleteShader(shader)); - return 0; - } -#endif - return shader; -} - -unsigned ProgramBindingBase::createShaderProgram(WebGraphicsContext3D* context, unsigned vertexShader, unsigned fragmentShader) -{ - unsigned programObject = context->createProgram(); - if (!programObject) { - if (!contextLost(context)) - LOG_ERROR("Failed to create shader program"); - return 0; - } - - GLC(context, context->attachShader(programObject, vertexShader)); - GLC(context, context->attachShader(programObject, fragmentShader)); - - // Bind the common attrib locations. - GLC(context, context->bindAttribLocation(programObject, GeometryBinding::positionAttribLocation(), "a_position")); - GLC(context, context->bindAttribLocation(programObject, GeometryBinding::texCoordAttribLocation(), "a_texCoord")); - - return programObject; -} - -void ProgramBindingBase::cleanupShaders(WebGraphicsContext3D* context) -{ - if (m_vertexShaderId) { - GLC(context, context->deleteShader(m_vertexShaderId)); - m_vertexShaderId = 0; - } - if (m_fragmentShaderId) { - GLC(context, context->deleteShader(m_fragmentShaderId)); - m_fragmentShaderId = 0; - } -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/ProgramBinding.h b/Source/WebCore/platform/graphics/chromium/ProgramBinding.h deleted file mode 100644 index c2d47dffc..000000000 --- a/Source/WebCore/platform/graphics/chromium/ProgramBinding.h +++ /dev/null @@ -1,105 +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 ProgramBinding_h -#define ProgramBinding_h - -#if USE(ACCELERATED_COMPOSITING) - -#include <wtf/text/WTFString.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class ProgramBindingBase { -public: - ProgramBindingBase(); - ~ProgramBindingBase(); - - void init(WebKit::WebGraphicsContext3D*, const String& vertexShader, const String& fragmentShader); - void link(WebKit::WebGraphicsContext3D*); - void cleanup(WebKit::WebGraphicsContext3D*); - - unsigned program() const { ASSERT(m_initialized); return m_program; } - bool initialized() const { return m_initialized; } - -protected: - - unsigned loadShader(WebKit::WebGraphicsContext3D*, unsigned type, const String& shaderSource); - unsigned createShaderProgram(WebKit::WebGraphicsContext3D*, unsigned vertexShader, unsigned fragmentShader); - void cleanupShaders(WebKit::WebGraphicsContext3D*); - - unsigned m_program; - unsigned m_vertexShaderId; - unsigned m_fragmentShaderId; - bool m_initialized; -}; - -template<class VertexShader, class FragmentShader> -class ProgramBinding : public ProgramBindingBase { -public: - explicit ProgramBinding(WebKit::WebGraphicsContext3D* context) - { - ProgramBindingBase::init(context, m_vertexShader.getShaderString(), m_fragmentShader.getShaderString()); - } - - void initialize(WebKit::WebGraphicsContext3D* context, bool usingBindUniform) - { - ASSERT(context); - ASSERT(m_program); - ASSERT(!m_initialized); - - // Need to bind uniforms before linking - if (!usingBindUniform) - link(context); - - int baseUniformIndex = 0; - m_vertexShader.init(context, m_program, usingBindUniform, &baseUniformIndex); - m_fragmentShader.init(context, m_program, usingBindUniform, &baseUniformIndex); - - // Link after binding uniforms - if (usingBindUniform) - link(context); - - m_initialized = true; - } - - const VertexShader& vertexShader() const { return m_vertexShader; } - const FragmentShader& fragmentShader() const { return m_fragmentShader; } - -private: - - VertexShader m_vertexShader; - FragmentShader m_fragmentShader; -}; - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/RateLimiter.cpp b/Source/WebCore/platform/graphics/chromium/RateLimiter.cpp deleted file mode 100644 index c9d5f51e1..000000000 --- a/Source/WebCore/platform/graphics/chromium/RateLimiter.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. - */ - -#include "config.h" - -#if USE(ACCELERATED_COMPOSITING) -#include "RateLimiter.h" - -#include "CCProxy.h" -#include "CCThread.h" -#include "TraceEvent.h" -#include <public/WebGraphicsContext3D.h> - -namespace WebCore { - -class RateLimiter::Task : public CCThread::Task { -public: - static PassOwnPtr<Task> create(RateLimiter* rateLimiter) - { - return adoptPtr(new Task(rateLimiter)); - } - virtual ~Task() { } - -private: - explicit Task(RateLimiter* rateLimiter) - : CCThread::Task(this) - , m_rateLimiter(rateLimiter) - { - } - - virtual void performTask() OVERRIDE - { - m_rateLimiter->rateLimitContext(); - } - - RefPtr<RateLimiter> m_rateLimiter; -}; - -PassRefPtr<RateLimiter> RateLimiter::create(WebKit::WebGraphicsContext3D* context, RateLimiterClient *client) -{ - return adoptRef(new RateLimiter(context, client)); -} - -RateLimiter::RateLimiter(WebKit::WebGraphicsContext3D* context, RateLimiterClient *client) - : m_context(context) - , m_active(false) - , m_client(client) -{ - ASSERT(context); -} - -RateLimiter::~RateLimiter() -{ -} - -void RateLimiter::start() -{ - if (m_active) - return; - - TRACE_EVENT0("cc", "RateLimiter::start"); - m_active = true; - CCProxy::mainThread()->postTask(RateLimiter::Task::create(this)); -} - -void RateLimiter::stop() -{ - TRACE_EVENT0("cc", "RateLimiter::stop"); - m_client = 0; -} - -void RateLimiter::rateLimitContext() -{ - if (!m_client) - return; - - TRACE_EVENT0("cc", "RateLimiter::rateLimitContext"); - - m_active = false; - m_client->rateLimit(); - m_context->rateLimitOffscreenContextCHROMIUM(); -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/RateLimiter.h b/Source/WebCore/platform/graphics/chromium/RateLimiter.h deleted file mode 100644 index 0548fde5e..000000000 --- a/Source/WebCore/platform/graphics/chromium/RateLimiter.h +++ /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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef RateLimiter_h -#define RateLimiter_h - -#if USE(ACCELERATED_COMPOSITING) - -#include <wtf/PassRefPtr.h> -#include <wtf/RefCounted.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class RateLimiterClient { -public: - virtual void rateLimit() = 0; -}; - -// A RateLimiter can be used to make sure that a single context does not dominate all execution time. -// To use, construct a RateLimiter class around the context and call start() whenever calls are made on the -// context outside of normal flow control. RateLimiter will block if the context is too far ahead of the -// compositor. -class RateLimiter : public RefCounted<RateLimiter> { -public: - static PassRefPtr<RateLimiter> create(WebKit::WebGraphicsContext3D*, RateLimiterClient*); - ~RateLimiter(); - - void start(); - - // Context and client will not be accessed after stop(). - void stop(); - -private: - RateLimiter(WebKit::WebGraphicsContext3D*, RateLimiterClient*); - - class Task; - friend class Task; - void rateLimitContext(); - - WebKit::WebGraphicsContext3D* m_context; - bool m_active; - RateLimiterClient *m_client; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/RenderSurfaceChromium.cpp b/Source/WebCore/platform/graphics/chromium/RenderSurfaceChromium.cpp deleted file mode 100644 index 263b60186..000000000 --- a/Source/WebCore/platform/graphics/chromium/RenderSurfaceChromium.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 AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR 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 USE(ACCELERATED_COMPOSITING) - -#include "RenderSurfaceChromium.h" - -#include "CCMathUtil.h" -#include "LayerChromium.h" -#include <public/WebTransformationMatrix.h> -#include <wtf/text/CString.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -RenderSurfaceChromium::RenderSurfaceChromium(LayerChromium* owningLayer) - : m_owningLayer(owningLayer) - , m_drawOpacity(1) - , m_drawOpacityIsAnimating(false) - , m_targetSurfaceTransformsAreAnimating(false) - , m_screenSpaceTransformsAreAnimating(false) - , m_nearestAncestorThatMovesPixels(0) -{ -} - -RenderSurfaceChromium::~RenderSurfaceChromium() -{ -} - -FloatRect RenderSurfaceChromium::drawableContentRect() const -{ - FloatRect drawableContentRect = CCMathUtil::mapClippedRect(m_drawTransform, m_contentRect); - if (m_owningLayer->hasReplica()) - drawableContentRect.unite(CCMathUtil::mapClippedRect(m_replicaDrawTransform, m_contentRect)); - return drawableContentRect; -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/RenderSurfaceChromium.h b/Source/WebCore/platform/graphics/chromium/RenderSurfaceChromium.h deleted file mode 100644 index 787eaaec2..000000000 --- a/Source/WebCore/platform/graphics/chromium/RenderSurfaceChromium.h +++ /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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#ifndef RenderSurfaceChromium_h -#define RenderSurfaceChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "FloatRect.h" -#include "IntRect.h" -#include <public/WebTransformationMatrix.h> -#include <wtf/Noncopyable.h> - -namespace WebCore { - -class LayerChromium; - -class RenderSurfaceChromium { - WTF_MAKE_NONCOPYABLE(RenderSurfaceChromium); -public: - explicit RenderSurfaceChromium(LayerChromium*); - ~RenderSurfaceChromium(); - - // Returns the rect that encloses the RenderSurface including any reflection. - FloatRect drawableContentRect() const; - - const IntRect& contentRect() const { return m_contentRect; } - void setContentRect(const IntRect& contentRect) { m_contentRect = contentRect; } - - float drawOpacity() const { return m_drawOpacity; } - void setDrawOpacity(float drawOpacity) { m_drawOpacity = drawOpacity; } - - bool drawOpacityIsAnimating() const { return m_drawOpacityIsAnimating; } - void setDrawOpacityIsAnimating(bool drawOpacityIsAnimating) { m_drawOpacityIsAnimating = drawOpacityIsAnimating; } - - // This goes from content space with the origin in the center of the rect being transformed to the target space with the origin in the top left of the - // rect being transformed. Position the rect so that the origin is in the center of it before applying this transform. - const WebKit::WebTransformationMatrix& drawTransform() const { return m_drawTransform; } - void setDrawTransform(const WebKit::WebTransformationMatrix& drawTransform) { m_drawTransform = drawTransform; } - - const WebKit::WebTransformationMatrix& screenSpaceTransform() const { return m_screenSpaceTransform; } - void setScreenSpaceTransform(const WebKit::WebTransformationMatrix& screenSpaceTransform) { m_screenSpaceTransform = screenSpaceTransform; } - - const WebKit::WebTransformationMatrix& replicaDrawTransform() const { return m_replicaDrawTransform; } - void setReplicaDrawTransform(const WebKit::WebTransformationMatrix& replicaDrawTransform) { m_replicaDrawTransform = replicaDrawTransform; } - - const WebKit::WebTransformationMatrix& replicaScreenSpaceTransform() const { return m_replicaScreenSpaceTransform; } - void setReplicaScreenSpaceTransform(const WebKit::WebTransformationMatrix& replicaScreenSpaceTransform) { m_replicaScreenSpaceTransform = replicaScreenSpaceTransform; } - - bool targetSurfaceTransformsAreAnimating() const { return m_targetSurfaceTransformsAreAnimating; } - void setTargetSurfaceTransformsAreAnimating(bool animating) { m_targetSurfaceTransformsAreAnimating = animating; } - bool screenSpaceTransformsAreAnimating() const { return m_screenSpaceTransformsAreAnimating; } - void setScreenSpaceTransformsAreAnimating(bool animating) { m_screenSpaceTransformsAreAnimating = animating; } - - const IntRect& clipRect() const { return m_clipRect; } - void setClipRect(const IntRect& clipRect) { m_clipRect = clipRect; } - - void clearLayerList() { m_layerList.clear(); } - Vector<RefPtr<LayerChromium> >& layerList() { return m_layerList; } - - void setNearestAncestorThatMovesPixels(RenderSurfaceChromium* surface) { m_nearestAncestorThatMovesPixels = surface; } - const RenderSurfaceChromium* nearestAncestorThatMovesPixels() const { return m_nearestAncestorThatMovesPixels; } - -private: - LayerChromium* m_owningLayer; - - // Uses this surface's space. - IntRect m_contentRect; - - float m_drawOpacity; - bool m_drawOpacityIsAnimating; - WebKit::WebTransformationMatrix m_drawTransform; - WebKit::WebTransformationMatrix m_screenSpaceTransform; - WebKit::WebTransformationMatrix m_replicaDrawTransform; - WebKit::WebTransformationMatrix m_replicaScreenSpaceTransform; - bool m_targetSurfaceTransformsAreAnimating; - bool m_screenSpaceTransformsAreAnimating; - - // Uses the space of the surface's target surface. - IntRect m_clipRect; - - Vector<RefPtr<LayerChromium> > m_layerList; - - // The nearest ancestor target surface that will contain the contents of this surface, and that is going - // to move pixels within the surface (such as with a blur). This can point to itself. - RenderSurfaceChromium* m_nearestAncestorThatMovesPixels; - - // For CCLayerIteratorActions - int m_targetRenderSurfaceLayerIndexHistory; - int m_currentLayerIndexHistory; - friend struct CCLayerIteratorActions; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/ScrollbarLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/ScrollbarLayerChromium.cpp deleted file mode 100644 index eff14ddfd..000000000 --- a/Source/WebCore/platform/graphics/chromium/ScrollbarLayerChromium.cpp +++ /dev/null @@ -1,281 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "ScrollbarLayerChromium.h" - -#include "BitmapCanvasLayerTextureUpdater.h" -#include "CCLayerTreeHost.h" -#include "CCScrollbarLayerImpl.h" -#include "CCTextureUpdateQueue.h" -#include "LayerPainterChromium.h" -#include <public/WebRect.h> - -using WebKit::WebRect; - -namespace WebCore { - -PassOwnPtr<CCLayerImpl> ScrollbarLayerChromium::createCCLayerImpl() -{ - return CCScrollbarLayerImpl::create(id()); -} - -PassRefPtr<ScrollbarLayerChromium> ScrollbarLayerChromium::create(PassOwnPtr<WebKit::WebScrollbar> scrollbar, WebKit::WebScrollbarThemePainter painter, PassOwnPtr<WebKit::WebScrollbarThemeGeometry> geometry, int scrollLayerId) -{ - return adoptRef(new ScrollbarLayerChromium(scrollbar, painter, geometry, scrollLayerId)); -} - -ScrollbarLayerChromium::ScrollbarLayerChromium(PassOwnPtr<WebKit::WebScrollbar> scrollbar, WebKit::WebScrollbarThemePainter painter, PassOwnPtr<WebKit::WebScrollbarThemeGeometry> geometry, int scrollLayerId) - : m_scrollbar(scrollbar) - , m_painter(painter) - , m_geometry(geometry) - , m_scrollLayerId(scrollLayerId) - , m_textureFormat(GraphicsContext3D::INVALID_ENUM) -{ -} - -void ScrollbarLayerChromium::pushPropertiesTo(CCLayerImpl* layer) -{ - LayerChromium::pushPropertiesTo(layer); - - CCScrollbarLayerImpl* scrollbarLayer = static_cast<CCScrollbarLayerImpl*>(layer); - - if (!scrollbarLayer->scrollbarGeometry()) - scrollbarLayer->setScrollbarGeometry(CCScrollbarGeometryFixedThumb::create(adoptPtr(m_geometry->clone()))); - - scrollbarLayer->setScrollbarData(m_scrollbar.get()); - - if (m_backTrack && m_backTrack->texture()->haveBackingTexture()) - scrollbarLayer->setBackTrackResourceId(m_backTrack->texture()->resourceId()); - else - scrollbarLayer->setBackTrackResourceId(0); - - if (m_foreTrack && m_foreTrack->texture()->haveBackingTexture()) - scrollbarLayer->setForeTrackResourceId(m_foreTrack->texture()->resourceId()); - else - scrollbarLayer->setForeTrackResourceId(0); - - if (m_thumb && m_thumb->texture()->haveBackingTexture()) - scrollbarLayer->setThumbResourceId(m_thumb->texture()->resourceId()); - else - scrollbarLayer->setThumbResourceId(0); -} - -class ScrollbarBackgroundPainter : public LayerPainterChromium { - WTF_MAKE_NONCOPYABLE(ScrollbarBackgroundPainter); -public: - static PassOwnPtr<ScrollbarBackgroundPainter> create(WebKit::WebScrollbar* scrollbar, WebKit::WebScrollbarThemePainter painter, WebKit::WebScrollbarThemeGeometry* geometry, WebKit::WebScrollbar::ScrollbarPart trackPart) - { - return adoptPtr(new ScrollbarBackgroundPainter(scrollbar, painter, geometry, trackPart)); - } - - virtual void paint(SkCanvas* skCanvas, const IntRect& contentRect, FloatRect&) OVERRIDE - { - WebKit::WebCanvas* canvas = skCanvas; - // The following is a simplification of ScrollbarThemeComposite::paint. - WebKit::WebRect contentWebRect(contentRect.x(), contentRect.y(), contentRect.width(), contentRect.height()); - m_painter.paintScrollbarBackground(canvas, contentWebRect); - - if (m_geometry->hasButtons(m_scrollbar)) { - WebRect backButtonStartPaintRect = m_geometry->backButtonStartRect(m_scrollbar); - m_painter.paintBackButtonStart(canvas, backButtonStartPaintRect); - - WebRect backButtonEndPaintRect = m_geometry->backButtonEndRect(m_scrollbar); - m_painter.paintBackButtonEnd(canvas, backButtonEndPaintRect); - - WebRect forwardButtonStartPaintRect = m_geometry->forwardButtonStartRect(m_scrollbar); - m_painter.paintForwardButtonStart(canvas, forwardButtonStartPaintRect); - - WebRect forwardButtonEndPaintRect = m_geometry->forwardButtonEndRect(m_scrollbar); - m_painter.paintForwardButtonEnd(canvas, forwardButtonEndPaintRect); - } - - WebRect trackPaintRect = m_geometry->trackRect(m_scrollbar); - m_painter.paintTrackBackground(canvas, trackPaintRect); - - bool thumbPresent = m_geometry->hasThumb(m_scrollbar); - if (thumbPresent) { - if (m_trackPart == WebKit::WebScrollbar::ForwardTrackPart) - m_painter.paintForwardTrackPart(canvas, trackPaintRect); - else - m_painter.paintBackTrackPart(canvas, trackPaintRect); - } - - m_painter.paintTickmarks(canvas, trackPaintRect); - } -private: - ScrollbarBackgroundPainter(WebKit::WebScrollbar* scrollbar, WebKit::WebScrollbarThemePainter painter, WebKit::WebScrollbarThemeGeometry* geometry, WebKit::WebScrollbar::ScrollbarPart trackPart) - : m_scrollbar(scrollbar) - , m_painter(painter) - , m_geometry(geometry) - , m_trackPart(trackPart) - { - } - - WebKit::WebScrollbar* m_scrollbar; - WebKit::WebScrollbarThemePainter m_painter; - WebKit::WebScrollbarThemeGeometry* m_geometry; - WebKit::WebScrollbar::ScrollbarPart m_trackPart; -}; - -class ScrollbarThumbPainter : public LayerPainterChromium { - WTF_MAKE_NONCOPYABLE(ScrollbarThumbPainter); -public: - static PassOwnPtr<ScrollbarThumbPainter> create(WebKit::WebScrollbar* scrollbar, WebKit::WebScrollbarThemePainter painter, WebKit::WebScrollbarThemeGeometry* geometry) - { - return adoptPtr(new ScrollbarThumbPainter(scrollbar, painter, geometry)); - } - - virtual void paint(SkCanvas* skCanvas, const IntRect& contentRect, FloatRect& opaque) OVERRIDE - { - WebKit::WebCanvas* canvas = skCanvas; - - // Consider the thumb to be at the origin when painting. - WebRect thumbRect = m_geometry->thumbRect(m_scrollbar); - thumbRect.x = 0; - thumbRect.y = 0; - m_painter.paintThumb(canvas, thumbRect); - } - -private: - ScrollbarThumbPainter(WebKit::WebScrollbar* scrollbar, WebKit::WebScrollbarThemePainter painter, WebKit::WebScrollbarThemeGeometry* geometry) - : m_scrollbar(scrollbar) - , m_painter(painter) - , m_geometry(geometry) - { - } - - WebKit::WebScrollbar* m_scrollbar; - WebKit::WebScrollbarThemePainter m_painter; - WebKit::WebScrollbarThemeGeometry* m_geometry; -}; - -void ScrollbarLayerChromium::setLayerTreeHost(CCLayerTreeHost* host) -{ - if (!host || host != layerTreeHost()) { - m_backTrackUpdater.clear(); - m_backTrack.clear(); - m_thumbUpdater.clear(); - m_thumb.clear(); - } - - LayerChromium::setLayerTreeHost(host); -} - -void ScrollbarLayerChromium::createTextureUpdaterIfNeeded() -{ - m_textureFormat = layerTreeHost()->rendererCapabilities().bestTextureFormat; - - if (!m_backTrackUpdater) - m_backTrackUpdater = BitmapCanvasLayerTextureUpdater::create(ScrollbarBackgroundPainter::create(m_scrollbar.get(), m_painter, m_geometry.get(), WebKit::WebScrollbar::BackTrackPart)); - if (!m_backTrack) - m_backTrack = m_backTrackUpdater->createTexture(layerTreeHost()->contentsTextureManager()); - - // Only create two-part track if we think the two parts could be different in appearance. - if (m_scrollbar->isCustomScrollbar()) { - if (!m_foreTrackUpdater) - m_foreTrackUpdater = BitmapCanvasLayerTextureUpdater::create(ScrollbarBackgroundPainter::create(m_scrollbar.get(), m_painter, m_geometry.get(), WebKit::WebScrollbar::ForwardTrackPart)); - if (!m_foreTrack) - m_foreTrack = m_foreTrackUpdater->createTexture(layerTreeHost()->contentsTextureManager()); - } - - if (!m_thumbUpdater) - m_thumbUpdater = BitmapCanvasLayerTextureUpdater::create(ScrollbarThumbPainter::create(m_scrollbar.get(), m_painter, m_geometry.get())); - if (!m_thumb) - m_thumb = m_thumbUpdater->createTexture(layerTreeHost()->contentsTextureManager()); -} - -void ScrollbarLayerChromium::updatePart(LayerTextureUpdater* painter, LayerTextureUpdater::Texture* texture, const IntRect& rect, CCTextureUpdateQueue& queue, CCRenderingStats& stats) -{ - // Skip painting and uploading if there are no invalidations and - // we already have valid texture data. - if (texture->texture()->haveBackingTexture() - && texture->texture()->size() == rect.size() - && m_updateRect.isEmpty()) - return; - - // We should always have enough memory for UI. - ASSERT(texture->texture()->canAcquireBackingTexture()); - if (!texture->texture()->canAcquireBackingTexture()) - return; - - // Paint and upload the entire part. - IntRect paintedOpaqueRect; - painter->prepareToUpdate(rect, rect.size(), 1, 1, paintedOpaqueRect, stats); - texture->prepareRect(rect, stats); - - IntSize destOffset(0, 0); - TextureUploader::Parameters upload = { texture, rect, destOffset }; - queue.appendFullUpload(upload); -} - - -void ScrollbarLayerChromium::setTexturePriorities(const CCPriorityCalculator&) -{ - if (contentBounds().isEmpty()) - return; - - createTextureUpdaterIfNeeded(); - - bool drawsToRoot = !renderTarget()->parent(); - if (m_backTrack) { - m_backTrack->texture()->setDimensions(contentBounds(), m_textureFormat); - m_backTrack->texture()->setRequestPriority(CCPriorityCalculator::uiPriority(drawsToRoot)); - } - if (m_foreTrack) { - m_foreTrack->texture()->setDimensions(contentBounds(), m_textureFormat); - m_foreTrack->texture()->setRequestPriority(CCPriorityCalculator::uiPriority(drawsToRoot)); - } - if (m_thumb) { - WebKit::WebRect thumbRect = m_geometry->thumbRect(m_scrollbar.get()); - m_thumb->texture()->setDimensions(IntSize(thumbRect.width, thumbRect.height), m_textureFormat); - m_thumb->texture()->setRequestPriority(CCPriorityCalculator::uiPriority(drawsToRoot)); - } -} - -void ScrollbarLayerChromium::update(CCTextureUpdateQueue& queue, const CCOcclusionTracker*, CCRenderingStats& stats) -{ - if (contentBounds().isEmpty()) - return; - - createTextureUpdaterIfNeeded(); - - IntPoint scrollbarOrigin(m_scrollbar->location().x, m_scrollbar->location().y); - IntRect contentRect(scrollbarOrigin, contentBounds()); - updatePart(m_backTrackUpdater.get(), m_backTrack.get(), contentRect, queue, stats); - if (m_foreTrack && m_foreTrackUpdater) - updatePart(m_foreTrackUpdater.get(), m_foreTrack.get(), contentRect, queue, stats); - - // Consider the thumb to be at the origin when painting. - WebKit::WebRect thumbRect = m_geometry->thumbRect(m_scrollbar.get()); - IntRect originThumbRect = IntRect(0, 0, thumbRect.width, thumbRect.height); - if (!originThumbRect.isEmpty()) - updatePart(m_thumbUpdater.get(), m_thumb.get(), originThumbRect, queue, stats); -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/ScrollbarLayerChromium.h b/Source/WebCore/platform/graphics/chromium/ScrollbarLayerChromium.h deleted file mode 100644 index 115fb6610..000000000 --- a/Source/WebCore/platform/graphics/chromium/ScrollbarLayerChromium.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 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 ScrollbarLayerChromium_h -#define ScrollbarLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerChromium.h" -#include "LayerTextureUpdater.h" -#include <public/WebScrollbar.h> -#include <public/WebScrollbarThemeGeometry.h> -#include <public/WebScrollbarThemePainter.h> - -namespace WebCore { - -class Scrollbar; -class ScrollbarThemeComposite; -class CCTextureUpdateQueue; - -class ScrollbarLayerChromium : public LayerChromium { -public: - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl() OVERRIDE; - static PassRefPtr<ScrollbarLayerChromium> create(PassOwnPtr<WebKit::WebScrollbar>, WebKit::WebScrollbarThemePainter, PassOwnPtr<WebKit::WebScrollbarThemeGeometry>, int scrollLayerId); - - // LayerChromium interface - virtual void setTexturePriorities(const CCPriorityCalculator&) OVERRIDE; - virtual void update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) OVERRIDE; - virtual void setLayerTreeHost(CCLayerTreeHost*) OVERRIDE; - virtual void pushPropertiesTo(CCLayerImpl*) OVERRIDE; - - int scrollLayerId() const { return m_scrollLayerId; } - void setScrollLayerId(int id) { m_scrollLayerId = id; } - - virtual ScrollbarLayerChromium* toScrollbarLayerChromium() OVERRIDE { return this; } - -protected: - ScrollbarLayerChromium(PassOwnPtr<WebKit::WebScrollbar>, WebKit::WebScrollbarThemePainter, PassOwnPtr<WebKit::WebScrollbarThemeGeometry>, int scrollLayerId); - -private: - void updatePart(LayerTextureUpdater*, LayerTextureUpdater::Texture*, const IntRect&, CCTextureUpdateQueue&, CCRenderingStats&); - void createTextureUpdaterIfNeeded(); - - OwnPtr<WebKit::WebScrollbar> m_scrollbar; - WebKit::WebScrollbarThemePainter m_painter; - OwnPtr<WebKit::WebScrollbarThemeGeometry> m_geometry; - int m_scrollLayerId; - - GC3Denum m_textureFormat; - - RefPtr<LayerTextureUpdater> m_backTrackUpdater; - RefPtr<LayerTextureUpdater> m_foreTrackUpdater; - RefPtr<LayerTextureUpdater> m_thumbUpdater; - - // All the parts of the scrollbar except the thumb - OwnPtr<LayerTextureUpdater::Texture> m_backTrack; - OwnPtr<LayerTextureUpdater::Texture> m_foreTrack; - OwnPtr<LayerTextureUpdater::Texture> m_thumb; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/ShaderChromium.cpp b/Source/WebCore/platform/graphics/chromium/ShaderChromium.cpp deleted file mode 100644 index 8823d1a6c..000000000 --- a/Source/WebCore/platform/graphics/chromium/ShaderChromium.cpp +++ /dev/null @@ -1,905 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "ShaderChromium.h" - -#include <public/WebGraphicsContext3D.h> - -#define SHADER0(Src) #Src -#define SHADER(Src) SHADER0(Src) - -using WebKit::WebGraphicsContext3D; - -namespace WebCore { - -namespace { - -static void getProgramUniformLocations(WebGraphicsContext3D* context, unsigned program, const char** shaderUniforms, size_t count, size_t maxLocations, int* locations, bool usingBindUniform, int* baseUniformIndex) -{ - for (size_t uniformIndex = 0; uniformIndex < count; uniformIndex ++) { - ASSERT(uniformIndex < maxLocations); - - if (usingBindUniform) { - locations[uniformIndex] = (*baseUniformIndex)++; - context->bindUniformLocationCHROMIUM(program, locations[uniformIndex], shaderUniforms[uniformIndex]); - } else - locations[uniformIndex] = context->getUniformLocation(program, shaderUniforms[uniformIndex]); - } -} - -} - -VertexShaderPosTex::VertexShaderPosTex() - : m_matrixLocation(-1) -{ -} - -void VertexShaderPosTex::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "matrix", - }; - int locations[1]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_matrixLocation = locations[0]; - ASSERT(m_matrixLocation != -1); -} - -String VertexShaderPosTex::getShaderString() const -{ - return SHADER( - attribute vec4 a_position; - attribute vec2 a_texCoord; - uniform mat4 matrix; - varying vec2 v_texCoord; - void main() - { - gl_Position = matrix * a_position; - v_texCoord = a_texCoord; - } - ); -} - -VertexShaderPosTexYUVStretch::VertexShaderPosTexYUVStretch() - : m_matrixLocation(-1) - , m_yWidthScaleFactorLocation(-1) - , m_uvWidthScaleFactorLocation(-1) -{ -} - -void VertexShaderPosTexYUVStretch::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "matrix", - "y_widthScaleFactor", - "uv_widthScaleFactor", - }; - int locations[3]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_matrixLocation = locations[0]; - m_yWidthScaleFactorLocation = locations[1]; - m_uvWidthScaleFactorLocation = locations[2]; - ASSERT(m_matrixLocation != -1 && m_yWidthScaleFactorLocation != -1 && m_uvWidthScaleFactorLocation != -1); -} - -String VertexShaderPosTexYUVStretch::getShaderString() const -{ - return SHADER( - precision mediump float; - attribute vec4 a_position; - attribute vec2 a_texCoord; - uniform mat4 matrix; - varying vec2 y_texCoord; - varying vec2 uv_texCoord; - uniform float y_widthScaleFactor; - uniform float uv_widthScaleFactor; - void main() - { - gl_Position = matrix * a_position; - y_texCoord = vec2(y_widthScaleFactor * a_texCoord.x, a_texCoord.y); - uv_texCoord = vec2(uv_widthScaleFactor * a_texCoord.x, a_texCoord.y); - } - ); -} - -VertexShaderPos::VertexShaderPos() - : m_matrixLocation(-1) -{ -} - -void VertexShaderPos::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "matrix", - }; - int locations[1]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_matrixLocation = locations[0]; - ASSERT(m_matrixLocation != -1); -} - -String VertexShaderPos::getShaderString() const -{ - return SHADER( - attribute vec4 a_position; - uniform mat4 matrix; - void main() - { - gl_Position = matrix * a_position; - } - ); -} - -VertexShaderPosTexTransform::VertexShaderPosTexTransform() - : m_matrixLocation(-1) - , m_texTransformLocation(-1) -{ -} - -void VertexShaderPosTexTransform::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "matrix", - "texTransform", - }; - int locations[2]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_matrixLocation = locations[0]; - m_texTransformLocation = locations[1]; - ASSERT(m_matrixLocation != -1 && m_texTransformLocation != -1); -} - -String VertexShaderPosTexTransform::getShaderString() const -{ - return SHADER( - attribute vec4 a_position; - attribute vec2 a_texCoord; - uniform mat4 matrix; - uniform vec4 texTransform; - varying vec2 v_texCoord; - void main() - { - gl_Position = matrix * a_position; - v_texCoord = a_texCoord * texTransform.zw + texTransform.xy; - } - ); -} - -VertexShaderQuad::VertexShaderQuad() - : m_matrixLocation(-1) - , m_pointLocation(-1) -{ -} - -String VertexShaderPosTexIdentity::getShaderString() const -{ - return SHADER( - attribute vec4 a_position; - varying vec2 v_texCoord; - void main() - { - gl_Position = a_position; - v_texCoord = (a_position.xy + vec2(1.0)) * 0.5; - } - ); -} - -void VertexShaderQuad::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "matrix", - "point", - }; - int locations[2]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_matrixLocation = locations[0]; - m_pointLocation = locations[1]; - ASSERT(m_matrixLocation != -1 && m_pointLocation != -1); -} - -String VertexShaderQuad::getShaderString() const -{ - return SHADER( - attribute vec4 a_position; - attribute vec2 a_texCoord; - uniform mat4 matrix; - uniform vec2 point[4]; - varying vec2 v_texCoord; - void main() - { - vec2 complement = abs(a_texCoord - 1.0); - vec4 pos = vec4(0.0, 0.0, a_position.z, a_position.w); - pos.xy += (complement.x * complement.y) * point[0]; - pos.xy += (a_texCoord.x * complement.y) * point[1]; - pos.xy += (a_texCoord.x * a_texCoord.y) * point[2]; - pos.xy += (complement.x * a_texCoord.y) * point[3]; - gl_Position = matrix * pos; - v_texCoord = pos.xy + vec2(0.5); - } - ); -} - -VertexShaderTile::VertexShaderTile() - : m_matrixLocation(-1) - , m_pointLocation(-1) - , m_vertexTexTransformLocation(-1) -{ -} - -void VertexShaderTile::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "matrix", - "point", - "vertexTexTransform", - }; - int locations[3]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_matrixLocation = locations[0]; - m_pointLocation = locations[1]; - m_vertexTexTransformLocation = locations[2]; - ASSERT(m_matrixLocation != -1 && m_pointLocation != -1 && m_vertexTexTransformLocation != -1); -} - -String VertexShaderTile::getShaderString() const -{ - return SHADER( - attribute vec4 a_position; - attribute vec2 a_texCoord; - uniform mat4 matrix; - uniform vec2 point[4]; - uniform vec4 vertexTexTransform; - varying vec2 v_texCoord; - void main() - { - vec2 complement = abs(a_texCoord - 1.0); - vec4 pos = vec4(0.0, 0.0, a_position.z, a_position.w); - pos.xy += (complement.x * complement.y) * point[0]; - pos.xy += (a_texCoord.x * complement.y) * point[1]; - pos.xy += (a_texCoord.x * a_texCoord.y) * point[2]; - pos.xy += (complement.x * a_texCoord.y) * point[3]; - gl_Position = matrix * pos; - v_texCoord = pos.xy * vertexTexTransform.zw + vertexTexTransform.xy; - } - ); -} - -VertexShaderVideoTransform::VertexShaderVideoTransform() - : m_matrixLocation(-1) - , m_texMatrixLocation(-1) -{ -} - -bool VertexShaderVideoTransform::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "matrix", - "texMatrix", - }; - int locations[2]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_matrixLocation = locations[0]; - m_texMatrixLocation = locations[1]; - return m_matrixLocation != -1 && m_texMatrixLocation != -1; -} - -String VertexShaderVideoTransform::getShaderString() const -{ - return SHADER( - attribute vec4 a_position; - attribute vec2 a_texCoord; - uniform mat4 matrix; - uniform mat4 texMatrix; - varying vec2 v_texCoord; - void main() - { - gl_Position = matrix * a_position; - v_texCoord = vec2(texMatrix * vec4(a_texCoord.x, 1.0 - a_texCoord.y, 0.0, 1.0)); - } - ); -} - -FragmentTexAlphaBinding::FragmentTexAlphaBinding() - : m_samplerLocation(-1) - , m_alphaLocation(-1) -{ -} - -void FragmentTexAlphaBinding::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "s_texture", - "alpha", - }; - int locations[2]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_samplerLocation = locations[0]; - m_alphaLocation = locations[1]; - ASSERT(m_samplerLocation != -1 && m_alphaLocation != -1); -} - -FragmentTexOpaqueBinding::FragmentTexOpaqueBinding() - : m_samplerLocation(-1) -{ -} - -void FragmentTexOpaqueBinding::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "s_texture", - }; - int locations[1]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_samplerLocation = locations[0]; - ASSERT(m_samplerLocation != -1); -} - -String FragmentShaderRGBATexFlipAlpha::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform float alpha; - void main() - { - vec4 texColor = texture2D(s_texture, vec2(v_texCoord.x, 1.0 - v_texCoord.y)); - gl_FragColor = vec4(texColor.x, texColor.y, texColor.z, texColor.w) * alpha; - } - ); -} - -bool FragmentShaderOESImageExternal::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "s_texture", - }; - int locations[1]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_samplerLocation = locations[0]; - return m_samplerLocation != -1; -} - -String FragmentShaderOESImageExternal::getShaderString() const -{ - // Cannot use the SHADER() macro because of the '#' char - return "#extension GL_OES_EGL_image_external : require \n" - "precision mediump float;\n" - "varying vec2 v_texCoord;\n" - "uniform samplerExternalOES s_texture;\n" - "void main()\n" - "{\n" - " vec4 texColor = texture2D(s_texture, v_texCoord);\n" - " gl_FragColor = vec4(texColor.x, texColor.y, texColor.z, texColor.w);\n" - "}\n"; -} - -String FragmentShaderRGBATexAlpha::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform float alpha; - void main() - { - vec4 texColor = texture2D(s_texture, v_texCoord); - gl_FragColor = texColor * alpha; - } - ); -} - -String FragmentShaderRGBATexRectFlipAlpha::getShaderString() const -{ - // This must be paired with VertexShaderPosTexTransform to pick up the texTransform uniform. - // The necessary #extension preprocessing directive breaks the SHADER and SHADER0 macros. - return "#extension GL_ARB_texture_rectangle : require\n" - "precision mediump float;\n" - "varying vec2 v_texCoord;\n" - "uniform vec4 texTransform;\n" - "uniform sampler2DRect s_texture;\n" - "uniform float alpha;\n" - "void main()\n" - "{\n" - " vec4 texColor = texture2DRect(s_texture, vec2(v_texCoord.x, texTransform.w - v_texCoord.y));\n" - " gl_FragColor = vec4(texColor.x, texColor.y, texColor.z, texColor.w) * alpha;\n" - "}\n"; -} - -String FragmentShaderRGBATexRectAlpha::getShaderString() const -{ - return "#extension GL_ARB_texture_rectangle : require\n" - "precision mediump float;\n" - "varying vec2 v_texCoord;\n" - "uniform sampler2DRect s_texture;\n" - "uniform float alpha;\n" - "void main()\n" - "{\n" - " vec4 texColor = texture2DRect(s_texture, v_texCoord);\n" - " gl_FragColor = texColor * alpha;\n" - "}\n"; -} - -String FragmentShaderRGBATexOpaque::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - void main() - { - vec4 texColor = texture2D(s_texture, v_texCoord); - gl_FragColor = vec4(texColor.rgb, 1.0); - } - ); -} - -String FragmentShaderRGBATex::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - void main() - { - gl_FragColor = texture2D(s_texture, v_texCoord); - } - ); -} - -String FragmentShaderRGBATexSwizzleAlpha::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform float alpha; - void main() - { - vec4 texColor = texture2D(s_texture, v_texCoord); - gl_FragColor = vec4(texColor.z, texColor.y, texColor.x, texColor.w) * alpha; - } - ); -} - -String FragmentShaderRGBATexSwizzleOpaque::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - void main() - { - vec4 texColor = texture2D(s_texture, v_texCoord); - gl_FragColor = vec4(texColor.z, texColor.y, texColor.x, 1.0); - } - ); -} - -FragmentShaderRGBATexAlphaAA::FragmentShaderRGBATexAlphaAA() - : m_samplerLocation(-1) - , m_alphaLocation(-1) - , m_edgeLocation(-1) -{ -} - -void FragmentShaderRGBATexAlphaAA::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "s_texture", - "alpha", - "edge", - }; - int locations[3]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_samplerLocation = locations[0]; - m_alphaLocation = locations[1]; - m_edgeLocation = locations[2]; - ASSERT(m_samplerLocation != -1 && m_alphaLocation != -1 && m_edgeLocation != -1); -} - -String FragmentShaderRGBATexAlphaAA::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform float alpha; - uniform vec3 edge[8]; - void main() - { - vec4 texColor = texture2D(s_texture, v_texCoord); - vec3 pos = vec3(gl_FragCoord.xy, 1); - float a0 = clamp(dot(edge[0], pos), 0.0, 1.0); - float a1 = clamp(dot(edge[1], pos), 0.0, 1.0); - float a2 = clamp(dot(edge[2], pos), 0.0, 1.0); - float a3 = clamp(dot(edge[3], pos), 0.0, 1.0); - float a4 = clamp(dot(edge[4], pos), 0.0, 1.0); - float a5 = clamp(dot(edge[5], pos), 0.0, 1.0); - float a6 = clamp(dot(edge[6], pos), 0.0, 1.0); - float a7 = clamp(dot(edge[7], pos), 0.0, 1.0); - gl_FragColor = texColor * alpha * min(min(a0, a2) * min(a1, a3), min(a4, a6) * min(a5, a7)); - } - ); -} - -FragmentTexClampAlphaAABinding::FragmentTexClampAlphaAABinding() - : m_samplerLocation(-1) - , m_alphaLocation(-1) - , m_fragmentTexTransformLocation(-1) - , m_edgeLocation(-1) -{ -} - -void FragmentTexClampAlphaAABinding::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "s_texture", - "alpha", - "fragmentTexTransform", - "edge", - }; - int locations[4]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_samplerLocation = locations[0]; - m_alphaLocation = locations[1]; - m_fragmentTexTransformLocation = locations[2]; - m_edgeLocation = locations[3]; - ASSERT(m_samplerLocation != -1 && m_alphaLocation != -1 && m_fragmentTexTransformLocation != -1 && m_edgeLocation != -1); -} - -String FragmentShaderRGBATexClampAlphaAA::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform float alpha; - uniform vec4 fragmentTexTransform; - uniform vec3 edge[8]; - void main() - { - vec2 texCoord = clamp(v_texCoord, 0.0, 1.0) * fragmentTexTransform.zw + fragmentTexTransform.xy; - vec4 texColor = texture2D(s_texture, texCoord); - vec3 pos = vec3(gl_FragCoord.xy, 1); - float a0 = clamp(dot(edge[0], pos), 0.0, 1.0); - float a1 = clamp(dot(edge[1], pos), 0.0, 1.0); - float a2 = clamp(dot(edge[2], pos), 0.0, 1.0); - float a3 = clamp(dot(edge[3], pos), 0.0, 1.0); - float a4 = clamp(dot(edge[4], pos), 0.0, 1.0); - float a5 = clamp(dot(edge[5], pos), 0.0, 1.0); - float a6 = clamp(dot(edge[6], pos), 0.0, 1.0); - float a7 = clamp(dot(edge[7], pos), 0.0, 1.0); - gl_FragColor = texColor * alpha * min(min(a0, a2) * min(a1, a3), min(a4, a6) * min(a5, a7)); - } - ); -} - -String FragmentShaderRGBATexClampSwizzleAlphaAA::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform float alpha; - uniform vec4 fragmentTexTransform; - uniform vec3 edge[8]; - void main() - { - vec2 texCoord = clamp(v_texCoord, 0.0, 1.0) * fragmentTexTransform.zw + fragmentTexTransform.xy; - vec4 texColor = texture2D(s_texture, texCoord); - vec3 pos = vec3(gl_FragCoord.xy, 1); - float a0 = clamp(dot(edge[0], pos), 0.0, 1.0); - float a1 = clamp(dot(edge[1], pos), 0.0, 1.0); - float a2 = clamp(dot(edge[2], pos), 0.0, 1.0); - float a3 = clamp(dot(edge[3], pos), 0.0, 1.0); - float a4 = clamp(dot(edge[4], pos), 0.0, 1.0); - float a5 = clamp(dot(edge[5], pos), 0.0, 1.0); - float a6 = clamp(dot(edge[6], pos), 0.0, 1.0); - float a7 = clamp(dot(edge[7], pos), 0.0, 1.0); - gl_FragColor = vec4(texColor.z, texColor.y, texColor.x, texColor.w) * alpha * min(min(a0, a2) * min(a1, a3), min(a4, a6) * min(a5, a7)); - } - ); -} - -FragmentShaderRGBATexAlphaMask::FragmentShaderRGBATexAlphaMask() - : m_samplerLocation(-1) - , m_maskSamplerLocation(-1) - , m_alphaLocation(-1) - , m_maskTexCoordScaleLocation(-1) -{ -} - -void FragmentShaderRGBATexAlphaMask::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "s_texture", - "s_mask", - "alpha", - "maskTexCoordScale", - "maskTexCoordOffset", - }; - int locations[5]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_samplerLocation = locations[0]; - m_maskSamplerLocation = locations[1]; - m_alphaLocation = locations[2]; - m_maskTexCoordScaleLocation = locations[3]; - m_maskTexCoordOffsetLocation = locations[4]; - ASSERT(m_samplerLocation != -1 && m_maskSamplerLocation != -1 && m_alphaLocation != -1); -} - -String FragmentShaderRGBATexAlphaMask::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform sampler2D s_mask; - uniform vec2 maskTexCoordScale; - uniform vec2 maskTexCoordOffset; - uniform float alpha; - void main() - { - vec4 texColor = texture2D(s_texture, v_texCoord); - vec2 maskTexCoord = vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x, maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y); - vec4 maskColor = texture2D(s_mask, maskTexCoord); - gl_FragColor = vec4(texColor.x, texColor.y, texColor.z, texColor.w) * alpha * maskColor.w; - } - ); -} - -FragmentShaderRGBATexAlphaMaskAA::FragmentShaderRGBATexAlphaMaskAA() - : m_samplerLocation(-1) - , m_maskSamplerLocation(-1) - , m_alphaLocation(-1) - , m_edgeLocation(-1) - , m_maskTexCoordScaleLocation(-1) -{ -} - -void FragmentShaderRGBATexAlphaMaskAA::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "s_texture", - "s_mask", - "alpha", - "edge", - "maskTexCoordScale", - "maskTexCoordOffset", - }; - int locations[6]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_samplerLocation = locations[0]; - m_maskSamplerLocation = locations[1]; - m_alphaLocation = locations[2]; - m_edgeLocation = locations[3]; - m_maskTexCoordScaleLocation = locations[4]; - m_maskTexCoordOffsetLocation = locations[5]; - ASSERT(m_samplerLocation != -1 && m_maskSamplerLocation != -1 && m_alphaLocation != -1 && m_edgeLocation != -1); -} - -String FragmentShaderRGBATexAlphaMaskAA::getShaderString() const -{ - return SHADER( - precision mediump float; - varying vec2 v_texCoord; - uniform sampler2D s_texture; - uniform sampler2D s_mask; - uniform vec2 maskTexCoordScale; - uniform vec2 maskTexCoordOffset; - uniform float alpha; - uniform vec3 edge[8]; - void main() - { - vec4 texColor = texture2D(s_texture, v_texCoord); - vec2 maskTexCoord = vec2(maskTexCoordOffset.x + v_texCoord.x * maskTexCoordScale.x, maskTexCoordOffset.y + v_texCoord.y * maskTexCoordScale.y); - vec4 maskColor = texture2D(s_mask, maskTexCoord); - vec3 pos = vec3(gl_FragCoord.xy, 1); - float a0 = clamp(dot(edge[0], pos), 0.0, 1.0); - float a1 = clamp(dot(edge[1], pos), 0.0, 1.0); - float a2 = clamp(dot(edge[2], pos), 0.0, 1.0); - float a3 = clamp(dot(edge[3], pos), 0.0, 1.0); - float a4 = clamp(dot(edge[4], pos), 0.0, 1.0); - float a5 = clamp(dot(edge[5], pos), 0.0, 1.0); - float a6 = clamp(dot(edge[6], pos), 0.0, 1.0); - float a7 = clamp(dot(edge[7], pos), 0.0, 1.0); - gl_FragColor = vec4(texColor.x, texColor.y, texColor.z, texColor.w) * alpha * maskColor.w * min(min(a0, a2) * min(a1, a3), min(a4, a6) * min(a5, a7)); - } - ); -} - -FragmentShaderYUVVideo::FragmentShaderYUVVideo() - : m_yTextureLocation(-1) - , m_uTextureLocation(-1) - , m_vTextureLocation(-1) - , m_alphaLocation(-1) - , m_ccMatrixLocation(-1) - , m_yuvAdjLocation(-1) -{ -} - -void FragmentShaderYUVVideo::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "y_texture", - "u_texture", - "v_texture", - "alpha", - "cc_matrix", - "yuv_adj", - }; - int locations[6]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_yTextureLocation = locations[0]; - m_uTextureLocation = locations[1]; - m_vTextureLocation = locations[2]; - m_alphaLocation = locations[3]; - m_ccMatrixLocation = locations[4]; - m_yuvAdjLocation = locations[5]; - - ASSERT(m_yTextureLocation != -1 && m_uTextureLocation != -1 && m_vTextureLocation != -1 - && m_alphaLocation != -1 && m_ccMatrixLocation != -1 && m_yuvAdjLocation != -1); -} - -String FragmentShaderYUVVideo::getShaderString() const -{ - return SHADER( - precision mediump float; - precision mediump int; - varying vec2 y_texCoord; - varying vec2 uv_texCoord; - uniform sampler2D y_texture; - uniform sampler2D u_texture; - uniform sampler2D v_texture; - uniform float alpha; - uniform vec3 yuv_adj; - uniform mat3 cc_matrix; - void main() - { - float y_raw = texture2D(y_texture, y_texCoord).x; - float u_unsigned = texture2D(u_texture, uv_texCoord).x; - float v_unsigned = texture2D(v_texture, uv_texCoord).x; - vec3 yuv = vec3(y_raw, u_unsigned, v_unsigned) + yuv_adj; - vec3 rgb = cc_matrix * yuv; - gl_FragColor = vec4(rgb, float(1)) * alpha; - } - ); -} - -FragmentShaderColor::FragmentShaderColor() - : m_colorLocation(-1) -{ -} - -void FragmentShaderColor::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "color", - }; - int locations[1]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_colorLocation = locations[0]; - ASSERT(m_colorLocation != -1); -} - -String FragmentShaderColor::getShaderString() const -{ - return SHADER( - precision mediump float; - uniform vec4 color; - void main() - { - gl_FragColor = color; - } - ); -} - -FragmentShaderCheckerboard::FragmentShaderCheckerboard() - : m_alphaLocation(-1) - , m_texTransformLocation(-1) - , m_frequencyLocation(-1) -{ -} - -void FragmentShaderCheckerboard::init(WebGraphicsContext3D* context, unsigned program, bool usingBindUniform, int* baseUniformIndex) -{ - static const char* shaderUniforms[] = { - "alpha", - "texTransform", - "frequency", - }; - int locations[3]; - - getProgramUniformLocations(context, program, shaderUniforms, WTF_ARRAY_LENGTH(shaderUniforms), WTF_ARRAY_LENGTH(locations), locations, usingBindUniform, baseUniformIndex); - - m_alphaLocation = locations[0]; - m_texTransformLocation = locations[1]; - m_frequencyLocation = locations[2]; - ASSERT(m_alphaLocation != -1 && m_texTransformLocation != -1 && m_frequencyLocation != -1); -} - -String FragmentShaderCheckerboard::getShaderString() const -{ - // Shader based on Example 13-17 of "OpenGL ES 2.0 Programming Guide" - // by Munshi, Ginsburg, Shreiner. - return SHADER( - precision mediump float; - precision mediump int; - varying vec2 v_texCoord; - uniform float alpha; - uniform float frequency; - uniform vec4 texTransform; - void main() - { - vec4 color1 = vec4(1.0, 1.0, 1.0, 1.0); - vec4 color2 = vec4(0.945, 0.945, 0.945, 1.0); - vec2 texCoord = clamp(v_texCoord, 0.0, 1.0) * texTransform.zw + texTransform.xy; - vec2 coord = mod(floor(texCoord * frequency * 2.0), 2.0); - float picker = abs(coord.x - coord.y); - gl_FragColor = mix(color1, color2, picker) * alpha; - } - ); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/ShaderChromium.h b/Source/WebCore/platform/graphics/chromium/ShaderChromium.h deleted file mode 100644 index 5af95d8c7..000000000 --- a/Source/WebCore/platform/graphics/chromium/ShaderChromium.h +++ /dev/null @@ -1,372 +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 ShaderChromium_h -#define ShaderChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "SkColorPriv.h" -#include <wtf/text/WTFString.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class VertexShaderPosTex { -public: - VertexShaderPosTex(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int matrixLocation() const { return m_matrixLocation; } - -private: - int m_matrixLocation; -}; - -class VertexShaderPosTexYUVStretch { -public: - VertexShaderPosTexYUVStretch(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int matrixLocation() const { return m_matrixLocation; } - int yWidthScaleFactorLocation() const { return m_yWidthScaleFactorLocation; } - int uvWidthScaleFactorLocation() const { return m_uvWidthScaleFactorLocation; } - -private: - int m_matrixLocation; - int m_yWidthScaleFactorLocation; - int m_uvWidthScaleFactorLocation; -}; - -class VertexShaderPos { -public: - VertexShaderPos(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int matrixLocation() const { return m_matrixLocation; } - -private: - int m_matrixLocation; -}; - -class VertexShaderPosTexIdentity { -public: - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex) { } - String getShaderString() const; -}; - -class VertexShaderPosTexTransform { -public: - VertexShaderPosTexTransform(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int matrixLocation() const { return m_matrixLocation; } - int texTransformLocation() const { return m_texTransformLocation; } - -private: - int m_matrixLocation; - int m_texTransformLocation; -}; - -class VertexShaderQuad { -public: - VertexShaderQuad(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int matrixLocation() const { return m_matrixLocation; } - int pointLocation() const { return m_pointLocation; } - -private: - int m_matrixLocation; - int m_pointLocation; -}; - -class VertexShaderTile { -public: - VertexShaderTile(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int matrixLocation() const { return m_matrixLocation; } - int pointLocation() const { return m_pointLocation; } - int vertexTexTransformLocation() const { return m_vertexTexTransformLocation; } - -private: - int m_matrixLocation; - int m_pointLocation; - int m_vertexTexTransformLocation; -}; - -class VertexShaderVideoTransform { -public: - VertexShaderVideoTransform(); - - bool init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int matrixLocation() const { return m_matrixLocation; } - int texMatrixLocation() const { return m_texMatrixLocation; } - -private: - int m_matrixLocation; - int m_texMatrixLocation; -}; - -class FragmentTexAlphaBinding { -public: - FragmentTexAlphaBinding(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - int alphaLocation() const { return m_alphaLocation; } - int edgeLocation() const { return -1; } - int fragmentTexTransformLocation() const { return -1; } - int samplerLocation() const { return m_samplerLocation; } - -private: - int m_samplerLocation; - int m_alphaLocation; -}; - -class FragmentTexOpaqueBinding { -public: - FragmentTexOpaqueBinding(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - int alphaLocation() const { return -1; } - int edgeLocation() const { return -1; } - int fragmentTexTransformLocation() const { return -1; } - int samplerLocation() const { return m_samplerLocation; } - -private: - int m_samplerLocation; -}; - -class FragmentShaderRGBATexFlipAlpha : public FragmentTexAlphaBinding { -public: - String getShaderString() const; -}; - -class FragmentShaderRGBATexAlpha : public FragmentTexAlphaBinding { -public: - String getShaderString() const; -}; - -class FragmentShaderRGBATexRectFlipAlpha : public FragmentTexAlphaBinding { -public: - String getShaderString() const; -}; - -class FragmentShaderRGBATexRectAlpha : public FragmentTexAlphaBinding { -public: - String getShaderString() const; -}; - -class FragmentShaderRGBATexOpaque : public FragmentTexOpaqueBinding { -public: - String getShaderString() const; -}; - -class FragmentShaderRGBATex : public FragmentTexOpaqueBinding { -public: - String getShaderString() const; -}; - -// Swizzles the red and blue component of sampled texel with alpha. -class FragmentShaderRGBATexSwizzleAlpha : public FragmentTexAlphaBinding { -public: - String getShaderString() const; -}; - -// Swizzles the red and blue component of sampled texel without alpha. -class FragmentShaderRGBATexSwizzleOpaque : public FragmentTexOpaqueBinding { -public: - String getShaderString() const; -}; - -// Fragment shader for external textures. -class FragmentShaderOESImageExternal : public FragmentTexAlphaBinding { -public: - String getShaderString() const; - bool init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); -private: - int m_samplerLocation; -}; - -class FragmentShaderRGBATexAlphaAA { -public: - FragmentShaderRGBATexAlphaAA(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - String getShaderString() const; - - int alphaLocation() const { return m_alphaLocation; } - int samplerLocation() const { return m_samplerLocation; } - int edgeLocation() const { return m_edgeLocation; } - -private: - int m_samplerLocation; - int m_alphaLocation; - int m_edgeLocation; -}; - -class FragmentTexClampAlphaAABinding { -public: - FragmentTexClampAlphaAABinding(); - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - int alphaLocation() const { return m_alphaLocation; } - int samplerLocation() const { return m_samplerLocation; } - int fragmentTexTransformLocation() const { return m_fragmentTexTransformLocation; } - int edgeLocation() const { return m_edgeLocation; } - -private: - int m_samplerLocation; - int m_alphaLocation; - int m_fragmentTexTransformLocation; - int m_edgeLocation; -}; - -class FragmentShaderRGBATexClampAlphaAA : public FragmentTexClampAlphaAABinding { -public: - String getShaderString() const; -}; - -// Swizzles the red and blue component of sampled texel. -class FragmentShaderRGBATexClampSwizzleAlphaAA : public FragmentTexClampAlphaAABinding { -public: - String getShaderString() const; -}; - -class FragmentShaderRGBATexAlphaMask { -public: - FragmentShaderRGBATexAlphaMask(); - String getShaderString() const; - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - int alphaLocation() const { return m_alphaLocation; } - int samplerLocation() const { return m_samplerLocation; } - int maskSamplerLocation() const { return m_maskSamplerLocation; } - int maskTexCoordScaleLocation() const { return m_maskTexCoordScaleLocation; } - int maskTexCoordOffsetLocation() const { return m_maskTexCoordOffsetLocation; } - -private: - int m_samplerLocation; - int m_maskSamplerLocation; - int m_alphaLocation; - int m_maskTexCoordScaleLocation; - int m_maskTexCoordOffsetLocation; -}; - -class FragmentShaderRGBATexAlphaMaskAA { -public: - FragmentShaderRGBATexAlphaMaskAA(); - String getShaderString() const; - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - int alphaLocation() const { return m_alphaLocation; } - int samplerLocation() const { return m_samplerLocation; } - int maskSamplerLocation() const { return m_maskSamplerLocation; } - int edgeLocation() const { return m_edgeLocation; } - int maskTexCoordScaleLocation() const { return m_maskTexCoordScaleLocation; } - int maskTexCoordOffsetLocation() const { return m_maskTexCoordOffsetLocation; } - -private: - int m_samplerLocation; - int m_maskSamplerLocation; - int m_alphaLocation; - int m_edgeLocation; - int m_maskTexCoordScaleLocation; - int m_maskTexCoordOffsetLocation; -}; - -class FragmentShaderYUVVideo { -public: - FragmentShaderYUVVideo(); - String getShaderString() const; - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - - int yTextureLocation() const { return m_yTextureLocation; } - int uTextureLocation() const { return m_uTextureLocation; } - int vTextureLocation() const { return m_vTextureLocation; } - int alphaLocation() const { return m_alphaLocation; } - int ccMatrixLocation() const { return m_ccMatrixLocation; } - int yuvAdjLocation() const { return m_yuvAdjLocation; } - -private: - int m_yTextureLocation; - int m_uTextureLocation; - int m_vTextureLocation; - int m_alphaLocation; - int m_ccMatrixLocation; - int m_yuvAdjLocation; -}; - -class FragmentShaderColor { -public: - FragmentShaderColor(); - String getShaderString() const; - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - int colorLocation() const { return m_colorLocation; } - -private: - int m_colorLocation; -}; - -class FragmentShaderCheckerboard { -public: - FragmentShaderCheckerboard(); - String getShaderString() const; - - void init(WebKit::WebGraphicsContext3D*, unsigned program, bool usingBindUniform, int* baseUniformIndex); - int alphaLocation() const { return m_alphaLocation; } - int texTransformLocation() const { return m_texTransformLocation; } - int frequencyLocation() const { return m_frequencyLocation; } -private: - int m_alphaLocation; - int m_texTransformLocation; - int m_frequencyLocation; -}; - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.cpp b/Source/WebCore/platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.cpp deleted file mode 100644 index d45c9892b..000000000 --- a/Source/WebCore/platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.cpp +++ /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. - */ - - -#include "config.h" - -#if USE(ACCELERATED_COMPOSITING) - -#include "SkPictureCanvasLayerTextureUpdater.h" - -#include "LayerPainterChromium.h" -#include "SkCanvas.h" -#include "TraceEvent.h" - -namespace WebCore { - -SkPictureCanvasLayerTextureUpdater::SkPictureCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium> painter) - : CanvasLayerTextureUpdater(painter) - , m_layerIsOpaque(false) -{ -} - -SkPictureCanvasLayerTextureUpdater::~SkPictureCanvasLayerTextureUpdater() -{ -} - -void SkPictureCanvasLayerTextureUpdater::prepareToUpdate(const IntRect& contentRect, const IntSize&, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, CCRenderingStats& stats) -{ - SkCanvas* canvas = m_picture.beginRecording(contentRect.width(), contentRect.height()); - paintContents(canvas, contentRect, contentsWidthScale, contentsHeightScale, resultingOpaqueRect, stats); - m_picture.endRecording(); -} - -void SkPictureCanvasLayerTextureUpdater::drawPicture(SkCanvas* canvas) -{ - TRACE_EVENT0("cc", "SkPictureCanvasLayerTextureUpdater::drawPicture"); - canvas->drawPicture(m_picture); -} - -void SkPictureCanvasLayerTextureUpdater::setOpaque(bool opaque) -{ - m_layerIsOpaque = opaque; -} - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.h b/Source/WebCore/platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.h deleted file mode 100644 index 9287ca01d..000000000 --- a/Source/WebCore/platform/graphics/chromium/SkPictureCanvasLayerTextureUpdater.h +++ /dev/null @@ -1,69 +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 SkPictureCanvasLayerTextureUpdater_h -#define SkPictureCanvasLayerTextureUpdater_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CanvasLayerTextureUpdater.h" -#include "SkPicture.h" - -class SkCanvas; - -namespace WebCore { - -class LayerPainterChromium; - -// This class records the contentRect into an SkPicture. Subclasses, provide -// different implementations of tile updating based on this recorded picture. -// The BitmapSkPictureCanvasLayerTextureUpdater and -// FrameBufferSkPictureCanvasLayerTextureUpdater are two examples of such -// implementations. -class SkPictureCanvasLayerTextureUpdater : public CanvasLayerTextureUpdater { -public: - virtual ~SkPictureCanvasLayerTextureUpdater(); - - virtual void setOpaque(bool) OVERRIDE; - -protected: - explicit SkPictureCanvasLayerTextureUpdater(PassOwnPtr<LayerPainterChromium>); - - virtual void prepareToUpdate(const IntRect& contentRect, const IntSize& tileSize, float contentsWidthScale, float contentsHeightScale, IntRect& resultingOpaqueRect, CCRenderingStats&) OVERRIDE; - void drawPicture(SkCanvas*); - - bool layerIsOpaque() const { return m_layerIsOpaque; } - -private: - // Recording canvas. - SkPicture m_picture; - // True when it is known that all output pixels will be opaque. - bool m_layerIsOpaque; -}; - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) -#endif // SkPictureCanvasLayerTextureUpdater_h diff --git a/Source/WebCore/platform/graphics/chromium/SolidColorLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/SolidColorLayerChromium.cpp deleted file mode 100644 index 0da63248a..000000000 --- a/Source/WebCore/platform/graphics/chromium/SolidColorLayerChromium.cpp +++ /dev/null @@ -1,57 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "SolidColorLayerChromium.h" - -#include "CCSolidColorLayerImpl.h" - -namespace WebCore { - -PassOwnPtr<CCLayerImpl> SolidColorLayerChromium::createCCLayerImpl() -{ - return CCSolidColorLayerImpl::create(id()); -} - -PassRefPtr<SolidColorLayerChromium> SolidColorLayerChromium::create() -{ - return adoptRef(new SolidColorLayerChromium()); -} - -SolidColorLayerChromium::SolidColorLayerChromium() - : LayerChromium() -{ -} - -SolidColorLayerChromium::~SolidColorLayerChromium() -{ -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/SolidColorLayerChromium.h b/Source/WebCore/platform/graphics/chromium/SolidColorLayerChromium.h deleted file mode 100644 index 4a64e55fa..000000000 --- a/Source/WebCore/platform/graphics/chromium/SolidColorLayerChromium.h +++ /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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 SolidColorLayerChromium_h -#define SolidColorLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerChromium.h" - -namespace WebCore { - -// A Layer that renders a solid color. The color is specified by using -// setBackgroundColor() on the base class. -class SolidColorLayerChromium : public LayerChromium { -public: - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl() OVERRIDE; - static PassRefPtr<SolidColorLayerChromium> create(); - - virtual ~SolidColorLayerChromium(); - -protected: - SolidColorLayerChromium(); -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif - diff --git a/Source/WebCore/platform/graphics/chromium/TextureCopier.cpp b/Source/WebCore/platform/graphics/chromium/TextureCopier.cpp deleted file mode 100644 index e20c323cc..000000000 --- a/Source/WebCore/platform/graphics/chromium/TextureCopier.cpp +++ /dev/null @@ -1,121 +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 "TextureCopier.h" - -#include "CCRendererGL.h" // For the GLC() macro. -#include "GraphicsContext3D.h" -#include "TraceEvent.h" -#include <public/WebGraphicsContext3D.h> - -namespace WebCore { - -#if USE(ACCELERATED_COMPOSITING) -AcceleratedTextureCopier::AcceleratedTextureCopier(WebKit::WebGraphicsContext3D* context, bool usingBindUniforms) - : m_context(context) - , m_usingBindUniforms(usingBindUniforms) -{ - ASSERT(m_context); - GLC(m_context, m_fbo = m_context->createFramebuffer()); - GLC(m_context, m_positionBuffer = m_context->createBuffer()); - - static const float kPositions[4][4] = { - {-1, -1, 0, 1}, - { 1, -1, 0, 1}, - { 1, 1, 0, 1}, - {-1, 1, 0, 1} - }; - - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, m_positionBuffer)); - GLC(m_context, m_context->bufferData(GraphicsContext3D::ARRAY_BUFFER, sizeof(kPositions), kPositions, GraphicsContext3D::STATIC_DRAW)); - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, 0)); - - m_blitProgram = adoptPtr(new BlitProgram(m_context)); -} - -AcceleratedTextureCopier::~AcceleratedTextureCopier() -{ - if (m_blitProgram) - m_blitProgram->cleanup(m_context); - if (m_positionBuffer) - GLC(m_context, m_context->deleteBuffer(m_positionBuffer)); - if (m_fbo) - GLC(m_context, m_context->deleteFramebuffer(m_fbo)); -} - -void AcceleratedTextureCopier::copyTexture(Parameters parameters) -{ - TRACE_EVENT0("cc", "TextureCopier::copyTexture"); - - // Note: this code does not restore the viewport, bound program, 2D texture, framebuffer, buffer or blend enable. - GLC(m_context, m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo)); - GLC(m_context, m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, parameters.destTexture, 0)); - -#if OS(ANDROID) - // Clear destination to improve performance on tiling GPUs. - // TODO: Use EXT_discard_framebuffer or skip clearing if it isn't available. - GLC(m_context, m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT)); -#endif - - GLC(m_context, m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, parameters.sourceTexture)); - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::NEAREST)); - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::NEAREST)); - - if (!m_blitProgram->initialized()) - m_blitProgram->initialize(m_context, m_usingBindUniforms); - - // TODO: Use EXT_framebuffer_blit if available. - GLC(m_context, m_context->useProgram(m_blitProgram->program())); - - const int kPositionAttribute = 0; - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, m_positionBuffer)); - GLC(m_context, m_context->vertexAttribPointer(kPositionAttribute, 4, GraphicsContext3D::FLOAT, false, 0, 0)); - GLC(m_context, m_context->enableVertexAttribArray(kPositionAttribute)); - GLC(m_context, m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, 0)); - - GLC(m_context, m_context->viewport(0, 0, parameters.size.width(), parameters.size.height())); - GLC(m_context, m_context->disable(GraphicsContext3D::BLEND)); - GLC(m_context, m_context->drawArrays(GraphicsContext3D::TRIANGLE_FAN, 0, 4)); - - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR)); - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR)); - GLC(m_context, m_context->disableVertexAttribArray(kPositionAttribute)); - - GLC(m_context, m_context->useProgram(0)); - - GLC(m_context, m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, 0, 0)); - GLC(m_context, m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0)); - GLC(m_context, m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, 0)); -} - -void AcceleratedTextureCopier::flush() -{ - GLC(m_context, m_context->flush()); -} - -} - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/TextureCopier.h b/Source/WebCore/platform/graphics/chromium/TextureCopier.h deleted file mode 100644 index 68b0f1656..000000000 --- a/Source/WebCore/platform/graphics/chromium/TextureCopier.h +++ /dev/null @@ -1,88 +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 TextureCopier_h -#define TextureCopier_h - -#include "GraphicsContext3D.h" -#include "ProgramBinding.h" -#include "ShaderChromium.h" -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { -class IntSize; - -class TextureCopier { -public: - struct Parameters { - unsigned sourceTexture; - unsigned destTexture; - IntSize size; - }; - // Copy the base level contents of |sourceTexture| to |destTexture|. Both texture objects - // must be complete and have a base level of |size| dimensions. The color formats do not need - // to match, but |destTexture| must have a renderable format. - virtual void copyTexture(Parameters) = 0; - virtual void flush() = 0; - - virtual ~TextureCopier() { } -}; - -#if USE(ACCELERATED_COMPOSITING) - -class AcceleratedTextureCopier : public TextureCopier { - WTF_MAKE_NONCOPYABLE(AcceleratedTextureCopier); -public: - static PassOwnPtr<AcceleratedTextureCopier> create(WebKit::WebGraphicsContext3D* context, bool usingBindUniforms) - { - return adoptPtr(new AcceleratedTextureCopier(context, usingBindUniforms)); - } - virtual ~AcceleratedTextureCopier(); - - virtual void copyTexture(Parameters) OVERRIDE; - virtual void flush() OVERRIDE; - -protected: - AcceleratedTextureCopier(WebKit::WebGraphicsContext3D*, bool usingBindUniforms); - -private: - typedef ProgramBinding<VertexShaderPosTexIdentity, FragmentShaderRGBATex> BlitProgram; - - WebKit::WebGraphicsContext3D* m_context; - Platform3DObject m_fbo; - Platform3DObject m_positionBuffer; - OwnPtr<BlitProgram> m_blitProgram; - bool m_usingBindUniforms; -}; - -#endif // USE(ACCELERATED_COMPOSITING) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/TextureLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/TextureLayerChromium.cpp deleted file mode 100644 index 34fd026eb..000000000 --- a/Source/WebCore/platform/graphics/chromium/TextureLayerChromium.cpp +++ /dev/null @@ -1,155 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "TextureLayerChromium.h" - -#include "CCLayerTreeHost.h" -#include "CCTextureLayerImpl.h" -#include "TextureLayerChromiumClient.h" -#include <public/WebGraphicsContext3D.h> - -namespace WebCore { - -PassRefPtr<TextureLayerChromium> TextureLayerChromium::create(TextureLayerChromiumClient* client) -{ - return adoptRef(new TextureLayerChromium(client)); -} - -TextureLayerChromium::TextureLayerChromium(TextureLayerChromiumClient* client) - : LayerChromium() - , m_client(client) - , m_flipped(true) - , m_uvRect(0, 0, 1, 1) - , m_premultipliedAlpha(true) - , m_rateLimitContext(false) - , m_contextLost(false) - , m_textureId(0) -{ -} - -TextureLayerChromium::~TextureLayerChromium() -{ - if (layerTreeHost()) { - if (m_textureId) - layerTreeHost()->acquireLayerTextures(); - if (m_rateLimitContext && m_client) - layerTreeHost()->stopRateLimiter(m_client->context()); - } -} - -PassOwnPtr<CCLayerImpl> TextureLayerChromium::createCCLayerImpl() -{ - return CCTextureLayerImpl::create(m_layerId); -} - -void TextureLayerChromium::setFlipped(bool flipped) -{ - m_flipped = flipped; - setNeedsCommit(); -} - -void TextureLayerChromium::setUVRect(const FloatRect& rect) -{ - m_uvRect = rect; - setNeedsCommit(); -} - -void TextureLayerChromium::setPremultipliedAlpha(bool premultipliedAlpha) -{ - m_premultipliedAlpha = premultipliedAlpha; - setNeedsCommit(); -} - -void TextureLayerChromium::setRateLimitContext(bool rateLimit) -{ - if (!rateLimit && m_rateLimitContext && m_client && layerTreeHost()) - layerTreeHost()->stopRateLimiter(m_client->context()); - - m_rateLimitContext = rateLimit; -} - -void TextureLayerChromium::setTextureId(unsigned id) -{ - if (m_textureId == id) - return; - if (m_textureId && layerTreeHost()) - layerTreeHost()->acquireLayerTextures(); - m_textureId = id; - setNeedsCommit(); -} - -void TextureLayerChromium::willModifyTexture() -{ - if (layerTreeHost()) - layerTreeHost()->acquireLayerTextures(); -} - -void TextureLayerChromium::setNeedsDisplayRect(const FloatRect& dirtyRect) -{ - LayerChromium::setNeedsDisplayRect(dirtyRect); - - if (m_rateLimitContext && m_client && layerTreeHost()) - layerTreeHost()->startRateLimiter(m_client->context()); -} - -void TextureLayerChromium::setLayerTreeHost(CCLayerTreeHost* host) -{ - if (m_textureId && layerTreeHost() && host != layerTreeHost()) - layerTreeHost()->acquireLayerTextures(); - LayerChromium::setLayerTreeHost(host); -} - -bool TextureLayerChromium::drawsContent() const -{ - return (m_client || m_textureId) && !m_contextLost && LayerChromium::drawsContent(); -} - -void TextureLayerChromium::update(CCTextureUpdateQueue& queue, const CCOcclusionTracker*, CCRenderingStats&) -{ - if (m_client) { - m_textureId = m_client->prepareTexture(queue); - m_contextLost = m_client->context()->getGraphicsResetStatusARB() != GraphicsContext3D::NO_ERROR; - } - - m_needsDisplay = false; -} - -void TextureLayerChromium::pushPropertiesTo(CCLayerImpl* layer) -{ - LayerChromium::pushPropertiesTo(layer); - - CCTextureLayerImpl* textureLayer = static_cast<CCTextureLayerImpl*>(layer); - textureLayer->setFlipped(m_flipped); - textureLayer->setUVRect(m_uvRect); - textureLayer->setPremultipliedAlpha(m_premultipliedAlpha); - textureLayer->setTextureId(m_textureId); -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/TextureLayerChromium.h b/Source/WebCore/platform/graphics/chromium/TextureLayerChromium.h deleted file mode 100644 index fd639f6f9..000000000 --- a/Source/WebCore/platform/graphics/chromium/TextureLayerChromium.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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef TextureLayerChromium_h -#define TextureLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerChromium.h" - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class TextureLayerChromiumClient; - -// A Layer containing a the rendered output of a plugin instance. -class TextureLayerChromium : public LayerChromium { -public: - // If this texture layer requires special preparation logic for each frame driven by - // the compositor, pass in a non-nil client. Pass in a nil client pointer if texture updates - // are driven by an external process. - static PassRefPtr<TextureLayerChromium> create(TextureLayerChromiumClient*); - virtual ~TextureLayerChromium(); - - void clearClient() { m_client = 0; } - - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl() OVERRIDE; - - // Sets whether this texture should be Y-flipped at draw time. Defaults to true. - void setFlipped(bool); - - // Sets a UV transform to be used at draw time. Defaults to (0, 0, 1, 1). - void setUVRect(const FloatRect&); - - // Sets whether the alpha channel is premultiplied or unpremultiplied. Defaults to true. - void setPremultipliedAlpha(bool); - - // Sets whether this context should rate limit on damage to prevent too many frames from - // being queued up before the compositor gets a chance to run. Requires a non-nil client. - // Defaults to false. - void setRateLimitContext(bool); - - // Code path for plugins which supply their own texture ID. - void setTextureId(unsigned); - - void willModifyTexture(); - - virtual void setNeedsDisplayRect(const FloatRect&) OVERRIDE; - - virtual void setLayerTreeHost(CCLayerTreeHost*) OVERRIDE; - virtual bool drawsContent() const OVERRIDE; - virtual void update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) OVERRIDE; - virtual void pushPropertiesTo(CCLayerImpl*) OVERRIDE; - -protected: - explicit TextureLayerChromium(TextureLayerChromiumClient*); - -private: - TextureLayerChromiumClient* m_client; - - bool m_flipped; - FloatRect m_uvRect; - bool m_premultipliedAlpha; - bool m_rateLimitContext; - bool m_contextLost; - - unsigned m_textureId; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/TextureLayerChromiumClient.h b/Source/WebCore/platform/graphics/chromium/TextureLayerChromiumClient.h deleted file mode 100644 index f32cf165d..000000000 --- a/Source/WebCore/platform/graphics/chromium/TextureLayerChromiumClient.h +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 TextureLayerChromiumClient_h -#define TextureLayerChromiumClient_h - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { -class CCTextureUpdateQueue; - -class TextureLayerChromiumClient { -public: - // Called to prepare this layer's texture for compositing. The client may queue a texture - // upload or copy on the CCTextureUpdateQueue. - // Returns the texture ID to be used for compositing. - virtual unsigned prepareTexture(CCTextureUpdateQueue&) = 0; - - // Returns the context that is providing the texture. Used for rate limiting and detecting lost context. - virtual WebKit::WebGraphicsContext3D* context() = 0; - -protected: - virtual ~TextureLayerChromiumClient() { } -}; - -} - -#endif // TextureLayerChromiumClient_h diff --git a/Source/WebCore/platform/graphics/chromium/ThrottledTextureUploader.cpp b/Source/WebCore/platform/graphics/chromium/ThrottledTextureUploader.cpp deleted file mode 100644 index b82ed2b97..000000000 --- a/Source/WebCore/platform/graphics/chromium/ThrottledTextureUploader.cpp +++ /dev/null @@ -1,138 +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 "ThrottledTextureUploader.h" - -#include "Extensions3DChromium.h" -#include <public/WebGraphicsContext3D.h> - -namespace { - -// Number of pending texture update queries to allow. -static const size_t maxPendingQueries = 2; - -} // anonymous namespace - -namespace WebCore { - -ThrottledTextureUploader::Query::Query(WebKit::WebGraphicsContext3D* context) - : m_context(context) - , m_queryId(0) -{ - m_queryId = m_context->createQueryEXT(); -} - -ThrottledTextureUploader::Query::~Query() -{ - m_context->deleteQueryEXT(m_queryId); -} - -void ThrottledTextureUploader::Query::begin() -{ - m_context->beginQueryEXT(Extensions3DChromium::COMMANDS_ISSUED_CHROMIUM, m_queryId); -} - -void ThrottledTextureUploader::Query::end() -{ - m_context->endQueryEXT(Extensions3DChromium::COMMANDS_ISSUED_CHROMIUM); -} - -bool ThrottledTextureUploader::Query::isPending() -{ - unsigned available = 1; - m_context->getQueryObjectuivEXT(m_queryId, Extensions3DChromium::QUERY_RESULT_AVAILABLE_EXT, &available); - return !available; -} - -void ThrottledTextureUploader::Query::wait() -{ - unsigned result; - m_context->getQueryObjectuivEXT(m_queryId, Extensions3DChromium::QUERY_RESULT_EXT, &result); -} - -ThrottledTextureUploader::ThrottledTextureUploader(WebKit::WebGraphicsContext3D* context) - : m_context(context) - , m_maxPendingQueries(maxPendingQueries) -{ -} - -ThrottledTextureUploader::ThrottledTextureUploader(WebKit::WebGraphicsContext3D* context, size_t pendingUploadLimit) - : m_context(context) - , m_maxPendingQueries(pendingUploadLimit) -{ - ASSERT(m_context); -} - -ThrottledTextureUploader::~ThrottledTextureUploader() -{ -} - -bool ThrottledTextureUploader::isBusy() -{ - processQueries(); - - if (!m_availableQueries.isEmpty()) - return false; - - if (m_pendingQueries.size() == m_maxPendingQueries) - return true; - - m_availableQueries.append(Query::create(m_context)); - return false; -} - -void ThrottledTextureUploader::beginUploads() -{ - // Wait for query to become available. - while (isBusy()) - m_pendingQueries.first()->wait(); - - ASSERT(!m_availableQueries.isEmpty()); - m_availableQueries.first()->begin(); -} - -void ThrottledTextureUploader::endUploads() -{ - m_availableQueries.first()->end(); - m_pendingQueries.append(m_availableQueries.takeFirst()); -} - -void ThrottledTextureUploader::uploadTexture(CCResourceProvider* resourceProvider, Parameters upload) -{ - upload.texture->updateRect(resourceProvider, upload.sourceRect, upload.destOffset); -} - -void ThrottledTextureUploader::processQueries() -{ - while (!m_pendingQueries.isEmpty()) { - if (m_pendingQueries.first()->isPending()) - break; - - m_availableQueries.append(m_pendingQueries.takeFirst()); - } -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/ThrottledTextureUploader.h b/Source/WebCore/platform/graphics/chromium/ThrottledTextureUploader.h deleted file mode 100644 index 361468fc8..000000000 --- a/Source/WebCore/platform/graphics/chromium/ThrottledTextureUploader.h +++ /dev/null @@ -1,88 +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 ThrottledTextureUploader_h -#define ThrottledTextureUploader_h - -#include "TextureUploader.h" - -#include <wtf/Deque.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class ThrottledTextureUploader : public TextureUploader { - WTF_MAKE_NONCOPYABLE(ThrottledTextureUploader); -public: - static PassOwnPtr<ThrottledTextureUploader> create(WebKit::WebGraphicsContext3D* context) - { - return adoptPtr(new ThrottledTextureUploader(context)); - } - static PassOwnPtr<ThrottledTextureUploader> create(WebKit::WebGraphicsContext3D* context, size_t pendingUploadLimit) - { - return adoptPtr(new ThrottledTextureUploader(context, pendingUploadLimit)); - } - virtual ~ThrottledTextureUploader(); - - virtual bool isBusy() OVERRIDE; - virtual void beginUploads() OVERRIDE; - virtual void endUploads() OVERRIDE; - virtual void uploadTexture(CCResourceProvider*, Parameters) OVERRIDE; - -private: - class Query { - public: - static PassOwnPtr<Query> create(WebKit::WebGraphicsContext3D* context) { return adoptPtr(new Query(context)); } - - virtual ~Query(); - - void begin(); - void end(); - bool isPending(); - void wait(); - - private: - explicit Query(WebKit::WebGraphicsContext3D*); - - WebKit::WebGraphicsContext3D* m_context; - unsigned m_queryId; - }; - - ThrottledTextureUploader(WebKit::WebGraphicsContext3D*); - ThrottledTextureUploader(WebKit::WebGraphicsContext3D*, size_t pendingUploadLimit); - - void processQueries(); - - WebKit::WebGraphicsContext3D* m_context; - size_t m_maxPendingQueries; - Deque<OwnPtr<Query> > m_pendingQueries; - Deque<OwnPtr<Query> > m_availableQueries; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/TiledLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/TiledLayerChromium.cpp deleted file mode 100644 index 5dc65ec5a..000000000 --- a/Source/WebCore/platform/graphics/chromium/TiledLayerChromium.cpp +++ /dev/null @@ -1,812 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "TiledLayerChromium.h" - -#include "CCLayerImpl.h" -#include "CCLayerTreeHost.h" -#include "CCOverdrawMetrics.h" -#include "CCTextureUpdateQueue.h" -#include "CCTiledLayerImpl.h" -#include "GraphicsContext3D.h" -#include "Region.h" -#include "TextStream.h" -#include <wtf/CurrentTime.h> -#include <wtf/MathExtras.h> - -using namespace std; -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -class UpdatableTile : public CCLayerTilingData::Tile { - WTF_MAKE_NONCOPYABLE(UpdatableTile); -public: - static PassOwnPtr<UpdatableTile> create(PassOwnPtr<LayerTextureUpdater::Texture> texture) - { - return adoptPtr(new UpdatableTile(texture)); - } - - LayerTextureUpdater::Texture* texture() { return m_texture.get(); } - CCPrioritizedTexture* managedTexture() { return m_texture->texture(); } - - bool isDirty() const { return !dirtyRect.isEmpty(); } - - // Reset update state for the current frame. This should occur before painting - // for all layers. Since painting one layer can invalidate another layer - // after it has already painted, mark all non-dirty tiles as valid before painting - // such that invalidations during painting won't prevent them from being pushed. - void resetUpdateState() - { - updateRect = IntRect(); - occluded = false; - partialUpdate = false; - validForFrame = !isDirty(); - } - - // This promises to update the tile and therefore also guarantees the tile - // will be valid for this frame. dirtyRect is copied into updateRect so - // we can continue to track re-entrant invalidations that occur during painting. - void markForUpdate() - { - validForFrame = true; - updateRect = dirtyRect; - dirtyRect = IntRect(); - } - - IntRect dirtyRect; - IntRect updateRect; - bool partialUpdate; - bool validForFrame; - bool occluded; - bool isInUseOnImpl; -private: - explicit UpdatableTile(PassOwnPtr<LayerTextureUpdater::Texture> texture) - : partialUpdate(false) - , validForFrame(false) - , occluded(false) - , isInUseOnImpl(false) - , m_texture(texture) - { - } - - OwnPtr<LayerTextureUpdater::Texture> m_texture; -}; - -TiledLayerChromium::TiledLayerChromium() - : LayerChromium() - , m_textureFormat(GraphicsContext3D::INVALID_ENUM) - , m_skipsDraw(false) - , m_failedUpdate(false) - , m_sampledTexelFormat(LayerTextureUpdater::SampledTexelFormatInvalid) - , m_tilingOption(AutoTile) -{ - m_tiler = CCLayerTilingData::create(IntSize(), CCLayerTilingData::HasBorderTexels); -} - -TiledLayerChromium::~TiledLayerChromium() -{ -} - -PassOwnPtr<CCLayerImpl> TiledLayerChromium::createCCLayerImpl() -{ - return CCTiledLayerImpl::create(id()); -} - -void TiledLayerChromium::updateTileSizeAndTilingOption() -{ - ASSERT(layerTreeHost()); - - const IntSize& defaultTileSize = layerTreeHost()->settings().defaultTileSize; - const IntSize& maxUntiledLayerSize = layerTreeHost()->settings().maxUntiledLayerSize; - int layerWidth = contentBounds().width(); - int layerHeight = contentBounds().height(); - - const IntSize tileSize(min(defaultTileSize.width(), layerWidth), min(defaultTileSize.height(), layerHeight)); - - // Tile if both dimensions large, or any one dimension large and the other - // extends into a second tile but the total layer area isn't larger than that - // of the largest possible untiled layer. This heuristic allows for long skinny layers - // (e.g. scrollbars) that are Nx1 tiles to minimize wasted texture space but still avoids - // creating very large tiles. - const bool anyDimensionLarge = layerWidth > maxUntiledLayerSize.width() || layerHeight > maxUntiledLayerSize.height(); - const bool anyDimensionOneTile = (layerWidth <= defaultTileSize.width() || layerHeight <= defaultTileSize.height()) - && (layerWidth * layerHeight) <= (maxUntiledLayerSize.width() * maxUntiledLayerSize.height()); - const bool autoTiled = anyDimensionLarge && !anyDimensionOneTile; - - bool isTiled; - if (m_tilingOption == AlwaysTile) - isTiled = true; - else if (m_tilingOption == NeverTile) - isTiled = false; - else - isTiled = autoTiled; - - IntSize requestedSize = isTiled ? tileSize : contentBounds(); - const int maxSize = layerTreeHost()->rendererCapabilities().maxTextureSize; - IntSize clampedSize = requestedSize.shrunkTo(IntSize(maxSize, maxSize)); - setTileSize(clampedSize); -} - -void TiledLayerChromium::updateBounds() -{ - IntSize oldBounds = m_tiler->bounds(); - IntSize newBounds = contentBounds(); - if (oldBounds == newBounds) - return; - m_tiler->setBounds(newBounds); - - // Invalidate any areas that the new bounds exposes. - Region oldRegion(IntRect(IntPoint(), oldBounds)); - Region newRegion(IntRect(IntPoint(), newBounds)); - newRegion.subtract(oldRegion); - Vector<IntRect> rects = newRegion.rects(); - for (size_t i = 0; i < rects.size(); ++i) - invalidateContentRect(rects[i]); -} - -void TiledLayerChromium::setTileSize(const IntSize& size) -{ - m_tiler->setTileSize(size); -} - -void TiledLayerChromium::setBorderTexelOption(CCLayerTilingData::BorderTexelOption borderTexelOption) -{ - m_tiler->setBorderTexelOption(borderTexelOption); -} - -bool TiledLayerChromium::drawsContent() const -{ - if (!LayerChromium::drawsContent()) - return false; - - bool hasMoreThanOneTile = m_tiler->numTilesX() > 1 || m_tiler->numTilesY() > 1; - if (m_tilingOption == NeverTile && hasMoreThanOneTile) - return false; - - return true; -} - -bool TiledLayerChromium::needsContentsScale() const -{ - return true; -} - -IntSize TiledLayerChromium::contentBounds() const -{ - return IntSize(lroundf(bounds().width() * contentsScale()), lroundf(bounds().height() * contentsScale())); -} - -void TiledLayerChromium::setTilingOption(TilingOption tilingOption) -{ - m_tilingOption = tilingOption; -} - -void TiledLayerChromium::setIsMask(bool isMask) -{ - setTilingOption(isMask ? NeverTile : AutoTile); -} - -void TiledLayerChromium::pushPropertiesTo(CCLayerImpl* layer) -{ - LayerChromium::pushPropertiesTo(layer); - - CCTiledLayerImpl* tiledLayer = static_cast<CCTiledLayerImpl*>(layer); - - tiledLayer->setSkipsDraw(m_skipsDraw); - tiledLayer->setContentsSwizzled(m_sampledTexelFormat != LayerTextureUpdater::SampledTexelFormatRGBA); - tiledLayer->setTilingData(*m_tiler); - Vector<UpdatableTile*> invalidTiles; - - for (CCLayerTilingData::TileMap::const_iterator iter = m_tiler->tiles().begin(); iter != m_tiler->tiles().end(); ++iter) { - int i = iter->first.first; - int j = iter->first.second; - UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second.get()); - // FIXME: This should not ever be null. - if (!tile) - continue; - tile->isInUseOnImpl = false; - if (!tile->managedTexture()->haveBackingTexture()) { - invalidTiles.append(tile); - continue; - } - if (!tile->validForFrame) - continue; - - tiledLayer->pushTileProperties(i, j, tile->managedTexture()->resourceId(), tile->opaqueRect()); - tile->isInUseOnImpl = true; - } - for (Vector<UpdatableTile*>::const_iterator iter = invalidTiles.begin(); iter != invalidTiles.end(); ++iter) - m_tiler->takeTile((*iter)->i(), (*iter)->j()); -} - -CCPrioritizedTextureManager* TiledLayerChromium::textureManager() const -{ - if (!layerTreeHost()) - return 0; - return layerTreeHost()->contentsTextureManager(); -} - -void TiledLayerChromium::setLayerTreeHost(CCLayerTreeHost* host) -{ - if (host && host != layerTreeHost()) { - for (CCLayerTilingData::TileMap::const_iterator iter = m_tiler->tiles().begin(); iter != m_tiler->tiles().end(); ++iter) { - UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second.get()); - // FIXME: This should not ever be null. - if (!tile) - continue; - tile->managedTexture()->setTextureManager(host->contentsTextureManager()); - } - } - LayerChromium::setLayerTreeHost(host); -} - -UpdatableTile* TiledLayerChromium::tileAt(int i, int j) const -{ - return static_cast<UpdatableTile*>(m_tiler->tileAt(i, j)); -} - -UpdatableTile* TiledLayerChromium::createTile(int i, int j) -{ - createTextureUpdaterIfNeeded(); - - OwnPtr<UpdatableTile> tile(UpdatableTile::create(textureUpdater()->createTexture(textureManager()))); - tile->managedTexture()->setDimensions(m_tiler->tileSize(), m_textureFormat); - - UpdatableTile* addedTile = tile.get(); - m_tiler->addTile(tile.release(), i, j); - - addedTile->dirtyRect = m_tiler->tileRect(addedTile); - - // Temporary diagnostic crash. - if (!addedTile) - CRASH(); - if (!tileAt(i, j)) - CRASH(); - - return addedTile; -} - -void TiledLayerChromium::setNeedsDisplayRect(const FloatRect& dirtyRect) -{ - float contentsWidthScale = static_cast<float>(contentBounds().width()) / bounds().width(); - float contentsHeightScale = static_cast<float>(contentBounds().height()) / bounds().height(); - FloatRect scaledDirtyRect(dirtyRect); - scaledDirtyRect.scale(contentsWidthScale, contentsHeightScale); - IntRect dirty = enclosingIntRect(scaledDirtyRect); - invalidateContentRect(dirty); - LayerChromium::setNeedsDisplayRect(dirtyRect); -} - -void TiledLayerChromium::setUseLCDText(bool useLCDText) -{ - LayerChromium::setUseLCDText(useLCDText); - - CCLayerTilingData::BorderTexelOption borderTexelOption; -#if OS(ANDROID) - // Always want border texels and GL_LINEAR due to pinch zoom. - borderTexelOption = CCLayerTilingData::HasBorderTexels; -#else - borderTexelOption = useLCDText ? CCLayerTilingData::NoBorderTexels : CCLayerTilingData::HasBorderTexels; -#endif - setBorderTexelOption(borderTexelOption); -} - -void TiledLayerChromium::invalidateContentRect(const IntRect& contentRect) -{ - updateBounds(); - if (m_tiler->isEmpty() || contentRect.isEmpty() || m_skipsDraw) - return; - - for (CCLayerTilingData::TileMap::const_iterator iter = m_tiler->tiles().begin(); iter != m_tiler->tiles().end(); ++iter) { - UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second.get()); - ASSERT(tile); - // FIXME: This should not ever be null. - if (!tile) - continue; - IntRect bound = m_tiler->tileRect(tile); - bound.intersect(contentRect); - tile->dirtyRect.unite(bound); - } -} - -// Returns true if tile is dirty and only part of it needs to be updated. -bool TiledLayerChromium::tileOnlyNeedsPartialUpdate(UpdatableTile* tile) -{ - return !tile->dirtyRect.contains(m_tiler->tileRect(tile)); -} - -// Dirty tiles with valid textures needs buffered update to guarantee that -// we don't modify textures currently used for drawing by the impl thread. -bool TiledLayerChromium::tileNeedsBufferedUpdate(UpdatableTile* tile) -{ - if (!tile->managedTexture()->haveBackingTexture()) - return false; - - if (!tile->isDirty()) - return false; - - if (!tile->isInUseOnImpl) - return false; - - return true; -} - - -bool TiledLayerChromium::updateTiles(int left, int top, int right, int bottom, CCTextureUpdateQueue& queue, const CCOcclusionTracker* occlusion, CCRenderingStats& stats, bool& didPaint) -{ - didPaint = false; - createTextureUpdaterIfNeeded(); - - bool ignoreOcclusions = !occlusion; - if (!haveTexturesForTiles(left, top, right, bottom, ignoreOcclusions)) { - m_failedUpdate = true; - return false; - } - - IntRect paintRect = markTilesForUpdate(left, top, right, bottom, ignoreOcclusions); - - if (occlusion) - occlusion->overdrawMetrics().didPaint(paintRect); - - if (paintRect.isEmpty()) - return true; - - didPaint = true; - updateTileTextures(paintRect, left, top, right, bottom, queue, occlusion, stats); - return true; -} - -void TiledLayerChromium::markOcclusionsAndRequestTextures(int left, int top, int right, int bottom, const CCOcclusionTracker* occlusion) -{ - // There is some difficult dependancies between occlusions, recording occlusion metrics - // and requesting memory so those are encapsulated in this function: - // - We only want to call requestLate on unoccluded textures (to preserve - // memory for other layers when near OOM). - // - We only want to record occlusion metrics if all memory requests succeed. - - int occludedTileCount = 0; - bool succeeded = true; - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - UpdatableTile* tile = tileAt(i, j); - ASSERT(tile); // Did setTexturePriorities get skipped? - // FIXME: This should not ever be null. - if (!tile) - continue; - ASSERT(!tile->occluded); // Did resetUpdateState get skipped? Are we doing more than one occlusion pass? - IntRect visibleTileRect = intersection(m_tiler->tileBounds(i, j), visibleContentRect()); - if (occlusion && occlusion->occluded(this, visibleTileRect)) { - tile->occluded = true; - occludedTileCount++; - } else { - succeeded &= tile->managedTexture()->requestLate(); - } - } - } - - if (!succeeded) - return; - - // FIXME: Remove the loop and just pass the count! - for (int i = 0; i < occludedTileCount; i++) - occlusion->overdrawMetrics().didCullTileForUpload(); -} - -bool TiledLayerChromium::haveTexturesForTiles(int left, int top, int right, int bottom, bool ignoreOcclusions) -{ - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - UpdatableTile* tile = tileAt(i, j); - ASSERT(tile); // Did setTexturePriorites get skipped? - // FIXME: This should not ever be null. - if (!tile) - continue; - - // Ensure the entire tile is dirty if we don't have the texture. - if (!tile->managedTexture()->haveBackingTexture()) - tile->dirtyRect = m_tiler->tileRect(tile); - - // If using occlusion and the visible region of the tile is occluded, - // don't reserve a texture or update the tile. - if (tile->occluded && !ignoreOcclusions) - continue; - - if (!tile->managedTexture()->canAcquireBackingTexture()) - return false; - } - } - return true; -} - -IntRect TiledLayerChromium::markTilesForUpdate(int left, int top, int right, int bottom, bool ignoreOcclusions) -{ - IntRect paintRect; - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - UpdatableTile* tile = tileAt(i, j); - ASSERT(tile); // Did setTexturePriorites get skipped? - // FIXME: This should not ever be null. - if (!tile) - continue; - if (tile->occluded && !ignoreOcclusions) - continue; - paintRect.unite(tile->dirtyRect); - tile->markForUpdate(); - } - } - return paintRect; -} - -void TiledLayerChromium::updateTileTextures(const IntRect& paintRect, int left, int top, int right, int bottom, CCTextureUpdateQueue& queue, const CCOcclusionTracker* occlusion, CCRenderingStats& stats) -{ - // The updateRect should be in layer space. So we have to convert the paintRect from content space to layer space. - m_updateRect = FloatRect(paintRect); - float widthScale = bounds().width() / static_cast<float>(contentBounds().width()); - float heightScale = bounds().height() / static_cast<float>(contentBounds().height()); - m_updateRect.scale(widthScale, heightScale); - - // Calling prepareToUpdate() calls into WebKit to paint, which may have the side - // effect of disabling compositing, which causes our reference to the texture updater to be deleted. - // However, we can't free the memory backing the SkCanvas until the paint finishes, - // so we grab a local reference here to hold the updater alive until the paint completes. - RefPtr<LayerTextureUpdater> protector(textureUpdater()); - IntRect paintedOpaqueRect; - textureUpdater()->prepareToUpdate(paintRect, m_tiler->tileSize(), 1 / widthScale, 1 / heightScale, paintedOpaqueRect, stats); - - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - UpdatableTile* tile = tileAt(i, j); - ASSERT(tile); // Did setTexturePriorites get skipped? - // FIXME: This should not ever be null. - if (!tile) - continue; - - IntRect tileRect = m_tiler->tileBounds(i, j); - - // Use updateRect as the above loop copied the dirty rect for this frame to updateRect. - const IntRect& dirtyRect = tile->updateRect; - if (dirtyRect.isEmpty()) - continue; - - // Save what was painted opaque in the tile. Keep the old area if the paint didn't touch it, and didn't paint some - // other part of the tile opaque. - IntRect tilePaintedRect = intersection(tileRect, paintRect); - IntRect tilePaintedOpaqueRect = intersection(tileRect, paintedOpaqueRect); - if (!tilePaintedRect.isEmpty()) { - IntRect paintInsideTileOpaqueRect = intersection(tile->opaqueRect(), tilePaintedRect); - bool paintInsideTileOpaqueRectIsNonOpaque = !tilePaintedOpaqueRect.contains(paintInsideTileOpaqueRect); - bool opaquePaintNotInsideTileOpaqueRect = !tilePaintedOpaqueRect.isEmpty() && !tile->opaqueRect().contains(tilePaintedOpaqueRect); - - if (paintInsideTileOpaqueRectIsNonOpaque || opaquePaintNotInsideTileOpaqueRect) - tile->setOpaqueRect(tilePaintedOpaqueRect); - } - - // sourceRect starts as a full-sized tile with border texels included. - IntRect sourceRect = m_tiler->tileRect(tile); - sourceRect.intersect(dirtyRect); - // Paint rect not guaranteed to line up on tile boundaries, so - // make sure that sourceRect doesn't extend outside of it. - sourceRect.intersect(paintRect); - - tile->updateRect = sourceRect; - - if (sourceRect.isEmpty()) - continue; - - tile->texture()->prepareRect(sourceRect, stats); - if (occlusion) - occlusion->overdrawMetrics().didUpload(WebTransformationMatrix(), sourceRect, tile->opaqueRect()); - - const IntPoint anchor = m_tiler->tileRect(tile).location(); - - // Calculate tile-space rectangle to upload into. - IntSize destOffset(sourceRect.x() - anchor.x(), sourceRect.y() - anchor.y()); - if (destOffset.width() < 0) - CRASH(); - if (destOffset.height() < 0) - CRASH(); - - // Offset from paint rectangle to this tile's dirty rectangle. - IntPoint paintOffset(sourceRect.x() - paintRect.x(), sourceRect.y() - paintRect.y()); - if (paintOffset.x() < 0) - CRASH(); - if (paintOffset.y() < 0) - CRASH(); - if (paintOffset.x() + sourceRect.width() > paintRect.width()) - CRASH(); - if (paintOffset.y() + sourceRect.height() > paintRect.height()) - CRASH(); - - TextureUploader::Parameters upload = { tile->texture(), sourceRect, destOffset }; - if (tile->partialUpdate) - queue.appendPartialUpload(upload); - else - queue.appendFullUpload(upload); - } - } -} - -namespace { -// This picks a small animated layer to be anything less than one viewport. This -// is specifically for page transitions which are viewport-sized layers. The extra -// 64 pixels is due to these layers being slightly larger than the viewport in some cases. -bool isSmallAnimatedLayer(TiledLayerChromium* layer) -{ - if (!layer->drawTransformIsAnimating() && !layer->screenSpaceTransformIsAnimating()) - return false; - IntSize viewportSize = layer->layerTreeHost() ? layer->layerTreeHost()->deviceViewportSize() : IntSize(); - IntRect contentRect(IntPoint::zero(), layer->contentBounds()); - return contentRect.width() <= viewportSize.width() + 64 - && contentRect.height() <= viewportSize.height() + 64; -} - -// FIXME: Remove this and make this based on distance once distance can be calculated -// for offscreen layers. For now, prioritize all small animated layers after 512 -// pixels of pre-painting. -void setPriorityForTexture(const CCPriorityCalculator& priorityCalc, - const IntRect& visibleRect, - const IntRect& tileRect, - bool drawsToRoot, - bool isSmallAnimatedLayer, - CCPrioritizedTexture* texture) -{ - int priority = CCPriorityCalculator::lowestPriority(); - if (!visibleRect.isEmpty()) - priority = priorityCalc.priorityFromDistance(visibleRect, tileRect, drawsToRoot); - if (isSmallAnimatedLayer) - priority = CCPriorityCalculator::maxPriority(priority, priorityCalc.priorityFromDistance(512, drawsToRoot)); - if (priority != CCPriorityCalculator::lowestPriority()) - texture->setRequestPriority(priority); -} -} - -void TiledLayerChromium::setTexturePriorities(const CCPriorityCalculator& priorityCalc) -{ - updateBounds(); - resetUpdateState(); - - if (m_tiler->hasEmptyBounds()) - return; - - bool drawsToRoot = !renderTarget()->parent(); - bool smallAnimatedLayer = isSmallAnimatedLayer(this); - - // Minimally create the tiles in the desired pre-paint rect. - IntRect createTilesRect = idlePaintRect(); - if (!createTilesRect.isEmpty()) { - int left, top, right, bottom; - m_tiler->contentRectToTileIndices(createTilesRect, left, top, right, bottom); - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - if (!tileAt(i, j)) - createTile(i, j); - } - } - } - - // Also, minimally create all tiles for small animated layers and also - // double-buffer them since we have limited their size to be reasonable. - IntRect doubleBufferedRect = visibleContentRect(); - if (smallAnimatedLayer) - doubleBufferedRect = IntRect(IntPoint::zero(), contentBounds()); - - // Create additional textures for double-buffered updates when needed. - // These textures must stay alive while the updated textures are incrementally - // uploaded, swapped atomically via pushProperties, and finally deleted - // after the commit is complete, after which they can be recycled. - if (!doubleBufferedRect.isEmpty()) { - int left, top, right, bottom; - m_tiler->contentRectToTileIndices(doubleBufferedRect, left, top, right, bottom); - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - UpdatableTile* tile = tileAt(i, j); - if (!tile) - tile = createTile(i, j); - // We need an additional texture if the tile needs a buffered-update and it's not a partial update. - // FIXME: Decide if partial update should be allowed based on cost - // of update. https://bugs.webkit.org/show_bug.cgi?id=77376 - if (!layerTreeHost() || !layerTreeHost()->bufferedUpdates() || !tileNeedsBufferedUpdate(tile)) - continue; - if (tileOnlyNeedsPartialUpdate(tile) && layerTreeHost()->requestPartialTextureUpdate()) { - tile->partialUpdate = true; - continue; - } - - IntRect tileRect = m_tiler->tileRect(tile); - tile->dirtyRect = tileRect; - LayerTextureUpdater::Texture* backBuffer = tile->texture(); - setPriorityForTexture(priorityCalc, visibleContentRect(), tile->dirtyRect, drawsToRoot, smallAnimatedLayer, backBuffer->texture()); - OwnPtr<CCPrioritizedTexture> frontBuffer = CCPrioritizedTexture::create(backBuffer->texture()->textureManager(), - backBuffer->texture()->size(), - backBuffer->texture()->format()); - // Swap backBuffer into frontBuffer and add it to delete after commit queue. - backBuffer->swapTextureWith(frontBuffer); - layerTreeHost()->deleteTextureAfterCommit(frontBuffer.release()); - } - } - } - - // Now update priorities on all tiles we have in the layer, no matter where they are. - for (CCLayerTilingData::TileMap::const_iterator iter = m_tiler->tiles().begin(); iter != m_tiler->tiles().end(); ++iter) { - UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second.get()); - // FIXME: This should not ever be null. - if (!tile) - continue; - IntRect tileRect = m_tiler->tileRect(tile); - setPriorityForTexture(priorityCalc, visibleContentRect(), tileRect, drawsToRoot, smallAnimatedLayer, tile->managedTexture()); - } -} - -Region TiledLayerChromium::visibleContentOpaqueRegion() const -{ - if (m_skipsDraw) - return Region(); - if (opaque()) - return visibleContentRect(); - return m_tiler->opaqueRegionInContentRect(visibleContentRect()); -} - -void TiledLayerChromium::resetUpdateState() -{ - m_skipsDraw = false; - m_failedUpdate = false; - - CCLayerTilingData::TileMap::const_iterator end = m_tiler->tiles().end(); - for (CCLayerTilingData::TileMap::const_iterator iter = m_tiler->tiles().begin(); iter != end; ++iter) { - UpdatableTile* tile = static_cast<UpdatableTile*>(iter->second.get()); - // FIXME: This should not ever be null. - if (!tile) - continue; - tile->resetUpdateState(); - } -} - -void TiledLayerChromium::update(CCTextureUpdateQueue& queue, const CCOcclusionTracker* occlusion, CCRenderingStats& stats) -{ - ASSERT(!m_skipsDraw && !m_failedUpdate); // Did resetUpdateState get skipped? - updateBounds(); - if (m_tiler->hasEmptyBounds() || !drawsContent()) - return; - - bool didPaint = false; - - // Animation pre-paint. If the layer is small, try to paint it all - // immediately whether or not it is occluded, to avoid paint/upload - // hiccups while it is animating. - if (isSmallAnimatedLayer(this)) { - int left, top, right, bottom; - m_tiler->contentRectToTileIndices(IntRect(IntPoint::zero(), contentBounds()), left, top, right, bottom); - updateTiles(left, top, right, bottom, queue, 0, stats, didPaint); - if (didPaint) - return; - // This was an attempt to paint the entire layer so if we fail it's okay, - // just fallback on painting visible etc. below. - m_failedUpdate = false; - } - - if (visibleContentRect().isEmpty()) - return; - - // Visible painting. First occlude visible tiles and paint the non-occluded tiles. - int left, top, right, bottom; - m_tiler->contentRectToTileIndices(visibleContentRect(), left, top, right, bottom); - markOcclusionsAndRequestTextures(left, top, right, bottom, occlusion); - m_skipsDraw = !updateTiles(left, top, right, bottom, queue, occlusion, stats, didPaint); - if (m_skipsDraw) - m_tiler->reset(); - if (m_skipsDraw || didPaint) - return; - - // If we have already painting everything visible. Do some pre-painting while idle. - IntRect idlePaintContentRect = idlePaintRect(); - if (idlePaintContentRect.isEmpty()) - return; - - // Prepaint anything that was occluded but inside the layer's visible region. - if (!updateTiles(left, top, right, bottom, queue, 0, stats, didPaint) || didPaint) - return; - - int prepaintLeft, prepaintTop, prepaintRight, prepaintBottom; - m_tiler->contentRectToTileIndices(idlePaintContentRect, prepaintLeft, prepaintTop, prepaintRight, prepaintBottom); - - // Then expand outwards from the visible area until we find a dirty row or column to update. - while (left > prepaintLeft || top > prepaintTop || right < prepaintRight || bottom < prepaintBottom) { - if (bottom < prepaintBottom) { - ++bottom; - if (!updateTiles(left, bottom, right, bottom, queue, 0, stats, didPaint) || didPaint) - return; - } - if (top > prepaintTop) { - --top; - if (!updateTiles(left, top, right, top, queue, 0, stats, didPaint) || didPaint) - return; - } - if (left > prepaintLeft) { - --left; - if (!updateTiles(left, top, left, bottom, queue, 0, stats, didPaint) || didPaint) - return; - } - if (right < prepaintRight) { - ++right; - if (!updateTiles(right, top, right, bottom, queue, 0, stats, didPaint) || didPaint) - return; - } - } -} - -bool TiledLayerChromium::needsIdlePaint() -{ - // Don't trigger more paints if we failed (as we'll just fail again). - if (m_failedUpdate || visibleContentRect().isEmpty() || m_tiler->hasEmptyBounds() || !drawsContent()) - return false; - - IntRect idlePaintContentRect = idlePaintRect(); - if (idlePaintContentRect.isEmpty()) - return false; - - int left, top, right, bottom; - m_tiler->contentRectToTileIndices(idlePaintContentRect, left, top, right, bottom); - - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - UpdatableTile* tile = tileAt(i, j); - ASSERT(tile); // Did setTexturePriorities get skipped? - if (!tile) - continue; - - bool updated = !tile->updateRect.isEmpty(); - bool canAcquire = tile->managedTexture()->canAcquireBackingTexture(); - bool dirty = tile->isDirty() || !tile->managedTexture()->haveBackingTexture(); - if (!updated && canAcquire && dirty) - return true; - } - } - return false; -} - -IntRect TiledLayerChromium::idlePaintRect() -{ - // Don't inflate an empty rect. - if (visibleContentRect().isEmpty()) - return IntRect(); - - // FIXME: This can be made a lot larger now! We should increase - // this slowly while insuring it doesn't cause any perf issues. - IntRect prepaintRect = visibleContentRect(); - prepaintRect.inflateX(m_tiler->tileSize().width()); - prepaintRect.inflateY(m_tiler->tileSize().height() * 2); - IntRect contentRect(IntPoint::zero(), contentBounds()); - prepaintRect.intersect(contentRect); - - return prepaintRect; -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/TiledLayerChromium.h b/Source/WebCore/platform/graphics/chromium/TiledLayerChromium.h deleted file mode 100644 index 2abc11298..000000000 --- a/Source/WebCore/platform/graphics/chromium/TiledLayerChromium.h +++ /dev/null @@ -1,127 +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 TiledLayerChromium_h -#define TiledLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCLayerTilingData.h" -#include "LayerChromium.h" -#include "LayerTextureUpdater.h" - -namespace WebCore { -class UpdatableTile; - -class TiledLayerChromium : public LayerChromium { -public: - enum TilingOption { AlwaysTile, NeverTile, AutoTile }; - - virtual ~TiledLayerChromium(); - - virtual void setIsMask(bool) OVERRIDE; - - virtual void pushPropertiesTo(CCLayerImpl*) OVERRIDE; - - virtual bool drawsContent() const OVERRIDE; - virtual bool needsContentsScale() const OVERRIDE; - - virtual IntSize contentBounds() const OVERRIDE; - - virtual void setNeedsDisplayRect(const FloatRect&) OVERRIDE; - - virtual void setUseLCDText(bool) OVERRIDE; - - virtual void setLayerTreeHost(CCLayerTreeHost*) OVERRIDE; - - virtual void setTexturePriorities(const CCPriorityCalculator&) OVERRIDE; - - virtual Region visibleContentOpaqueRegion() const OVERRIDE; - - virtual void update(CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&) OVERRIDE; - -protected: - TiledLayerChromium(); - - void updateTileSizeAndTilingOption(); - void updateBounds(); - - // Exposed to subclasses for testing. - void setTileSize(const IntSize&); - void setTextureFormat(GC3Denum textureFormat) { m_textureFormat = textureFormat; } - void setBorderTexelOption(CCLayerTilingData::BorderTexelOption); - void setSampledTexelFormat(LayerTextureUpdater::SampledTexelFormat sampledTexelFormat) { m_sampledTexelFormat = sampledTexelFormat; } - size_t numPaintedTiles() { return m_tiler->tiles().size(); } - - virtual LayerTextureUpdater* textureUpdater() const = 0; - virtual void createTextureUpdaterIfNeeded() = 0; - - // Set invalidations to be potentially repainted during update(). - void invalidateContentRect(const IntRect& contentRect); - - // Reset state on tiles that will be used for updating the layer. - void resetUpdateState(); - - // After preparing an update, returns true if more painting is needed. - bool needsIdlePaint(); - IntRect idlePaintRect(); - - bool skipsDraw() const { return m_skipsDraw; } - - // Virtual for testing - virtual CCPrioritizedTextureManager* textureManager() const; - -private: - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl() OVERRIDE; - - void createTilerIfNeeded(); - void setTilingOption(TilingOption); - - bool tileOnlyNeedsPartialUpdate(UpdatableTile*); - bool tileNeedsBufferedUpdate(UpdatableTile*); - - void markOcclusionsAndRequestTextures(int left, int top, int right, int bottom, const CCOcclusionTracker*); - - bool updateTiles(int left, int top, int right, int bottom, CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&, bool& didPaint); - bool haveTexturesForTiles(int left, int top, int right, int bottom, bool ignoreOcclusions); - IntRect markTilesForUpdate(int left, int top, int right, int bottom, bool ignoreOcclusions); - void updateTileTextures(const IntRect& paintRect, int left, int top, int right, int bottom, CCTextureUpdateQueue&, const CCOcclusionTracker*, CCRenderingStats&); - - UpdatableTile* tileAt(int, int) const; - UpdatableTile* createTile(int, int); - - GC3Denum m_textureFormat; - bool m_skipsDraw; - bool m_failedUpdate; - LayerTextureUpdater::SampledTexelFormat m_sampledTexelFormat; - - TilingOption m_tilingOption; - OwnPtr<CCLayerTilingData> m_tiler; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/TreeSynchronizer.cpp b/Source/WebCore/platform/graphics/chromium/TreeSynchronizer.cpp deleted file mode 100644 index 247d0c4d9..000000000 --- a/Source/WebCore/platform/graphics/chromium/TreeSynchronizer.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 "TreeSynchronizer.h" - -#include "CCLayerImpl.h" -#include "CCScrollbarAnimationController.h" -#include "CCScrollbarLayerImpl.h" -#include "LayerChromium.h" -#include "ScrollbarLayerChromium.h" -#include <wtf/RefPtr.h> - -namespace WebCore { - -PassOwnPtr<CCLayerImpl> TreeSynchronizer::synchronizeTrees(LayerChromium* layerChromiumRoot, PassOwnPtr<CCLayerImpl> oldCCLayerImplRoot, CCLayerTreeHostImpl* hostImpl) -{ - OwnPtrCCLayerImplMap oldLayers; - RawPtrCCLayerImplMap newLayers; - - collectExistingCCLayerImplRecursive(oldLayers, oldCCLayerImplRoot); - - OwnPtr<CCLayerImpl> newTree = synchronizeTreeRecursive(newLayers, oldLayers, layerChromiumRoot, hostImpl); - - updateScrollbarLayerPointersRecursive(newLayers, layerChromiumRoot); - - return newTree.release(); -} - -void TreeSynchronizer::collectExistingCCLayerImplRecursive(OwnPtrCCLayerImplMap& oldLayers, PassOwnPtr<CCLayerImpl> popCCLayerImpl) -{ - OwnPtr<CCLayerImpl> ccLayerImpl = popCCLayerImpl; - - if (!ccLayerImpl) - return; - - Vector<OwnPtr<CCLayerImpl> >& children = ccLayerImpl->m_children; - for (size_t i = 0; i < children.size(); ++i) - collectExistingCCLayerImplRecursive(oldLayers, children[i].release()); - - collectExistingCCLayerImplRecursive(oldLayers, ccLayerImpl->m_maskLayer.release()); - collectExistingCCLayerImplRecursive(oldLayers, ccLayerImpl->m_replicaLayer.release()); - - int id = ccLayerImpl->id(); - oldLayers.set(id, ccLayerImpl.release()); -} - -PassOwnPtr<CCLayerImpl> TreeSynchronizer::reuseOrCreateCCLayerImpl(RawPtrCCLayerImplMap& newLayers, OwnPtrCCLayerImplMap& oldLayers, LayerChromium* layer) -{ - OwnPtr<CCLayerImpl> ccLayerImpl = oldLayers.take(layer->id()); - - if (!ccLayerImpl) - ccLayerImpl = layer->createCCLayerImpl(); - - newLayers.set(layer->id(), ccLayerImpl.get()); - return ccLayerImpl.release(); -} - -PassOwnPtr<CCLayerImpl> TreeSynchronizer::synchronizeTreeRecursive(RawPtrCCLayerImplMap& newLayers, OwnPtrCCLayerImplMap& oldLayers, LayerChromium* layer, CCLayerTreeHostImpl* hostImpl) -{ - if (!layer) - return nullptr; - - OwnPtr<CCLayerImpl> ccLayerImpl = reuseOrCreateCCLayerImpl(newLayers, oldLayers, layer); - - ccLayerImpl->clearChildList(); - const Vector<RefPtr<LayerChromium> >& children = layer->children(); - for (size_t i = 0; i < children.size(); ++i) - ccLayerImpl->addChild(synchronizeTreeRecursive(newLayers, oldLayers, children[i].get(), hostImpl)); - - ccLayerImpl->setMaskLayer(synchronizeTreeRecursive(newLayers, oldLayers, layer->maskLayer(), hostImpl)); - ccLayerImpl->setReplicaLayer(synchronizeTreeRecursive(newLayers, oldLayers, layer->replicaLayer(), hostImpl)); - - layer->pushPropertiesTo(ccLayerImpl.get()); - ccLayerImpl->setLayerTreeHostImpl(hostImpl); - - // Remove all dangling pointers. The pointers will be setup later in updateScrollbarLayerPointersRecursive phase - if (CCScrollbarAnimationController* scrollbarController = ccLayerImpl->scrollbarAnimationController()) { - scrollbarController->setHorizontalScrollbarLayer(0); - scrollbarController->setVerticalScrollbarLayer(0); - } - - return ccLayerImpl.release(); -} - -void TreeSynchronizer::updateScrollbarLayerPointersRecursive(const RawPtrCCLayerImplMap& newLayers, LayerChromium* layer) -{ - if (!layer) - return; - - const Vector<RefPtr<LayerChromium> >& children = layer->children(); - for (size_t i = 0; i < children.size(); ++i) - updateScrollbarLayerPointersRecursive(newLayers, children[i].get()); - - ScrollbarLayerChromium* scrollbarLayer = layer->toScrollbarLayerChromium(); - if (!scrollbarLayer) - return; - - CCScrollbarLayerImpl* ccScrollbarLayerImpl = static_cast<CCScrollbarLayerImpl*>(newLayers.get(scrollbarLayer->id())); - ASSERT(ccScrollbarLayerImpl); - CCLayerImpl* ccScrollLayerImpl = newLayers.get(scrollbarLayer->scrollLayerId()); - ASSERT(ccScrollLayerImpl); - - if (ccScrollbarLayerImpl->orientation() == WebKit::WebScrollbar::Horizontal) - ccScrollLayerImpl->setHorizontalScrollbarLayer(ccScrollbarLayerImpl); - else - ccScrollLayerImpl->setVerticalScrollbarLayer(ccScrollbarLayerImpl); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/TreeSynchronizer.h b/Source/WebCore/platform/graphics/chromium/TreeSynchronizer.h deleted file mode 100644 index d5289d887..000000000 --- a/Source/WebCore/platform/graphics/chromium/TreeSynchronizer.h +++ /dev/null @@ -1,62 +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 TreeSynchronizer_h -#define TreeSynchronizer_h - -#include <wtf/HashMap.h> -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCLayerImpl; -class CCLayerTreeHostImpl; -class LayerChromium; - -class TreeSynchronizer { -WTF_MAKE_NONCOPYABLE(TreeSynchronizer); -public: - // Accepts a LayerChromium tree and returns a reference to a CCLayerImpl tree that duplicates the structure - // of the LayerChromium tree, reusing the CCLayerImpls in the tree provided by oldCCLayerImplRoot if possible. - static PassOwnPtr<CCLayerImpl> synchronizeTrees(LayerChromium* layerRoot, PassOwnPtr<CCLayerImpl> oldCCLayerImplRoot, CCLayerTreeHostImpl*); - -private: - TreeSynchronizer(); // Not instantiable. - - typedef HashMap<int, OwnPtr<CCLayerImpl> > OwnPtrCCLayerImplMap; - typedef HashMap<int, CCLayerImpl*> RawPtrCCLayerImplMap; - - // Declared as static member functions so they can access functions on LayerChromium as a friend class. - static PassOwnPtr<CCLayerImpl> reuseOrCreateCCLayerImpl(RawPtrCCLayerImplMap& newLayers, OwnPtrCCLayerImplMap& oldLayers, LayerChromium*); - static void collectExistingCCLayerImplRecursive(OwnPtrCCLayerImplMap& oldLayers, PassOwnPtr<CCLayerImpl>); - static PassOwnPtr<CCLayerImpl> synchronizeTreeRecursive(RawPtrCCLayerImplMap& newLayers, OwnPtrCCLayerImplMap& oldLayers, LayerChromium*, CCLayerTreeHostImpl*); - static void updateScrollbarLayerPointersRecursive(const RawPtrCCLayerImplMap& newLayers, LayerChromium*); -}; - -} // namespace WebCore - -#endif // TreeSynchronizer_h diff --git a/Source/WebCore/platform/graphics/chromium/UnthrottledTextureUploader.h b/Source/WebCore/platform/graphics/chromium/UnthrottledTextureUploader.h deleted file mode 100644 index fa96899b6..000000000 --- a/Source/WebCore/platform/graphics/chromium/UnthrottledTextureUploader.h +++ /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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 UnthrottledTextureUploader_h -#define UnthrottledTextureUploader_h - -#include "CCResourceProvider.h" -#include "TextureUploader.h" - -namespace WebCore { - -class UnthrottledTextureUploader : public TextureUploader { - WTF_MAKE_NONCOPYABLE(UnthrottledTextureUploader); -public: - static PassOwnPtr<UnthrottledTextureUploader> create() - { - return adoptPtr(new UnthrottledTextureUploader()); - } - virtual ~UnthrottledTextureUploader() { } - - virtual bool isBusy() OVERRIDE { return false; } - virtual void beginUploads() OVERRIDE { } - virtual void endUploads() OVERRIDE { } - virtual void uploadTexture(CCResourceProvider* resourceProvider, Parameters upload) OVERRIDE { upload.texture->updateRect(resourceProvider, upload.sourceRect, upload.destOffset); } - -protected: - UnthrottledTextureUploader() { } -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/VideoLayerChromium.cpp b/Source/WebCore/platform/graphics/chromium/VideoLayerChromium.cpp deleted file mode 100644 index 62337d3da..000000000 --- a/Source/WebCore/platform/graphics/chromium/VideoLayerChromium.cpp +++ /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. - */ - -#include "config.h" - -#if USE(ACCELERATED_COMPOSITING) -#include "VideoLayerChromium.h" - -#include "CCVideoLayerImpl.h" - -namespace WebCore { - -PassRefPtr<VideoLayerChromium> VideoLayerChromium::create(WebKit::WebVideoFrameProvider* provider) -{ - return adoptRef(new VideoLayerChromium(provider)); -} - -VideoLayerChromium::VideoLayerChromium(WebKit::WebVideoFrameProvider* provider) - : LayerChromium() - , m_provider(provider) -{ - ASSERT(m_provider); -} - -VideoLayerChromium::~VideoLayerChromium() -{ -} - -PassOwnPtr<CCLayerImpl> VideoLayerChromium::createCCLayerImpl() -{ - return CCVideoLayerImpl::create(m_layerId, m_provider); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/VideoLayerChromium.h b/Source/WebCore/platform/graphics/chromium/VideoLayerChromium.h deleted file mode 100644 index dc4559cf8..000000000 --- a/Source/WebCore/platform/graphics/chromium/VideoLayerChromium.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 VideoLayerChromium_h -#define VideoLayerChromium_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "LayerChromium.h" - -namespace WebKit { -class WebVideoFrameProvider; -} - -namespace WebCore { - -class CCVideoLayerImpl; - -// A Layer that contains a Video element. -class VideoLayerChromium : public LayerChromium { -public: - - static PassRefPtr<VideoLayerChromium> create(WebKit::WebVideoFrameProvider*); - virtual ~VideoLayerChromium(); - - virtual PassOwnPtr<CCLayerImpl> createCCLayerImpl() OVERRIDE; - -private: - explicit VideoLayerChromium(WebKit::WebVideoFrameProvider*); - - // This pointer is only for passing to CCVideoLayerImpl's constructor. It should never be dereferenced by this class. - WebKit::WebVideoFrameProvider* m_provider; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCActiveAnimation.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCActiveAnimation.cpp deleted file mode 100644 index 68fe45a73..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCActiveAnimation.cpp +++ /dev/null @@ -1,227 +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 "CCActiveAnimation.h" - -#include "CCAnimationCurve.h" -#include "TraceEvent.h" -#include <cmath> -#include <wtf/Assertions.h> -#include <wtf/StdLibExtras.h> -#include <wtf/StringExtras.h> - -namespace { - -// This should match the RunState enum. -static const char* const s_runStateNames[] = { - "WaitingForNextTick", - "WaitingForTargetAvailability", - "WaitingForStartTime", - "WaitingForDeletion", - "Running", - "Paused", - "Finished", - "Aborted" -}; - -COMPILE_ASSERT(static_cast<int>(WebCore::CCActiveAnimation::RunStateEnumSize) == WTF_ARRAY_LENGTH(s_runStateNames), RunState_names_match_enum); - -// This should match the TargetProperty enum. -static const char* const s_targetPropertyNames[] = { - "Transform", - "Opacity" -}; - -COMPILE_ASSERT(static_cast<int>(WebCore::CCActiveAnimation::TargetPropertyEnumSize) == WTF_ARRAY_LENGTH(s_targetPropertyNames), TargetProperty_names_match_enum); - -} // namespace - -namespace WebCore { - -PassOwnPtr<CCActiveAnimation> CCActiveAnimation::create(PassOwnPtr<CCAnimationCurve> curve, int animationId, int groupId, TargetProperty targetProperty) -{ - return adoptPtr(new CCActiveAnimation(curve, animationId, groupId, targetProperty)); -} - -CCActiveAnimation::CCActiveAnimation(PassOwnPtr<CCAnimationCurve> curve, int animationId, int groupId, TargetProperty targetProperty) - : m_curve(curve) - , m_id(animationId) - , m_group(groupId) - , m_targetProperty(targetProperty) - , m_runState(WaitingForTargetAvailability) - , m_iterations(1) - , m_startTime(0) - , m_alternatesDirection(false) - , m_timeOffset(0) - , m_needsSynchronizedStartTime(false) - , m_suspended(false) - , m_pauseTime(0) - , m_totalPausedTime(0) - , m_isControllingInstance(false) -{ -} - -CCActiveAnimation::~CCActiveAnimation() -{ - if (m_runState == Running || m_runState == Paused) - setRunState(Aborted, 0); -} - -void CCActiveAnimation::setRunState(RunState runState, double monotonicTime) -{ - if (m_suspended) - return; - - char nameBuffer[256]; - snprintf(nameBuffer, sizeof(nameBuffer), "%s-%d%s", s_targetPropertyNames[m_targetProperty], m_group, m_isControllingInstance ? "(impl)" : ""); - - bool isWaitingToStart = m_runState == WaitingForNextTick - || m_runState == WaitingForTargetAvailability - || m_runState == WaitingForStartTime; - - if (isWaitingToStart && runState == Running) - TRACE_EVENT_ASYNC_BEGIN1("cc", "CCActiveAnimation", this, "Name", TRACE_STR_COPY(nameBuffer)); - - bool wasFinished = isFinished(); - - const char* oldRunStateName = s_runStateNames[m_runState]; - - if (runState == Running && m_runState == Paused) - m_totalPausedTime += monotonicTime - m_pauseTime; - else if (runState == Paused) - m_pauseTime = monotonicTime; - m_runState = runState; - - const char* newRunStateName = s_runStateNames[runState]; - - if (!wasFinished && isFinished()) - TRACE_EVENT_ASYNC_END0("cc", "CCActiveAnimation", this); - - char stateBuffer[256]; - snprintf(stateBuffer, sizeof(stateBuffer), "%s->%s", oldRunStateName, newRunStateName); - - TRACE_EVENT_INSTANT2("cc", "CCLayerAnimationController::setRunState", "Name", TRACE_STR_COPY(nameBuffer), "State", TRACE_STR_COPY(stateBuffer)); -} - -void CCActiveAnimation::suspend(double monotonicTime) -{ - setRunState(Paused, monotonicTime); - m_suspended = true; -} - -void CCActiveAnimation::resume(double monotonicTime) -{ - m_suspended = false; - setRunState(Running, monotonicTime); -} - -bool CCActiveAnimation::isFinishedAt(double monotonicTime) const -{ - if (isFinished()) - return true; - - if (m_needsSynchronizedStartTime) - return false; - - return m_runState == Running - && m_iterations >= 0 - && m_iterations * m_curve->duration() <= monotonicTime - startTime() - m_totalPausedTime; -} - -double CCActiveAnimation::trimTimeToCurrentIteration(double monotonicTime) const -{ - double trimmed = monotonicTime + m_timeOffset; - - // If we're paused, time is 'stuck' at the pause time. - if (m_runState == Paused) - trimmed = m_pauseTime; - - // Returned time should always be relative to the start time and should subtract - // all time spent paused. - trimmed -= m_startTime + m_totalPausedTime; - - // Zero is always the start of the animation. - if (trimmed <= 0) - return 0; - - // Always return zero if we have no iterations. - if (!m_iterations) - return 0; - - // If less than an iteration duration, just return trimmed. - if (trimmed < m_curve->duration()) - return trimmed; - - // If greater than or equal to the total duration, return iteration duration. - if (m_iterations >= 0 && trimmed >= m_curve->duration() * m_iterations) { - if (m_alternatesDirection && !(m_iterations % 2)) - return 0; - return m_curve->duration(); - } - - // We need to know the current iteration if we're alternating. - int iteration = static_cast<int>(trimmed / m_curve->duration()); - - // Calculate x where trimmed = x + n * m_curve->duration() for some positive integer n. - trimmed = fmod(trimmed, m_curve->duration()); - - // If we're alternating and on an odd iteration, reverse the direction. - if (m_alternatesDirection && iteration % 2 == 1) - return m_curve->duration() - trimmed; - - return trimmed; -} - -PassOwnPtr<CCActiveAnimation> CCActiveAnimation::clone(InstanceType instanceType) const -{ - return cloneAndInitialize(instanceType, m_runState, m_startTime); -} - -PassOwnPtr<CCActiveAnimation> CCActiveAnimation::cloneAndInitialize(InstanceType instanceType, RunState initialRunState, double startTime) const -{ - OwnPtr<CCActiveAnimation> toReturn(adoptPtr(new CCActiveAnimation(m_curve->clone(), m_id, m_group, m_targetProperty))); - toReturn->m_runState = initialRunState; - toReturn->m_iterations = m_iterations; - toReturn->m_startTime = startTime; - toReturn->m_pauseTime = m_pauseTime; - toReturn->m_totalPausedTime = m_totalPausedTime; - toReturn->m_timeOffset = m_timeOffset; - toReturn->m_alternatesDirection = m_alternatesDirection; - toReturn->m_isControllingInstance = instanceType == ControllingInstance; - return toReturn.release(); -} - -void CCActiveAnimation::pushPropertiesTo(CCActiveAnimation* other) const -{ - // Currently, we only push changes due to pausing and resuming animations on the main thread. - if (m_runState == CCActiveAnimation::Paused || other->m_runState == CCActiveAnimation::Paused) { - other->m_runState = m_runState; - other->m_pauseTime = m_pauseTime; - other->m_totalPausedTime = m_totalPausedTime; - } -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCActiveAnimation.h b/Source/WebCore/platform/graphics/chromium/cc/CCActiveAnimation.h deleted file mode 100644 index ea4e34f2e..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCActiveAnimation.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCActiveAnimation_h -#define CCActiveAnimation_h - -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCAnimationCurve; - -// A CCActiveAnimation, contains all the state required to play a CCAnimationCurve. -// Specifically, the affected property, the run state (paused, finished, etc.), -// loop count, last pause time, and the total time spent paused. -class CCActiveAnimation { - WTF_MAKE_NONCOPYABLE(CCActiveAnimation); -public: - // Animations begin in one of the 'waiting' states. Animations waiting for the next tick - // will start the next time the controller animates. Animations waiting for target - // availibility will run as soon as their target property is free (and all the animations - // animating with it are also able to run). Animations waiting for their start time to - // come have be scheduled to run at a particular point in time. When this time arrives, - // the controller will move the animations into the Running state. Running animations - // may toggle between Running and Paused, and may be stopped by moving into either the - // Aborted or Finished states. A Finished animation was allowed to run to completion, but - // an Aborted animation was not. - enum RunState { - WaitingForNextTick = 0, - WaitingForTargetAvailability, - WaitingForStartTime, - WaitingForDeletion, - Running, - Paused, - Finished, - Aborted, - // This sentinel must be last. - RunStateEnumSize - }; - - enum TargetProperty { - Transform = 0, - Opacity, - // This sentinel must be last. - TargetPropertyEnumSize - }; - - static PassOwnPtr<CCActiveAnimation> create(PassOwnPtr<CCAnimationCurve>, int animationId, int groupId, TargetProperty); - - virtual ~CCActiveAnimation(); - - int id() const { return m_id; } - int group() const { return m_group; } - TargetProperty targetProperty() const { return m_targetProperty; } - - RunState runState() const { return m_runState; } - void setRunState(RunState, double monotonicTime); - - // This is the number of times that the animation will play. If this - // value is zero the animation will not play. If it is negative, then - // the animation will loop indefinitely. - int iterations() const { return m_iterations; } - void setIterations(int n) { m_iterations = n; } - - double startTime() const { return m_startTime; } - void setStartTime(double monotonicTime) { m_startTime = monotonicTime; } - bool hasSetStartTime() const { return m_startTime; } - - double timeOffset() const { return m_timeOffset; } - void setTimeOffset(double monotonicTime) { m_timeOffset = monotonicTime; } - - void suspend(double monotonicTime); - void resume(double monotonicTime); - - // If alternatesDirection is true, on odd numbered iterations we reverse the curve. - bool alternatesDirection() const { return m_alternatesDirection; } - void setAlternatesDirection(bool alternates) { m_alternatesDirection = alternates; } - - bool isFinishedAt(double monotonicTime) const; - bool isFinished() const { return m_runState == Finished - || m_runState == Aborted - || m_runState == WaitingForDeletion; } - - CCAnimationCurve* curve() { return m_curve.get(); } - const CCAnimationCurve* curve() const { return m_curve.get(); } - - // If this is true, even if the animation is running, it will not be tickable until - // it is given a start time. This is true for animations running on the main thread. - bool needsSynchronizedStartTime() const { return m_needsSynchronizedStartTime; } - void setNeedsSynchronizedStartTime(bool needsSynchronizedStartTime) { m_needsSynchronizedStartTime = needsSynchronizedStartTime; } - - // Takes the given absolute time, and using the start time and the number - // of iterations, returns the relative time in the current iteration. - double trimTimeToCurrentIteration(double monotonicTime) const; - - enum InstanceType { - ControllingInstance = 0, - NonControllingInstance - }; - - PassOwnPtr<CCActiveAnimation> clone(InstanceType) const; - PassOwnPtr<CCActiveAnimation> cloneAndInitialize(InstanceType, RunState initialRunState, double startTime) const; - bool isControllingInstance() const { return m_isControllingInstance; } - - void pushPropertiesTo(CCActiveAnimation*) const; - -private: - CCActiveAnimation(PassOwnPtr<CCAnimationCurve>, int animationId, int groupId, TargetProperty); - - OwnPtr<CCAnimationCurve> m_curve; - - // IDs are not necessarily unique. - int m_id; - - // Animations that must be run together are called 'grouped' and have the same group id - // Grouped animations are guaranteed to start at the same time and no other animations - // may animate any of the group's target properties until all animations in the - // group have finished animating. Note: an active animation's group id and target - // property uniquely identify that animation. - int m_group; - - TargetProperty m_targetProperty; - RunState m_runState; - int m_iterations; - double m_startTime; - bool m_alternatesDirection; - - // The time offset effectively pushes the start of the animation back in time. This is - // used for resuming paused animations -- an animation is added with a non-zero time - // offset, causing the animation to skip ahead to the desired point in time. - double m_timeOffset; - - bool m_needsSynchronizedStartTime; - - // When an animation is suspended, it behaves as if it is paused and it also ignores - // all run state changes until it is resumed. This is used for testing purposes. - bool m_suspended; - - // These are used in trimTimeToCurrentIteration to account for time - // spent while paused. This is not included in AnimationState since it - // there is absolutely no need for clients of this controller to know - // about these values. - double m_pauseTime; - double m_totalPausedTime; - - // Animations lead dual lives. An active animation will be conceptually owned by - // two controllers, one on the impl thread and one on the main. In reality, there - // will be two separate CCActiveAnimation instances for the same animation. They - // will have the same group id and the same target property (these two values - // uniquely identify an animation). The instance on the impl thread is the instance - // that ultimately controls the values of the animating layer and so we will refer - // to it as the 'controlling instance'. - bool m_isControllingInstance; -}; - -} // namespace WebCore - -#endif // CCActiveAnimation_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCAnimationCurve.h b/Source/WebCore/platform/graphics/chromium/cc/CCAnimationCurve.h deleted file mode 100644 index 0e458eb2b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCAnimationCurve.h +++ /dev/null @@ -1,76 +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 CCAnimationCurve_h -#define CCAnimationCurve_h - -#include <public/WebTransformationMatrix.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCFloatAnimationCurve; -class CCTransformAnimationCurve; -class IntSize; -class TransformOperations; - -// An animation curve is a function that returns a value given a time. -// There are currently only two types of curve, float and transform. -class CCAnimationCurve { -public: - enum Type { Float, Transform }; - - virtual ~CCAnimationCurve() { } - - virtual double duration() const = 0; - virtual Type type() const = 0; - virtual PassOwnPtr<CCAnimationCurve> clone() const = 0; - - const CCFloatAnimationCurve* toFloatAnimationCurve() const; - const CCTransformAnimationCurve* toTransformAnimationCurve() const; -}; - -class CCFloatAnimationCurve : public CCAnimationCurve { -public: - virtual ~CCFloatAnimationCurve() { } - - virtual float getValue(double t) const = 0; - - // Partial CCAnimation implementation. - virtual Type type() const OVERRIDE { return Float; } -}; - -class CCTransformAnimationCurve : public CCAnimationCurve { -public: - virtual ~CCTransformAnimationCurve() { } - - virtual WebKit::WebTransformationMatrix getValue(double t) const = 0; - - // Partial CCAnimation implementation. - virtual Type type() const OVERRIDE { return Transform; } -}; - -} // namespace WebCore - -#endif // CCAnimation_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCAnimationEvents.h b/Source/WebCore/platform/graphics/chromium/cc/CCAnimationEvents.h deleted file mode 100644 index f21f3d025..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCAnimationEvents.h +++ /dev/null @@ -1,58 +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 CCAnimationEvents_h -#define CCAnimationEvents_h - -#include "CCActiveAnimation.h" - -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { - -struct CCAnimationEvent { - enum Type { Started, Finished }; - - CCAnimationEvent(Type type, int layerId, int groupId, CCActiveAnimation::TargetProperty targetProperty, double monotonicTime) - : type(type) - , layerId(layerId) - , groupId(groupId) - , targetProperty(targetProperty) - , monotonicTime(monotonicTime) - { - } - - Type type; - int layerId; - int groupId; - CCActiveAnimation::TargetProperty targetProperty; - double monotonicTime; -}; - -typedef Vector<CCAnimationEvent> CCAnimationEventsVector; - -} // namespace WebCore - -#endif // CCAnimationEvents_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCAppendQuadsData.h b/Source/WebCore/platform/graphics/chromium/cc/CCAppendQuadsData.h deleted file mode 100644 index d53fdbbf0..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCAppendQuadsData.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 AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CCAppendQuadsData_h -#define CCAppendQuadsData_h - -namespace WebCore { - -struct CCAppendQuadsData { - CCAppendQuadsData() - : hadOcclusionFromOutsideTargetSurface(false) - , hadMissingTiles(false) - { - } - - // Set by the QuadCuller. - bool hadOcclusionFromOutsideTargetSurface; - // Set by the layer appending quads. - bool hadMissingTiles; -}; - -} -#endif // CCCCAppendQuadsData_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCCheckerboardDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCCheckerboardDrawQuad.cpp deleted file mode 100644 index 52fca7c01..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCCheckerboardDrawQuad.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 AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "CCCheckerboardDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCCheckerboardDrawQuad> CCCheckerboardDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect) -{ - return adoptPtr(new CCCheckerboardDrawQuad(sharedQuadState, quadRect)); -} - -CCCheckerboardDrawQuad::CCCheckerboardDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect) - : CCDrawQuad(sharedQuadState, CCDrawQuad::Checkerboard, quadRect) -{ -} - -const CCCheckerboardDrawQuad* CCCheckerboardDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::Checkerboard); - return static_cast<const CCCheckerboardDrawQuad*>(quad); -} - - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCCheckerboardDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCCheckerboardDrawQuad.h deleted file mode 100644 index 7e1105d09..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCCheckerboardDrawQuad.h +++ /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 AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CCCheckerboardDrawQuad_h -#define CCCheckerboardDrawQuad_h - -#include "CCDrawQuad.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -#pragma pack(push, 4) - -class CCCheckerboardDrawQuad : public CCDrawQuad { -public: - static PassOwnPtr<CCCheckerboardDrawQuad> create(const CCSharedQuadState*, const IntRect&); - - static const CCCheckerboardDrawQuad* materialCast(const CCDrawQuad*); -private: - CCCheckerboardDrawQuad(const CCSharedQuadState*, const IntRect&); -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCCompletionEvent.h b/Source/WebCore/platform/graphics/chromium/cc/CCCompletionEvent.h deleted file mode 100644 index f0226617b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCCompletionEvent.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCCompletionEvent_h -#define CCCompletionEvent_h - -#include <wtf/ThreadingPrimitives.h> - -namespace WebCore { - -// Used for making blocking calls from one thread to another. Use only when -// absolutely certain that doing-so will not lead to a deadlock. -// -// It is safe to destroy this object as soon as wait() returns. -class CCCompletionEvent { -public: - CCCompletionEvent() - { -#ifndef NDEBUG - m_waited = false; - m_signaled = false; -#endif - m_mutex.lock(); - } - - ~CCCompletionEvent() - { - m_mutex.unlock(); - ASSERT(m_waited); - ASSERT(m_signaled); - } - - void wait() - { - ASSERT(!m_waited); -#ifndef NDEBUG - m_waited = true; -#endif - m_condition.wait(m_mutex); - } - - void signal() - { - MutexLocker lock(m_mutex); - ASSERT(!m_signaled); -#ifndef NDEBUG - m_signaled = true; -#endif - m_condition.signal(); - } - -private: - Mutex m_mutex; - ThreadCondition m_condition; -#ifndef NDEBUG - // Used to assert that wait() and signal() are each called exactly once. - bool m_waited; - bool m_signaled; -#endif -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDamageTracker.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCDamageTracker.cpp deleted file mode 100644 index 114499ba1..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDamageTracker.cpp +++ /dev/null @@ -1,371 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCDamageTracker.h" - -#include "CCLayerImpl.h" -#include "CCLayerTreeHostCommon.h" -#include "CCMathUtil.h" -#include "CCRenderSurface.h" -#include <public/WebFilterOperations.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -PassOwnPtr<CCDamageTracker> CCDamageTracker::create() -{ - return adoptPtr(new CCDamageTracker()); -} - -CCDamageTracker::CCDamageTracker() - : m_forceFullDamageNextUpdate(false) -{ - m_currentRectHistory = adoptPtr(new RectMap); - m_nextRectHistory = adoptPtr(new RectMap); -} - -CCDamageTracker::~CCDamageTracker() -{ -} - -static inline void expandRectWithFilters(FloatRect& rect, const WebKit::WebFilterOperations& filters) -{ - int top, right, bottom, left; - filters.getOutsets(top, right, bottom, left); - rect.move(-left, -top); - rect.expand(left + right, top + bottom); -} - -static inline void expandDamageRectInsideRectWithFilters(FloatRect& damageRect, const FloatRect& preFilterRect, const WebKit::WebFilterOperations& filters) -{ - FloatRect expandedDamageRect = damageRect; - expandRectWithFilters(expandedDamageRect, filters); - FloatRect filterRect = preFilterRect; - expandRectWithFilters(filterRect, filters); - - expandedDamageRect.intersect(filterRect); - damageRect.unite(expandedDamageRect); -} - -void CCDamageTracker::updateDamageTrackingState(const Vector<CCLayerImpl*>& layerList, int targetSurfaceLayerID, bool targetSurfacePropertyChangedOnlyFromDescendant, const IntRect& targetSurfaceContentRect, CCLayerImpl* targetSurfaceMaskLayer, const WebKit::WebFilterOperations& filters) -{ - // - // This function computes the "damage rect" of a target surface, and updates the state - // that is used to correctly track damage across frames. The damage rect is the region - // of the surface that may have changed and needs to be redrawn. This can be used to - // scissor what is actually drawn, to save GPU computation and bandwidth. - // - // The surface's damage rect is computed as the union of all possible changes that - // have happened to the surface since the last frame was drawn. This includes: - // - any changes for existing layers/surfaces that contribute to the target surface - // - layers/surfaces that existed in the previous frame, but no longer exist. - // - // The basic algorithm for computing the damage region is as follows: - // - // 1. compute damage caused by changes in active/new layers - // for each layer in the layerList: - // if the layer is actually a renderSurface: - // add the surface's damage to our target surface. - // else - // add the layer's damage to the target surface. - // - // 2. compute damage caused by the target surface's mask, if it exists. - // - // 3. compute damage caused by old layers/surfaces that no longer exist - // for each leftover layer: - // add the old layer/surface bounds to the target surface damage. - // - // 4. combine all partial damage rects to get the full damage rect. - // - // Additional important points: - // - // - This algorithm is implicitly recursive; it assumes that descendant surfaces have - // already computed their damage. - // - // - Changes to layers/surfaces indicate "damage" to the target surface; If a layer is - // not changed, it does NOT mean that the layer can skip drawing. All layers that - // overlap the damaged region still need to be drawn. For example, if a layer - // changed its opacity, then layers underneath must be re-drawn as well, even if - // they did not change. - // - // - If a layer/surface property changed, the old bounds and new bounds may overlap... - // i.e. some of the exposed region may not actually be exposing anything. But this - // does not artificially inflate the damage rect. If the layer changed, its entire - // old bounds would always need to be redrawn, regardless of how much it overlaps - // with the layer's new bounds, which also need to be entirely redrawn. - // - // - See comments in the rest of the code to see what exactly is considered a "change" - // in a layer/surface. - // - // - To correctly manage exposed rects, two RectMaps are maintained: - // - // 1. The "current" map contains all the layer bounds that contributed to the - // previous frame (even outside the previous damaged area). If a layer changes - // or does not exist anymore, those regions are then exposed and damage the - // target surface. As the algorithm progresses, entries are removed from the - // map until it has only leftover layers that no longer exist. - // - // 2. The "next" map starts out empty, and as the algorithm progresses, every - // layer/surface that contributes to the surface is added to the map. - // - // 3. After the damage rect is computed, the two maps are swapped, so that the - // damage tracker is ready for the next frame. - // - - // These functions cannot be bypassed with early-exits, even if we know what the - // damage will be for this frame, because we need to update the damage tracker state - // to correctly track the next frame. - FloatRect damageFromActiveLayers = trackDamageFromActiveLayers(layerList, targetSurfaceLayerID); - FloatRect damageFromSurfaceMask = trackDamageFromSurfaceMask(targetSurfaceMaskLayer); - FloatRect damageFromLeftoverRects = trackDamageFromLeftoverRects(); - - FloatRect damageRectForThisUpdate; - - if (m_forceFullDamageNextUpdate || targetSurfacePropertyChangedOnlyFromDescendant) { - damageRectForThisUpdate = targetSurfaceContentRect; - m_forceFullDamageNextUpdate = false; - } else { - // FIXME: can we clamp this damage to the surface's content rect? (affects performance, but not correctness) - damageRectForThisUpdate = damageFromActiveLayers; - damageRectForThisUpdate.uniteIfNonZero(damageFromSurfaceMask); - damageRectForThisUpdate.uniteIfNonZero(damageFromLeftoverRects); - - if (filters.hasFilterThatMovesPixels()) - expandRectWithFilters(damageRectForThisUpdate, filters); - } - - // Damage accumulates until we are notified that we actually did draw on that frame. - m_currentDamageRect.uniteIfNonZero(damageRectForThisUpdate); - - // The next history map becomes the current map for the next frame. Note this must - // happen every frame to correctly track changes, even if damage accumulates over - // multiple frames before actually being drawn. - swap(m_currentRectHistory, m_nextRectHistory); -} - -FloatRect CCDamageTracker::removeRectFromCurrentFrame(int layerID, bool& layerIsNew) -{ - layerIsNew = !m_currentRectHistory->contains(layerID); - - // take() will remove the entry from the map, or if not found, return a default (empty) rect. - return m_currentRectHistory->take(layerID); -} - -void CCDamageTracker::saveRectForNextFrame(int layerID, const FloatRect& targetSpaceRect) -{ - // This layer should not yet exist in next frame's history. - ASSERT(layerID > 0); - ASSERT(m_nextRectHistory->find(layerID) == m_nextRectHistory->end()); - m_nextRectHistory->set(layerID, targetSpaceRect); -} - -FloatRect CCDamageTracker::trackDamageFromActiveLayers(const Vector<CCLayerImpl*>& layerList, int targetSurfaceLayerID) -{ - FloatRect damageRect = FloatRect(); - - for (unsigned layerIndex = 0; layerIndex < layerList.size(); ++layerIndex) { - // Visit layers in back-to-front order. - CCLayerImpl* layer = layerList[layerIndex]; - - if (CCLayerTreeHostCommon::renderSurfaceContributesToTarget<CCLayerImpl>(layer, targetSurfaceLayerID)) - extendDamageForRenderSurface(layer, damageRect); - else - extendDamageForLayer(layer, damageRect); - } - - return damageRect; -} - -FloatRect CCDamageTracker::trackDamageFromSurfaceMask(CCLayerImpl* targetSurfaceMaskLayer) -{ - FloatRect damageRect = FloatRect(); - - if (!targetSurfaceMaskLayer) - return damageRect; - - // Currently, if there is any change to the mask, we choose to damage the entire - // surface. This could potentially be optimized later, but it is not expected to be a - // common case. - if (targetSurfaceMaskLayer->layerPropertyChanged() || !targetSurfaceMaskLayer->updateRect().isEmpty()) - damageRect = FloatRect(FloatPoint::zero(), FloatSize(targetSurfaceMaskLayer->bounds())); - - return damageRect; -} - -FloatRect CCDamageTracker::trackDamageFromLeftoverRects() -{ - // After computing damage for all active layers, any leftover items in the current - // rect history correspond to layers/surfaces that no longer exist. So, these regions - // are now exposed on the target surface. - - FloatRect damageRect = FloatRect(); - - for (RectMap::iterator it = m_currentRectHistory->begin(); it != m_currentRectHistory->end(); ++it) - damageRect.unite(it->second); - - m_currentRectHistory->clear(); - - return damageRect; -} - -static bool layerNeedsToRedrawOntoItsTargetSurface(CCLayerImpl* layer) -{ - // If the layer does NOT own a surface but has SurfacePropertyChanged, - // this means that its target surface is affected and needs to be redrawn. - // However, if the layer DOES own a surface, then the SurfacePropertyChanged - // flag should not be used here, because that flag represents whether the - // layer's surface has changed. - if (layer->renderSurface()) - return layer->layerPropertyChanged(); - return layer->layerPropertyChanged() || layer->layerSurfacePropertyChanged(); -} - -void CCDamageTracker::extendDamageForLayer(CCLayerImpl* layer, FloatRect& targetDamageRect) -{ - // There are two ways that a layer can damage a region of the target surface: - // 1. Property change (e.g. opacity, position, transforms): - // - the entire region of the layer itself damages the surface. - // - the old layer region also damages the surface, because this region is now exposed. - // - note that in many cases the old and new layer rects may overlap, which is fine. - // - // 2. Repaint/update: If a region of the layer that was repainted/updated, that - // region damages the surface. - // - // Property changes take priority over update rects. - // - // This method is called when we want to consider how a layer contributes to its - // targetRenderSurface, even if that layer owns the targetRenderSurface itself. - // To consider how a layer's targetSurface contributes to the ancestorSurface, - // extendDamageForRenderSurface() must be called instead. - - bool layerIsNew = false; - FloatRect oldRectInTargetSpace = removeRectFromCurrentFrame(layer->id(), layerIsNew); - - FloatRect rectInTargetSpace = CCMathUtil::mapClippedRect(layer->drawTransform(), FloatRect(FloatPoint::zero(), layer->contentBounds())); - saveRectForNextFrame(layer->id(), rectInTargetSpace); - - if (layerIsNew || layerNeedsToRedrawOntoItsTargetSurface(layer)) { - // If a layer is new or has changed, then its entire layer rect affects the target surface. - targetDamageRect.uniteIfNonZero(rectInTargetSpace); - - // The layer's old region is now exposed on the target surface, too. - // Note oldRectInTargetSpace is already in target space. - targetDamageRect.uniteIfNonZero(oldRectInTargetSpace); - } else if (!layer->updateRect().isEmpty()) { - // If the layer properties havent changed, then the the target surface is only - // affected by the layer's update area, which could be empty. - FloatRect updateContentRect = layer->updateRect(); - float widthScale = layer->contentBounds().width() / static_cast<float>(layer->bounds().width()); - float heightScale = layer->contentBounds().height() / static_cast<float>(layer->bounds().height()); - updateContentRect.scale(widthScale, heightScale); - - FloatRect updateRectInTargetSpace = CCMathUtil::mapClippedRect(layer->drawTransform(), updateContentRect); - targetDamageRect.uniteIfNonZero(updateRectInTargetSpace); - } -} - -void CCDamageTracker::extendDamageForRenderSurface(CCLayerImpl* layer, FloatRect& targetDamageRect) -{ - // There are two ways a "descendant surface" can damage regions of the "target surface": - // 1. Property change: - // - a surface's geometry can change because of - // - changes to descendants (i.e. the subtree) that affect the surface's content rect - // - changes to ancestor layers that propagate their property changes to their entire subtree. - // - just like layers, both the old surface rect and new surface rect will - // damage the target surface in this case. - // - // 2. Damage rect: This surface may have been damaged by its own layerList as well, and that damage - // should propagate to the target surface. - // - - CCRenderSurface* renderSurface = layer->renderSurface(); - - bool surfaceIsNew = false; - FloatRect oldSurfaceRect = removeRectFromCurrentFrame(layer->id(), surfaceIsNew); - - FloatRect surfaceRectInTargetSpace = renderSurface->drawableContentRect(); // already includes replica if it exists. - saveRectForNextFrame(layer->id(), surfaceRectInTargetSpace); - - FloatRect damageRectInLocalSpace; - if (surfaceIsNew || renderSurface->surfacePropertyChanged() || layer->layerSurfacePropertyChanged()) { - // The entire surface contributes damage. - damageRectInLocalSpace = renderSurface->contentRect(); - - // The surface's old region is now exposed on the target surface, too. - targetDamageRect.uniteIfNonZero(oldSurfaceRect); - } else { - // Only the surface's damageRect will damage the target surface. - damageRectInLocalSpace = renderSurface->damageTracker()->currentDamageRect(); - } - - // If there was damage, transform it to target space, and possibly contribute its reflection if needed. - if (!damageRectInLocalSpace.isEmpty()) { - const WebTransformationMatrix& drawTransform = renderSurface->drawTransform(); - FloatRect damageRectInTargetSpace = CCMathUtil::mapClippedRect(drawTransform, damageRectInLocalSpace); - targetDamageRect.uniteIfNonZero(damageRectInTargetSpace); - - if (layer->replicaLayer()) { - const WebTransformationMatrix& replicaDrawTransform = renderSurface->replicaDrawTransform(); - targetDamageRect.uniteIfNonZero(CCMathUtil::mapClippedRect(replicaDrawTransform, damageRectInLocalSpace)); - } - } - - // If there was damage on the replica's mask, then the target surface receives that damage as well. - if (layer->replicaLayer() && layer->replicaLayer()->maskLayer()) { - CCLayerImpl* replicaMaskLayer = layer->replicaLayer()->maskLayer(); - - bool replicaIsNew = false; - removeRectFromCurrentFrame(replicaMaskLayer->id(), replicaIsNew); - - const WebTransformationMatrix& replicaDrawTransform = renderSurface->replicaDrawTransform(); - FloatRect replicaMaskLayerRect = CCMathUtil::mapClippedRect(replicaDrawTransform, FloatRect(FloatPoint::zero(), FloatSize(replicaMaskLayer->bounds().width(), replicaMaskLayer->bounds().height()))); - saveRectForNextFrame(replicaMaskLayer->id(), replicaMaskLayerRect); - - // In the current implementation, a change in the replica mask damages the entire replica region. - if (replicaIsNew || replicaMaskLayer->layerPropertyChanged() || !replicaMaskLayer->updateRect().isEmpty()) - targetDamageRect.uniteIfNonZero(replicaMaskLayerRect); - } - - // If the layer has a background filter, this may cause pixels in our surface to be expanded, so we will need to expand any damage - // at or below this layer. We expand the damage from this layer too, as we need to readback those pixels from the surface with only - // the contents of layers below this one in them. This means we need to redraw any pixels in the surface being used for the blur in - // this layer this frame. - if (layer->backgroundFilters().hasFilterThatMovesPixels()) - expandDamageRectInsideRectWithFilters(targetDamageRect, surfaceRectInTargetSpace, layer->backgroundFilters()); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDamageTracker.h b/Source/WebCore/platform/graphics/chromium/cc/CCDamageTracker.h deleted file mode 100644 index a86c587af..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDamageTracker.h +++ /dev/null @@ -1,83 +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 CCDamageTracker_h -#define CCDamageTracker_h - -#include "FloatRect.h" -#include <wtf/HashMap.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> - -namespace WebKit { -class WebFilterOperations; -} - -namespace WebCore { - -class CCLayerImpl; -class CCRenderSurface; - -// Computes the region where pixels have actually changed on a RenderSurface. This region is used -// to scissor what is actually drawn to the screen to save GPU computation and bandwidth. -class CCDamageTracker { -public: - static PassOwnPtr<CCDamageTracker> create(); - ~CCDamageTracker(); - - void didDrawDamagedArea() { m_currentDamageRect = FloatRect(); } - void forceFullDamageNextUpdate() { m_forceFullDamageNextUpdate = true; } - void updateDamageTrackingState(const Vector<CCLayerImpl*>& layerList, int targetSurfaceLayerID, bool targetSurfacePropertyChangedOnlyFromDescendant, const IntRect& targetSurfaceContentRect, CCLayerImpl* targetSurfaceMaskLayer, const WebKit::WebFilterOperations&); - - const FloatRect& currentDamageRect() { return m_currentDamageRect; } - -private: - CCDamageTracker(); - - FloatRect trackDamageFromActiveLayers(const Vector<CCLayerImpl*>& layerList, int targetSurfaceLayerID); - FloatRect trackDamageFromSurfaceMask(CCLayerImpl* targetSurfaceMaskLayer); - FloatRect trackDamageFromLeftoverRects(); - - FloatRect removeRectFromCurrentFrame(int layerID, bool& layerIsNew); - void saveRectForNextFrame(int layerID, const FloatRect& targetSpaceRect); - - // These helper functions are used only in trackDamageFromActiveLayers(). - void extendDamageForLayer(CCLayerImpl*, FloatRect& targetDamageRect); - void extendDamageForRenderSurface(CCLayerImpl*, FloatRect& targetDamageRect); - - // To correctly track exposed regions, two hashtables of rects are maintained. - // The "current" map is used to compute exposed regions of the current frame, while - // the "next" map is used to collect layer rects that are used in the next frame. - typedef HashMap<int, FloatRect> RectMap; - OwnPtr<RectMap> m_currentRectHistory; - OwnPtr<RectMap> m_nextRectHistory; - - FloatRect m_currentDamageRect; - bool m_forceFullDamageNextUpdate; -}; - -} // namespace WebCore - -#endif // CCDamageTracker_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDebugBorderDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCDebugBorderDrawQuad.cpp deleted file mode 100644 index 694cc3718..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDebugBorderDrawQuad.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCDebugBorderDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCDebugBorderDrawQuad> CCDebugBorderDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, SkColor color, int width) -{ - return adoptPtr(new CCDebugBorderDrawQuad(sharedQuadState, quadRect, color, width)); -} - -CCDebugBorderDrawQuad::CCDebugBorderDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, SkColor color, int width) - : CCDrawQuad(sharedQuadState, CCDrawQuad::DebugBorder, quadRect) - , m_color(color) - , m_width(width) -{ - m_quadOpaque = false; - if (SkColorGetA(m_color) < 255) - m_needsBlending = true; -} - -const CCDebugBorderDrawQuad* CCDebugBorderDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::DebugBorder); - return static_cast<const CCDebugBorderDrawQuad*>(quad); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDebugBorderDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCDebugBorderDrawQuad.h deleted file mode 100644 index 027a88cc2..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDebugBorderDrawQuad.h +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCDebugBorderDrawQuad_h -#define CCDebugBorderDrawQuad_h - -#include "CCDrawQuad.h" -#include "SkColor.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -#pragma pack(push, 4) - -class CCDebugBorderDrawQuad : public CCDrawQuad { -public: - static PassOwnPtr<CCDebugBorderDrawQuad> create(const CCSharedQuadState*, const IntRect&, SkColor, int width); - - SkColor color() const { return m_color; }; - int width() const { return m_width; } - - static const CCDebugBorderDrawQuad* materialCast(const CCDrawQuad*); -private: - CCDebugBorderDrawQuad(const CCSharedQuadState*, const IntRect&, SkColor, int width); - - SkColor m_color; - int m_width; -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDebugRectHistory.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCDebugRectHistory.cpp deleted file mode 100644 index 857d71f52..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDebugRectHistory.cpp +++ /dev/null @@ -1,136 +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" - -#if USE(ACCELERATED_COMPOSITING) -#include "CCDebugRectHistory.h" - -#include "CCDamageTracker.h" -#include "CCLayerImpl.h" -#include "CCLayerTreeHost.h" -#include "CCMathUtil.h" - -namespace WebCore { - -CCDebugRectHistory::CCDebugRectHistory() -{ -} - -void CCDebugRectHistory::saveDebugRectsForCurrentFrame(CCLayerImpl* rootLayer, const Vector<CCLayerImpl*>& renderSurfaceLayerList, const Vector<IntRect>& occludingScreenSpaceRects, const CCLayerTreeSettings& settings) -{ - // For now, clear all rects from previous frames. In the future we may want to store - // all debug rects for a history of many frames. - m_debugRects.clear(); - - if (settings.showPaintRects) - savePaintRects(rootLayer); - - if (settings.showPropertyChangedRects) - savePropertyChangedRects(renderSurfaceLayerList); - - if (settings.showSurfaceDamageRects) - saveSurfaceDamageRects(renderSurfaceLayerList); - - if (settings.showScreenSpaceRects) - saveScreenSpaceRects(renderSurfaceLayerList); - - if (settings.showOccludingRects) - saveOccludingRects(occludingScreenSpaceRects); -} - - -void CCDebugRectHistory::savePaintRects(CCLayerImpl* layer) -{ - // We would like to visualize where any layer's paint rect (update rect) has changed, - // regardless of whether this layer is skipped for actual drawing or not. Therefore - // we traverse recursively over all layers, not just the render surface list. - - if (!layer->updateRect().isEmpty() && layer->drawsContent()) { - FloatRect updateContentRect = layer->updateRect(); - updateContentRect.scale(layer->contentBounds().width() / static_cast<float>(layer->bounds().width()), layer->contentBounds().height() / static_cast<float>(layer->bounds().height())); - m_debugRects.append(CCDebugRect(PaintRectType, CCMathUtil::mapClippedRect(layer->screenSpaceTransform(), updateContentRect))); - } - - for (unsigned i = 0; i < layer->children().size(); ++i) - savePaintRects(layer->children()[i].get()); -} - -void CCDebugRectHistory::savePropertyChangedRects(const Vector<CCLayerImpl*>& renderSurfaceLayerList) -{ - for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) { - CCLayerImpl* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex]; - CCRenderSurface* renderSurface = renderSurfaceLayer->renderSurface(); - ASSERT(renderSurface); - - const Vector<CCLayerImpl*>& layerList = renderSurface->layerList(); - for (unsigned layerIndex = 0; layerIndex < layerList.size(); ++layerIndex) { - CCLayerImpl* layer = layerList[layerIndex]; - - if (CCLayerTreeHostCommon::renderSurfaceContributesToTarget<CCLayerImpl>(layer, renderSurfaceLayer->id())) - continue; - - if (layer->layerIsAlwaysDamaged()) - continue; - - if (layer->layerPropertyChanged() || layer->layerSurfacePropertyChanged()) - m_debugRects.append(CCDebugRect(PropertyChangedRectType, CCMathUtil::mapClippedRect(layer->screenSpaceTransform(), FloatRect(FloatPoint::zero(), layer->contentBounds())))); - } - } -} - -void CCDebugRectHistory::saveSurfaceDamageRects(const Vector<CCLayerImpl* >& renderSurfaceLayerList) -{ - for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) { - CCLayerImpl* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex]; - CCRenderSurface* renderSurface = renderSurfaceLayer->renderSurface(); - ASSERT(renderSurface); - - m_debugRects.append(CCDebugRect(SurfaceDamageRectType, CCMathUtil::mapClippedRect(renderSurface->screenSpaceTransform(), renderSurface->damageTracker()->currentDamageRect()))); - } -} - -void CCDebugRectHistory::saveScreenSpaceRects(const Vector<CCLayerImpl* >& renderSurfaceLayerList) -{ - for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) { - CCLayerImpl* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex]; - CCRenderSurface* renderSurface = renderSurfaceLayer->renderSurface(); - ASSERT(renderSurface); - - m_debugRects.append(CCDebugRect(ScreenSpaceRectType, CCMathUtil::mapClippedRect(renderSurface->screenSpaceTransform(), renderSurface->contentRect()))); - - if (renderSurfaceLayer->replicaLayer()) - m_debugRects.append(CCDebugRect(ReplicaScreenSpaceRectType, CCMathUtil::mapClippedRect(renderSurface->replicaScreenSpaceTransform(), renderSurface->contentRect()))); - } -} - -void CCDebugRectHistory::saveOccludingRects(const Vector<IntRect>& occludingRects) -{ - for (size_t i = 0; i < occludingRects.size(); ++i) - m_debugRects.append(CCDebugRect(OccludingRectType, occludingRects[i])); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDebugRectHistory.h b/Source/WebCore/platform/graphics/chromium/cc/CCDebugRectHistory.h deleted file mode 100644 index 2405aa0e2..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDebugRectHistory.h +++ /dev/null @@ -1,103 +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 CCDebugRectHistory_h -#define CCDebugRectHistory_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "FloatRect.h" -#include "IntRect.h" -#include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { - -class CCLayerImpl; -struct CCLayerTreeSettings; - -// There are currently six types of debug rects: -// -// - Paint rects (update rects): regions of a layer that needed to be re-uploaded to the -// texture resource; in most cases implying that WebCore had to repaint them, too. -// -// - Property-changed rects: enclosing bounds of layers that cause changes to the screen -// even if the layer did not change internally. (For example, if the layer's opacity or -// position changes.) -// -// - Surface damage rects: the aggregate damage on a target surface that is caused by all -// layers and surfaces that contribute to it. This includes (1) paint rects, (2) property- -// changed rects, and (3) newly exposed areas. -// -// - Screen space rects: this is the region the contents occupy in screen space. -// -// - Replica screen space rects: this is the region the replica's contents occupy in screen space. -// -// - Occluding rects: these are the regions that contribute to the occluded region. -// -enum DebugRectType { PaintRectType, PropertyChangedRectType, SurfaceDamageRectType, ScreenSpaceRectType, ReplicaScreenSpaceRectType, OccludingRectType }; - -struct CCDebugRect { - CCDebugRect(DebugRectType newType, FloatRect newRect) - : type(newType) - , rect(newRect) { } - - DebugRectType type; - FloatRect rect; -}; - -// This class maintains a history of rects of various types that can be used -// for debugging purposes. The overhead of collecting rects is performed only if -// the appropriate CCLayerTreeSettings are enabled. -class CCDebugRectHistory { - WTF_MAKE_NONCOPYABLE(CCDebugRectHistory); -public: - static PassOwnPtr<CCDebugRectHistory> create() - { - return adoptPtr(new CCDebugRectHistory()); - } - - // Note: Saving debug rects must happen before layers' change tracking is reset. - void saveDebugRectsForCurrentFrame(CCLayerImpl* rootLayer, const Vector<CCLayerImpl*>& renderSurfaceLayerList, const Vector<IntRect>& occludingScreenSpaceRects, const CCLayerTreeSettings&); - - const Vector<CCDebugRect>& debugRects() { return m_debugRects; } - -private: - CCDebugRectHistory(); - - void savePaintRects(CCLayerImpl*); - void savePropertyChangedRects(const Vector<CCLayerImpl*>& renderSurfaceLayerList); - void saveSurfaceDamageRects(const Vector<CCLayerImpl* >& renderSurfaceLayerList); - void saveScreenSpaceRects(const Vector<CCLayerImpl* >& renderSurfaceLayerList); - void saveOccludingRects(const Vector<IntRect>& occludingScreenSpaceRects); - - Vector<CCDebugRect> m_debugRects; -}; - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDelayBasedTimeSource.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCDelayBasedTimeSource.cpp deleted file mode 100644 index c2a8892d0..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDelayBasedTimeSource.cpp +++ /dev/null @@ -1,240 +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 "CCDelayBasedTimeSource.h" - -#include "TraceEvent.h" -#include <algorithm> -#include <wtf/CurrentTime.h> -#include <wtf/MathExtras.h> - -namespace WebCore { - -namespace { - -// doubleTickThreshold prevents ticks from running within the specified fraction of an interval. -// This helps account for jitter in the timebase as well as quick timer reactivation. -const double doubleTickThreshold = 0.25; - -// intervalChangeThreshold is the fraction of the interval that will trigger an immediate interval change. -// phaseChangeThreshold is the fraction of the interval that will trigger an immediate phase change. -// If the changes are within the thresholds, the change will take place on the next tick. -// If either change is outside the thresholds, the next tick will be canceled and reissued immediately. -const double intervalChangeThreshold = 0.25; -const double phaseChangeThreshold = 0.25; - -} - - -PassRefPtr<CCDelayBasedTimeSource> CCDelayBasedTimeSource::create(double interval, CCThread* thread) -{ - return adoptRef(new CCDelayBasedTimeSource(interval, thread)); -} - -CCDelayBasedTimeSource::CCDelayBasedTimeSource(double intervalSeconds, CCThread* thread) - : m_client(0) - , m_hasTickTarget(false) - , m_lastTickTime(0) - , m_currentParameters(intervalSeconds, 0) - , m_nextParameters(intervalSeconds, 0) - , m_state(STATE_INACTIVE) - , m_timer(thread, this) -{ -} - -void CCDelayBasedTimeSource::setActive(bool active) -{ - TRACE_EVENT1("cc", "CCDelayBasedTimeSource::setActive", "active", active); - if (!active) { - m_state = STATE_INACTIVE; - m_timer.stop(); - return; - } - - if (m_state == STATE_STARTING || m_state == STATE_ACTIVE) - return; - - if (!m_hasTickTarget) { - // Becoming active the first time is deferred: we post a 0-delay task. When - // it runs, we use that to establish the timebase, become truly active, and - // fire the first tick. - m_state = STATE_STARTING; - m_timer.startOneShot(0); - return; - } - - m_state = STATE_ACTIVE; - - double now = monotonicTimeNow(); - postNextTickTask(now); -} - -double CCDelayBasedTimeSource::lastTickTime() -{ - return m_lastTickTime; -} - -double CCDelayBasedTimeSource::nextTickTimeIfActivated() -{ - return active() ? m_currentParameters.tickTarget : nextTickTarget(monotonicTimeNow()); -} - -void CCDelayBasedTimeSource::onTimerFired() -{ - ASSERT(m_state != STATE_INACTIVE); - - double now = monotonicTimeNow(); - m_lastTickTime = now; - - if (m_state == STATE_STARTING) { - setTimebaseAndInterval(now, m_currentParameters.interval); - m_state = STATE_ACTIVE; - } - - postNextTickTask(now); - - // Fire the tick - if (m_client) - m_client->onTimerTick(); -} - -void CCDelayBasedTimeSource::setTimebaseAndInterval(double timebase, double intervalSeconds) -{ - m_nextParameters.interval = intervalSeconds; - m_nextParameters.tickTarget = timebase; - m_hasTickTarget = true; - - if (m_state != STATE_ACTIVE) { - // If we aren't active, there's no need to reset the timer. - return; - } - - // If the change in interval is larger than the change threshold, - // request an immediate reset. - double intervalDelta = std::abs(intervalSeconds - m_currentParameters.interval); - double intervalChange = intervalDelta / intervalSeconds; - if (intervalChange > intervalChangeThreshold) { - setActive(false); - setActive(true); - return; - } - - // If the change in phase is greater than the change threshold in either - // direction, request an immediate reset. This logic might result in a false - // negative if there is a simultaneous small change in the interval and the - // fmod just happens to return something near zero. Assuming the timebase - // is very recent though, which it should be, we'll still be ok because the - // old clock and new clock just happen to line up. - double targetDelta = std::abs(timebase - m_currentParameters.tickTarget); - double phaseChange = fmod(targetDelta, intervalSeconds) / intervalSeconds; - if (phaseChange > phaseChangeThreshold && phaseChange < (1.0 - phaseChangeThreshold)) { - setActive(false); - setActive(true); - return; - } -} - -double CCDelayBasedTimeSource::monotonicTimeNow() const -{ - return monotonicallyIncreasingTime(); -} - -// This code tries to achieve an average tick rate as close to m_intervalMs as possible. -// To do this, it has to deal with a few basic issues: -// 1. postDelayedTask can delay only at a millisecond granularity. So, 16.666 has to -// posted as 16 or 17. -// 2. A delayed task may come back a bit late (a few ms), or really late (frames later) -// -// The basic idea with this scheduler here is to keep track of where we *want* to run in -// m_tickTarget. We update this with the exact interval. -// -// Then, when we post our task, we take the floor of (m_tickTarget and now()). If we -// started at now=0, and 60FPs: -// now=0 target=16.667 postDelayedTask(16) -// -// When our callback runs, we figure out how far off we were from that goal. Because of the flooring -// operation, and assuming our timer runs exactly when it should, this yields: -// now=16 target=16.667 -// -// Since we can't post a 0.667 ms task to get to now=16, we just treat this as a tick. Then, -// we update target to be 33.333. We now post another task based on the difference between our target -// and now: -// now=16 tickTarget=16.667 newTarget=33.333 --> postDelayedTask(floor(33.333 - 16)) --> postDelayedTask(17) -// -// Over time, with no late tasks, this leads to us posting tasks like this: -// now=0 tickTarget=0 newTarget=16.667 --> tick(), postDelayedTask(16) -// now=16 tickTarget=16.667 newTarget=33.333 --> tick(), postDelayedTask(17) -// now=33 tickTarget=33.333 newTarget=50.000 --> tick(), postDelayedTask(17) -// now=50 tickTarget=50.000 newTarget=66.667 --> tick(), postDelayedTask(16) -// -// We treat delays in tasks differently depending on the amount of delay we encounter. Suppose we -// posted a task with a target=16.667: -// Case 1: late but not unrecoverably-so -// now=18 tickTarget=16.667 -// -// Case 2: so late we obviously missed the tick -// now=25.0 tickTarget=16.667 -// -// We treat the first case as a tick anyway, and assume the delay was -// unusual. Thus, we compute the newTarget based on the old timebase: -// now=18 tickTarget=16.667 newTarget=33.333 --> tick(), postDelayedTask(floor(33.333-18)) --> postDelayedTask(15) -// This brings us back to 18+15 = 33, which was where we would have been if the task hadn't been late. -// -// For the really late delay, we we move to the next logical tick. The timebase is not reset. -// now=37 tickTarget=16.667 newTarget=50.000 --> tick(), postDelayedTask(floor(50.000-37)) --> postDelayedTask(13) -// -// Note, that in the above discussion, times are expressed in milliseconds, but in the code, seconds are used. -double CCDelayBasedTimeSource::nextTickTarget(double now) -{ - double newInterval = m_nextParameters.interval; - double intervalsElapsed = floor((now - m_nextParameters.tickTarget) / newInterval); - double lastEffectiveTick = m_nextParameters.tickTarget + newInterval * intervalsElapsed; - double newTickTarget = lastEffectiveTick + newInterval; - ASSERT(newTickTarget > now); - - // Avoid double ticks when: - // 1) Turning off the timer and turning it right back on. - // 2) Jittery data is passed to setTimebaseAndInterval(). - if (newTickTarget - m_lastTickTime <= newInterval * doubleTickThreshold) - newTickTarget += newInterval; - - return newTickTarget; -} - -void CCDelayBasedTimeSource::postNextTickTask(double now) -{ - double newTickTarget = nextTickTarget(now); - - // Post another task *before* the tick and update state - double delay = newTickTarget - now; - ASSERT(delay <= m_nextParameters.interval * (1.0 + doubleTickThreshold)); - m_timer.startOneShot(delay); - - m_nextParameters.tickTarget = newTickTarget; - m_currentParameters = m_nextParameters; -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDelayBasedTimeSource.h b/Source/WebCore/platform/graphics/chromium/cc/CCDelayBasedTimeSource.h deleted file mode 100644 index c68dc0b99..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDelayBasedTimeSource.h +++ /dev/null @@ -1,98 +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 CCDelayBasedTimeSource_h -#define CCDelayBasedTimeSource_h - -#include "CCTimeSource.h" -#include "CCTimer.h" -#include <wtf/PassRefPtr.h> - -namespace WebCore { - -class CCThread; - -// This timer implements a time source that achieves the specified interval -// in face of millisecond-precision delayed callbacks and random queueing delays. -class CCDelayBasedTimeSource : public CCTimeSource, CCTimerClient { -public: - static PassRefPtr<CCDelayBasedTimeSource> create(double intervalSeconds, CCThread*); - - virtual ~CCDelayBasedTimeSource() { } - - virtual void setClient(CCTimeSourceClient* client) OVERRIDE { m_client = client; } - - // CCTimeSource implementation - virtual void setTimebaseAndInterval(double timebase, double intervalSeconds) OVERRIDE; - - virtual void setActive(bool) OVERRIDE; - virtual bool active() const OVERRIDE { return m_state != STATE_INACTIVE; } - - // Get the last and next tick times. - virtual double lastTickTime() OVERRIDE; - virtual double nextTickTimeIfActivated() OVERRIDE; - - // CCTimerClient implementation. - virtual void onTimerFired() OVERRIDE; - - // Virtual for testing. - virtual double monotonicTimeNow() const; - -protected: - CCDelayBasedTimeSource(double interval, CCThread*); - double nextTickTarget(double now); - void postNextTickTask(double now); - - enum State { - STATE_INACTIVE, - STATE_STARTING, - STATE_ACTIVE, - }; - - struct Parameters { - Parameters(double interval, double tickTarget) - : interval(interval), tickTarget(tickTarget) - { } - double interval; - double tickTarget; - }; - - CCTimeSourceClient* m_client; - bool m_hasTickTarget; - double m_lastTickTime; - - // m_currentParameters should only be written by postNextTickTask. - // m_nextParameters will take effect on the next call to postNextTickTask. - // Maintaining a pending set of parameters allows nextTickTime() to always - // reflect the actual time we expect onTimerFired to be called. - Parameters m_currentParameters; - Parameters m_nextParameters; - - State m_state; - CCThread* m_thread; - CCTimer m_timer; -}; - -} -#endif // CCDelayBasedTimeSource_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDirectRenderer.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCDirectRenderer.cpp deleted file mode 100644 index 6b53789f5..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDirectRenderer.cpp +++ /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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "CCDirectRenderer.h" - -#include "CCMathUtil.h" -#include <public/WebTransformationMatrix.h> - -using WebKit::WebTransformationMatrix; - -static WebTransformationMatrix orthoProjectionMatrix(float left, float right, float bottom, float top) -{ - // Use the standard formula to map the clipping frustum to the cube from - // [-1, -1, -1] to [1, 1, 1]. - float deltaX = right - left; - float deltaY = top - bottom; - WebTransformationMatrix proj; - if (!deltaX || !deltaY) - return proj; - proj.setM11(2.0f / deltaX); - proj.setM41(-(right + left) / deltaX); - proj.setM22(2.0f / deltaY); - proj.setM42(-(top + bottom) / deltaY); - - // Z component of vertices is always set to zero as we don't use the depth buffer - // while drawing. - proj.setM33(0); - - return proj; -} - -static WebTransformationMatrix windowMatrix(int x, int y, int width, int height) -{ - WebTransformationMatrix canvas; - - // Map to window position and scale up to pixel coordinates. - canvas.translate3d(x, y, 0); - canvas.scale3d(width, height, 0); - - // Map from ([-1, -1] to [1, 1]) -> ([0, 0] to [1, 1]) - canvas.translate3d(0.5, 0.5, 0.5); - canvas.scale3d(0.5, 0.5, 0.5); - - return canvas; -} - -namespace WebCore { -// -// static -FloatRect CCDirectRenderer::quadVertexRect() -{ - return FloatRect(-0.5, -0.5, 1, 1); -} - -// static -void CCDirectRenderer::quadRectTransform(WebKit::WebTransformationMatrix* quadRectTransform, const WebKit::WebTransformationMatrix& quadTransform, const FloatRect& quadRect) -{ - *quadRectTransform = quadTransform; - quadRectTransform->translate(0.5 * quadRect.width() + quadRect.x(), 0.5 * quadRect.height() + quadRect.y()); - quadRectTransform->scaleNonUniform(quadRect.width(), quadRect.height()); -} - -// static -void CCDirectRenderer::initializeMatrices(DrawingFrame& frame, const IntRect& drawRect, bool flipY) -{ - if (flipY) - frame.projectionMatrix = orthoProjectionMatrix(drawRect.x(), drawRect.maxX(), drawRect.maxY(), drawRect.y()); - else - frame.projectionMatrix = orthoProjectionMatrix(drawRect.x(), drawRect.maxX(), drawRect.y(), drawRect.maxY()); - frame.windowMatrix = windowMatrix(0, 0, drawRect.width(), drawRect.height()); - frame.flippedY = flipY; -} - -// static -IntRect CCDirectRenderer::moveScissorToWindowSpace(const DrawingFrame& frame, FloatRect scissorRect) -{ - IntRect scissorRectInCanvasSpace = enclosingIntRect(scissorRect); - // The scissor coordinates must be supplied in viewport space so we need to offset - // by the relative position of the top left corner of the current render pass. - IntRect framebufferOutputRect = frame.currentRenderPass->outputRect(); - scissorRectInCanvasSpace.setX(scissorRectInCanvasSpace.x() - framebufferOutputRect.x()); - if (frame.flippedY && !frame.currentTexture) - scissorRectInCanvasSpace.setY(framebufferOutputRect.height() - (scissorRectInCanvasSpace.maxY() - framebufferOutputRect.y())); - else - scissorRectInCanvasSpace.setY(scissorRectInCanvasSpace.y() - framebufferOutputRect.y()); - return scissorRectInCanvasSpace; -} - -void CCDirectRenderer::decideRenderPassAllocationsForFrame(const CCRenderPassList& renderPassesInDrawOrder) -{ - HashMap<CCRenderPass::Id, const CCRenderPass*> renderPassesInFrame; - for (size_t i = 0; i < renderPassesInDrawOrder.size(); ++i) - renderPassesInFrame.set(renderPassesInDrawOrder[i]->id(), renderPassesInDrawOrder[i]); - - Vector<CCRenderPass::Id> passesToDelete; - HashMap<CCRenderPass::Id, OwnPtr<CachedTexture> >::const_iterator passIterator; - for (passIterator = m_renderPassTextures.begin(); passIterator != m_renderPassTextures.end(); ++passIterator) { - const CCRenderPass* renderPassInFrame = renderPassesInFrame.get(passIterator->first); - if (!renderPassInFrame) { - passesToDelete.append(passIterator->first); - continue; - } - - const IntSize& requiredSize = renderPassTextureSize(renderPassInFrame); - GC3Denum requiredFormat = renderPassTextureFormat(renderPassInFrame); - CachedTexture* texture = passIterator->second.get(); - ASSERT(texture); - - if (texture->id() && (texture->size() != requiredSize || texture->format() != requiredFormat)) - texture->free(); - } - - // Delete RenderPass textures from the previous frame that will not be used again. - for (size_t i = 0; i < passesToDelete.size(); ++i) - m_renderPassTextures.remove(passesToDelete[i]); - - for (size_t i = 0; i < renderPassesInDrawOrder.size(); ++i) { - if (!m_renderPassTextures.contains(renderPassesInDrawOrder[i]->id())) { - OwnPtr<CachedTexture> texture = CachedTexture::create(m_resourceProvider); - m_renderPassTextures.set(renderPassesInDrawOrder[i]->id(), texture.release()); - } - } -} - -void CCDirectRenderer::drawFrame(const CCRenderPassList& renderPassesInDrawOrder, const CCRenderPassIdHashMap& renderPassesById) -{ - const CCRenderPass* rootRenderPass = renderPassesInDrawOrder.last(); - ASSERT(rootRenderPass); - - DrawingFrame frame; - frame.renderPassesById = &renderPassesById; - frame.rootRenderPass = rootRenderPass; - frame.rootDamageRect = capabilities().usingPartialSwap ? rootRenderPass->damageRect() : rootRenderPass->outputRect(); - frame.rootDamageRect.intersect(IntRect(IntPoint::zero(), viewportSize())); - - beginDrawingFrame(frame); - for (size_t i = 0; i < renderPassesInDrawOrder.size(); ++i) - drawRenderPass(frame, renderPassesInDrawOrder[i]); - finishDrawingFrame(frame); -} - -void CCDirectRenderer::drawRenderPass(DrawingFrame& frame, const CCRenderPass* renderPass) -{ - if (!useRenderPass(frame, renderPass)) - return; - - frame.scissorRectInRenderPassSpace = frame.currentRenderPass->outputRect(); - if (frame.rootDamageRect != frame.rootRenderPass->outputRect()) { - WebTransformationMatrix inverseTransformToRoot = frame.currentRenderPass->transformToRootTarget().inverse(); - frame.scissorRectInRenderPassSpace.intersect(CCMathUtil::projectClippedRect(inverseTransformToRoot, frame.rootDamageRect)); - } - - enableScissorTestRect(moveScissorToWindowSpace(frame, frame.scissorRectInRenderPassSpace)); - clearFramebuffer(frame); - - const CCQuadList& quadList = renderPass->quadList(); - for (CCQuadList::constBackToFrontIterator it = quadList.backToFrontBegin(); it != quadList.backToFrontEnd(); ++it) { - FloatRect quadScissorRect = frame.scissorRectInRenderPassSpace; - quadScissorRect.intersect(it->get()->clippedRectInTarget()); - if (!quadScissorRect.isEmpty()) { - enableScissorTestRect(moveScissorToWindowSpace(frame, quadScissorRect)); - drawQuad(frame, it->get()); - } - } - - CachedTexture* texture = m_renderPassTextures.get(renderPass->id()); - if (texture) - texture->setIsComplete(!renderPass->hasOcclusionFromOutsideTargetSurface()); -} - -bool CCDirectRenderer::useRenderPass(DrawingFrame& frame, const CCRenderPass* renderPass) -{ - frame.currentRenderPass = renderPass; - frame.currentTexture = 0; - - if (renderPass == frame.rootRenderPass) { - bindFramebufferToOutputSurface(frame); - initializeMatrices(frame, renderPass->outputRect(), true); - setDrawViewportSize(renderPass->outputRect().size()); - return true; - } - - CachedTexture* texture = m_renderPassTextures.get(renderPass->id()); - ASSERT(texture); - if (!texture->id() && !texture->allocate(CCRenderer::ImplPool, renderPassTextureSize(renderPass), renderPassTextureFormat(renderPass), CCResourceProvider::TextureUsageFramebuffer)) - return false; - - return bindFramebufferToTexture(frame, texture, renderPass->outputRect()); -} - -bool CCDirectRenderer::haveCachedResourcesForRenderPassId(CCRenderPass::Id id) const -{ - CachedTexture* texture = m_renderPassTextures.get(id); - return texture && texture->id() && texture->isComplete(); -} - -// static -IntSize CCDirectRenderer::renderPassTextureSize(const CCRenderPass* pass) -{ - return pass->outputRect().size(); -} - -// static -GC3Denum CCDirectRenderer::renderPassTextureFormat(const CCRenderPass*) -{ - return GraphicsContext3D::RGBA; -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDirectRenderer.h b/Source/WebCore/platform/graphics/chromium/cc/CCDirectRenderer.h deleted file mode 100644 index 73d624fba..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDirectRenderer.h +++ /dev/null @@ -1,127 +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 CCDirectRenderer_h -#define CCDirectRenderer_h - -#include "CCRenderer.h" -#include "CCResourceProvider.h" -#include "CCScopedTexture.h" - -namespace WebCore { - -class CCResourceProvider; - -// This is the base class for code shared between the GL and software -// renderer implementations. "Direct" refers to the fact that it does not -// delegate rendering to another compositor. -class CCDirectRenderer : public CCRenderer { - WTF_MAKE_NONCOPYABLE(CCDirectRenderer); -public: - virtual ~CCDirectRenderer() { } - - CCResourceProvider* resourceProvider() const { return m_resourceProvider; } - - virtual void decideRenderPassAllocationsForFrame(const CCRenderPassList& renderPassesInDrawOrder) OVERRIDE; - virtual bool haveCachedResourcesForRenderPassId(CCRenderPass::Id) const OVERRIDE; - virtual void drawFrame(const CCRenderPassList& renderPassesInDrawOrder, const CCRenderPassIdHashMap& renderPassesById) OVERRIDE; - -protected: - CCDirectRenderer(CCRendererClient* client, CCResourceProvider* resourceProvider) - : CCRenderer(client) - , m_resourceProvider(resourceProvider) - { - } - - struct DrawingFrame { - const CCRenderPassIdHashMap* renderPassesById; - const CCRenderPass* rootRenderPass; - const CCRenderPass* currentRenderPass; - const CCScopedTexture* currentTexture; - - FloatRect rootDamageRect; - - WebKit::WebTransformationMatrix projectionMatrix; - WebKit::WebTransformationMatrix windowMatrix; - bool flippedY; - FloatRect scissorRectInRenderPassSpace; - - DrawingFrame() - : rootRenderPass(0) - , currentRenderPass(0) - , currentTexture(0) - , flippedY(false) - { } - }; - - class CachedTexture : public CCScopedTexture { - WTF_MAKE_NONCOPYABLE(CachedTexture); - public: - static PassOwnPtr<CachedTexture> create(CCResourceProvider* resourceProvider) { return adoptPtr(new CachedTexture(resourceProvider)); } - virtual ~CachedTexture() { } - - bool isComplete() const { return m_isComplete; } - void setIsComplete(bool isComplete) { m_isComplete = isComplete; } - - protected: - explicit CachedTexture(CCResourceProvider* resourceProvider) - : CCScopedTexture(resourceProvider) - , m_isComplete(false) - { - } - - private: - bool m_isComplete; - }; - - static FloatRect quadVertexRect(); - static void quadRectTransform(WebKit::WebTransformationMatrix* quadRectTransform, const WebKit::WebTransformationMatrix& quadTransform, const FloatRect& quadRect); - static void initializeMatrices(DrawingFrame&, const IntRect& drawRect, bool flipY); - static IntRect moveScissorToWindowSpace(const DrawingFrame&, FloatRect scissorRect); - - bool haveCachedResources(CCRenderPass::Id) const; - static IntSize renderPassTextureSize(const CCRenderPass*); - static GC3Denum renderPassTextureFormat(const CCRenderPass*); - - void drawRenderPass(DrawingFrame&, const CCRenderPass*); - bool useRenderPass(DrawingFrame&, const CCRenderPass*); - - virtual void bindFramebufferToOutputSurface(DrawingFrame&) = 0; - virtual bool bindFramebufferToTexture(DrawingFrame&, const CCScopedTexture*, const IntRect& framebufferRect) = 0; - virtual void setDrawViewportSize(const IntSize&) = 0; - virtual void enableScissorTestRect(const IntRect& scissorRect) = 0; - virtual void disableScissorTest() = 0; - virtual void clearFramebuffer(DrawingFrame&) = 0; - virtual void drawQuad(DrawingFrame&, const CCDrawQuad*) = 0; - virtual void beginDrawingFrame(DrawingFrame&) = 0; - virtual void finishDrawingFrame(DrawingFrame&) = 0; - - HashMap<CCRenderPass::Id, OwnPtr<CachedTexture> > m_renderPassTextures; - CCResourceProvider* m_resourceProvider; -}; - -} - -#endif // CCDirectRenderer_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCDrawQuad.cpp deleted file mode 100644 index 49321182b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDrawQuad.cpp +++ /dev/null @@ -1,121 +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 "CCDrawQuad.h" - -#include "CCCheckerboardDrawQuad.h" -#include "CCDebugBorderDrawQuad.h" -#include "CCIOSurfaceDrawQuad.h" -#include "CCRenderPassDrawQuad.h" -#include "CCSolidColorDrawQuad.h" -#include "CCStreamVideoDrawQuad.h" -#include "CCTextureDrawQuad.h" -#include "CCTileDrawQuad.h" -#include "CCYUVVideoDrawQuad.h" -#include "IntRect.h" - -namespace WebCore { - -CCDrawQuad::CCDrawQuad(const CCSharedQuadState* sharedQuadState, Material material, const IntRect& quadRect) - : m_sharedQuadState(sharedQuadState) - , m_sharedQuadStateId(sharedQuadState->id) - , m_material(material) - , m_quadRect(quadRect) - , m_quadVisibleRect(quadRect) - , m_quadOpaque(true) - , m_needsBlending(false) -{ - ASSERT(m_sharedQuadState); - ASSERT(m_material != Invalid); -} - -IntRect CCDrawQuad::opaqueRect() const -{ - if (opacity() != 1) - return IntRect(); - if (m_sharedQuadState->opaque && m_quadOpaque) - return m_quadRect; - return m_opaqueRect; -} - -void CCDrawQuad::setQuadVisibleRect(const IntRect& quadVisibleRect) -{ - IntRect intersection = quadVisibleRect; - intersection.intersect(m_quadRect); - m_quadVisibleRect = intersection; -} - -unsigned CCDrawQuad::size() const -{ - switch (material()) { - case Checkerboard: - return sizeof(CCCheckerboardDrawQuad); - case DebugBorder: - return sizeof(CCDebugBorderDrawQuad); - case IOSurfaceContent: - return sizeof(CCIOSurfaceDrawQuad); - case TextureContent: - return sizeof(CCTextureDrawQuad); - case SolidColor: - return sizeof(CCSolidColorDrawQuad); - case TiledContent: - return sizeof(CCTileDrawQuad); - case StreamVideoContent: - return sizeof(CCStreamVideoDrawQuad); - case RenderPass: - return sizeof(CCRenderPassDrawQuad); - case YUVVideoContent: - return sizeof(CCYUVVideoDrawQuad); - case Invalid: - break; - } - - CRASH(); - return sizeof(CCDrawQuad); -} - -PassOwnPtr<CCDrawQuad> CCDrawQuad::copy(const CCSharedQuadState* copiedSharedQuadState) const -{ - // RenderPass quads have their own copy() method. - ASSERT(material() != RenderPass); - - unsigned bytes = size(); - ASSERT(bytes); - - OwnPtr<CCDrawQuad> copyQuad(adoptPtr(reinterpret_cast<CCDrawQuad*>(new char[bytes]))); - memcpy(copyQuad.get(), this, bytes); - copyQuad->setSharedQuadState(copiedSharedQuadState); - - return copyQuad.release(); -} - -void CCDrawQuad::setSharedQuadState(const CCSharedQuadState* sharedQuadState) -{ - m_sharedQuadState = sharedQuadState; - m_sharedQuadStateId = sharedQuadState->id; -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCDrawQuad.h deleted file mode 100644 index 805ef1562..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCDrawQuad.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCDrawQuad_h -#define CCDrawQuad_h - -#include "CCSharedQuadState.h" - -namespace WebCore { - -// WARNING! All CCXYZDrawQuad classes must remain PODs (plain old data). -// They are intended to be "serializable" by copying their raw bytes, so they -// must not contain any non-bit-copyable member variables! -// -// Furthermore, the class members need to be packed so they are aligned -// properly and don't have paddings/gaps, otherwise memory check tools -// like Valgrind will complain about uninitialized memory usage when -// transferring these classes over the wire. -#pragma pack(push, 4) - -// CCDrawQuad is a bag of data used for drawing a quad. Because different -// materials need different bits of per-quad data to render, classes that derive -// from CCDrawQuad store additional data in their derived instance. The Material -// enum is used to "safely" downcast to the derived class. -class CCDrawQuad { -public: - enum Material { - Invalid, - Checkerboard, - DebugBorder, - IOSurfaceContent, - RenderPass, - TextureContent, - SolidColor, - TiledContent, - YUVVideoContent, - StreamVideoContent, - }; - - IntRect quadRect() const { return m_quadRect; } - const WebKit::WebTransformationMatrix& quadTransform() const { return m_sharedQuadState->quadTransform; } - IntRect visibleContentRect() const { return m_sharedQuadState->visibleContentRect; } - IntRect clippedRectInTarget() const { return m_sharedQuadState->clippedRectInTarget; } - float opacity() const { return m_sharedQuadState->opacity; } - // For the purposes of blending, what part of the contents of this quad are opaque? - IntRect opaqueRect() const; - bool needsBlending() const { return m_needsBlending || !opaqueRect().contains(m_quadVisibleRect); } - - // Allows changing the rect that gets drawn to make it smaller. Parameter passed - // in will be clipped to quadRect(). - void setQuadVisibleRect(const IntRect&); - IntRect quadVisibleRect() const { return m_quadVisibleRect; } - bool isDebugQuad() const { return m_material == DebugBorder; } - - Material material() const { return m_material; } - - // Returns transfer size of this object based on the derived class (by - // looking at the material type). - unsigned size() const; - - PassOwnPtr<CCDrawQuad> copy(const CCSharedQuadState* copiedSharedQuadState) const; - - const CCSharedQuadState* sharedQuadState() const { return m_sharedQuadState; } - int sharedQuadStateId() const { return m_sharedQuadStateId; } - void setSharedQuadState(const CCSharedQuadState*); - -protected: - CCDrawQuad(const CCSharedQuadState*, Material, const IntRect&); - - // Stores state common to a large bundle of quads; kept separate for memory - // efficiency. There is special treatment to reconstruct these pointers - // during serialization. - const CCSharedQuadState* m_sharedQuadState; - int m_sharedQuadStateId; - - Material m_material; - IntRect m_quadRect; - IntRect m_quadVisibleRect; - - // By default, the shared quad state determines whether or not this quad is - // opaque or needs blending. Derived classes can override with these - // variables. - bool m_quadOpaque; - bool m_needsBlending; - - // Be default, this rect is empty. It is used when the shared quad state and above - // variables determine that the quad is not fully opaque but may be partially opaque. - IntRect m_opaqueRect; -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCFontAtlas.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCFontAtlas.cpp deleted file mode 100644 index 8636a1a3d..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCFontAtlas.cpp +++ /dev/null @@ -1,90 +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" - -#if USE(ACCELERATED_COMPOSITING) -#include "CCFontAtlas.h" - -#include "CCProxy.h" -#include "SkCanvas.h" - -namespace WebCore { - -using namespace std; - -CCFontAtlas::CCFontAtlas(SkBitmap bitmap, IntRect asciiToRectTable[128], int fontHeight) - : m_atlas(bitmap) - , m_fontHeight(fontHeight) -{ - for (size_t i = 0; i < 128; ++i) - m_asciiToRectTable[i] = asciiToRectTable[i]; -} - -CCFontAtlas::~CCFontAtlas() -{ -} - -void CCFontAtlas::drawText(SkCanvas* canvas, const SkPaint& paint, const String& text, const IntPoint& destPosition, const IntSize& clip) const -{ - ASSERT(CCProxy::isImplThread()); - - Vector<String> lines; - text.split('\n', lines); - - IntPoint position = destPosition; - for (size_t i = 0; i < lines.size(); ++i) { - drawOneLineOfTextInternal(canvas, paint, lines[i], position); - position.setY(position.y() + m_fontHeight); - if (position.y() > clip.height()) - return; - } -} - -void CCFontAtlas::drawOneLineOfTextInternal(SkCanvas* canvas, const SkPaint& paint, const String& textLine, const IntPoint& destPosition) const -{ - ASSERT(CCProxy::isImplThread()); - - IntPoint position = destPosition; - for (unsigned i = 0; i < textLine.length(); ++i) { - // If the ASCII code is out of bounds, then index 0 is used, which is just a plain rectangle glyph. - int asciiIndex = (textLine[i] < 128) ? textLine[i] : 0; - IntRect glyphBounds = m_asciiToRectTable[asciiIndex]; - SkIRect source = SkIRect::MakeXYWH(glyphBounds.x(), glyphBounds.y(), glyphBounds.width(), glyphBounds.height()); - canvas->drawBitmapRect(m_atlas, &source, SkRect::MakeXYWH(position.x(), position.y(), glyphBounds.width(), glyphBounds.height()), &paint); - position.setX(position.x() + glyphBounds.width()); - } -} - -void CCFontAtlas::drawDebugAtlas(SkCanvas* canvas, const IntPoint& destPosition) const -{ - ASSERT(CCProxy::isImplThread()); - - SkIRect source = SkIRect::MakeWH(m_atlas.width(), m_atlas.height()); - canvas->drawBitmapRect(m_atlas, &source, SkRect::MakeXYWH(destPosition.x(), destPosition.y(), m_atlas.width(), m_atlas.height())); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCFontAtlas.h b/Source/WebCore/platform/graphics/chromium/cc/CCFontAtlas.h deleted file mode 100644 index bf25264f6..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCFontAtlas.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCFontAtlas_h -#define CCFontAtlas_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "IntRect.h" -#include "SkBitmap.h" -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/text/WTFString.h> - -class SkCanvas; - -namespace WebCore { - -class Color; -class FontDescription; -class GraphicsContext; -class IntPoint; -class IntSize; - -// This class provides basic ability to draw text onto the heads-up display. -class CCFontAtlas { - WTF_MAKE_NONCOPYABLE(CCFontAtlas); -public: - static PassOwnPtr<CCFontAtlas> create(SkBitmap bitmap, IntRect asciiToRectTable[128], int fontHeight) - { - return adoptPtr(new CCFontAtlas(bitmap, asciiToRectTable, fontHeight)); - } - ~CCFontAtlas(); - - // Draws multiple lines of text where each line of text is separated by '\n'. - // - Correct glyphs will be drawn for ASCII codes in the range 32-127; any characters - // outside that range will be displayed as a default rectangle glyph. - // - IntSize clip is used to avoid wasting time drawing things that are outside the - // target canvas bounds. - // - Should only be called only on the impl thread. - void drawText(SkCanvas*, const SkPaint&, const String& text, const IntPoint& destPosition, const IntSize& clip) const; - - // Draws the entire atlas at the specified position, just for debugging purposes. - void drawDebugAtlas(SkCanvas*, const IntPoint& destPosition) const; - -private: - CCFontAtlas(SkBitmap, IntRect asciiToRectTable[128], int fontHeight); - - void drawOneLineOfTextInternal(SkCanvas*, const SkPaint&, const String&, const IntPoint& destPosition) const; - - // The actual texture atlas containing all the pre-rendered glyphs. - SkBitmap m_atlas; - - // The look-up tables mapping ascii characters to their IntRect locations on the atlas. - IntRect m_asciiToRectTable[128]; - - int m_fontHeight; -}; - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateController.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateController.cpp deleted file mode 100755 index c6059ee99..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateController.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCFrameRateController.h" - -#include "CCDelayBasedTimeSource.h" -#include "CCTimeSource.h" -#include "TraceEvent.h" -#include <wtf/CurrentTime.h> - -namespace { - -// This will be the maximum number of pending frames unless -// CCFrameRateController::setMaxFramesPending is called. -const int defaultMaxFramesPending = 2; - -} - -namespace WebCore { - -class CCFrameRateControllerTimeSourceAdapter : public CCTimeSourceClient { -public: - static PassOwnPtr<CCFrameRateControllerTimeSourceAdapter> create(CCFrameRateController* frameRateController) - { - return adoptPtr(new CCFrameRateControllerTimeSourceAdapter(frameRateController)); - } - virtual ~CCFrameRateControllerTimeSourceAdapter() { } - - virtual void onTimerTick() OVERRIDE { m_frameRateController->onTimerTick(); } -private: - explicit CCFrameRateControllerTimeSourceAdapter(CCFrameRateController* frameRateController) - : m_frameRateController(frameRateController) { } - - CCFrameRateController* m_frameRateController; -}; - -CCFrameRateController::CCFrameRateController(PassRefPtr<CCTimeSource> timer) - : m_client(0) - , m_numFramesPending(0) - , m_maxFramesPending(defaultMaxFramesPending) - , m_timeSource(timer) - , m_active(false) - , m_swapBuffersCompleteSupported(true) - , m_isTimeSourceThrottling(true) -{ - m_timeSourceClientAdapter = CCFrameRateControllerTimeSourceAdapter::create(this); - m_timeSource->setClient(m_timeSourceClientAdapter.get()); -} - -CCFrameRateController::CCFrameRateController(CCThread* thread) - : m_client(0) - , m_numFramesPending(0) - , m_maxFramesPending(defaultMaxFramesPending) - , m_active(false) - , m_swapBuffersCompleteSupported(true) - , m_isTimeSourceThrottling(false) -{ - m_manualTicker = adoptPtr(new CCTimer(thread, this)); -} - -CCFrameRateController::~CCFrameRateController() -{ - if (m_isTimeSourceThrottling) - m_timeSource->setActive(false); -} - -void CCFrameRateController::setActive(bool active) -{ - if (m_active == active) - return; - TRACE_EVENT1("cc", "CCFrameRateController::setActive", "active", active); - m_active = active; - - if (m_isTimeSourceThrottling) - m_timeSource->setActive(active); - else { - if (active) - postManualTick(); - else - m_manualTicker->stop(); - } -} - -void CCFrameRateController::setMaxFramesPending(int maxFramesPending) -{ - ASSERT(maxFramesPending > 0); - m_maxFramesPending = maxFramesPending; -} - -void CCFrameRateController::setTimebaseAndInterval(double timebase, double intervalSeconds) -{ - if (m_isTimeSourceThrottling) - m_timeSource->setTimebaseAndInterval(timebase, intervalSeconds); -} - -void CCFrameRateController::setSwapBuffersCompleteSupported(bool supported) -{ - m_swapBuffersCompleteSupported = supported; -} - -void CCFrameRateController::onTimerTick() -{ - ASSERT(m_active); - - // Don't forward the tick if we have too many frames in flight. - if (m_numFramesPending >= m_maxFramesPending) { - TRACE_EVENT0("cc", "CCFrameRateController::onTimerTickButMaxFramesPending"); - return; - } - - if (m_client) - m_client->vsyncTick(); - - if (m_swapBuffersCompleteSupported && !m_isTimeSourceThrottling && m_numFramesPending < m_maxFramesPending) - postManualTick(); -} - -void CCFrameRateController::postManualTick() -{ - if (m_active) - m_manualTicker->startOneShot(0); -} - -void CCFrameRateController::onTimerFired() -{ - onTimerTick(); -} - -void CCFrameRateController::didBeginFrame() -{ - if (m_swapBuffersCompleteSupported) - m_numFramesPending++; - else if (!m_isTimeSourceThrottling) - postManualTick(); -} - -void CCFrameRateController::didFinishFrame() -{ - ASSERT(m_swapBuffersCompleteSupported); - - m_numFramesPending--; - if (!m_isTimeSourceThrottling) - postManualTick(); -} - -void CCFrameRateController::didAbortAllPendingFrames() -{ - m_numFramesPending = 0; -} - -double CCFrameRateController::nextTickTimeIfActivated() -{ - if (m_isTimeSourceThrottling) - return m_timeSource->nextTickTimeIfActivated(); - - return monotonicallyIncreasingTime(); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateController.h b/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateController.h deleted file mode 100644 index f87cd4a2b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateController.h +++ /dev/null @@ -1,98 +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 CCFrameRateController_h -#define CCFrameRateController_h - -#include "CCTimer.h" - -#include <wtf/Deque.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCThread; -class CCTimeSource; - -class CCFrameRateControllerClient { -public: - virtual void vsyncTick() = 0; - -protected: - virtual ~CCFrameRateControllerClient() { } -}; - -class CCFrameRateControllerTimeSourceAdapter; - -class CCFrameRateController : public CCTimerClient { -public: - explicit CCFrameRateController(PassRefPtr<CCTimeSource>); - // Alternate form of CCFrameRateController with unthrottled frame-rate. - explicit CCFrameRateController(CCThread*); - virtual ~CCFrameRateController(); - - void setClient(CCFrameRateControllerClient* client) { m_client = client; } - - void setActive(bool); - - // Use the following methods to adjust target frame rate. - // - // Multiple frames can be in-progress, but for every didBeginFrame, a - // didFinishFrame should be posted. - // - // If the rendering pipeline crashes, call didAbortAllPendingFrames. - void didBeginFrame(); - void didFinishFrame(); - void didAbortAllPendingFrames(); - void setMaxFramesPending(int); // 0 for unlimited. - double nextTickTimeIfActivated(); - - void setTimebaseAndInterval(double timebase, double intervalSeconds); - void setSwapBuffersCompleteSupported(bool); - -protected: - friend class CCFrameRateControllerTimeSourceAdapter; - void onTimerTick(); - - void postManualTick(); - - // CCTimerClient implementation (used for unthrottled frame-rate). - virtual void onTimerFired() OVERRIDE; - - CCFrameRateControllerClient* m_client; - int m_numFramesPending; - int m_maxFramesPending; - RefPtr<CCTimeSource> m_timeSource; - OwnPtr<CCFrameRateControllerTimeSourceAdapter> m_timeSourceClientAdapter; - bool m_active; - bool m_swapBuffersCompleteSupported; - - // Members for unthrottled frame-rate. - bool m_isTimeSourceThrottling; - OwnPtr<CCTimer> m_manualTicker; -}; - -} -#endif // CCFrameRateController_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateCounter.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateCounter.cpp deleted file mode 100644 index e34225a84..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateCounter.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 USE(ACCELERATED_COMPOSITING) -#include "CCFrameRateCounter.h" - -#include "CCProxy.h" -#include <public/Platform.h> -#include <wtf/CurrentTime.h> - -namespace WebCore { - -const double CCFrameRateCounter::kFrameTooFast = 1.0 / 70.0; // measured in seconds -const double CCFrameRateCounter::kFrameTooSlow = 1.0 / 12.0; -const double CCFrameRateCounter::kDroppedFrameTime = 1.0 / 50.0; - -// safeMod works on -1, returning m-1 in that case. -static inline int safeMod(int number, int modulus) -{ - return (number + modulus) % modulus; -} - -inline double CCFrameRateCounter::frameInterval(int frameNumber) const -{ - return m_timeStampHistory[frameIndex(frameNumber)] - - m_timeStampHistory[frameIndex(frameNumber - 1)]; -} - -inline int CCFrameRateCounter::frameIndex(int frameNumber) const -{ - return safeMod(frameNumber, kTimeStampHistorySize); -} - -CCFrameRateCounter::CCFrameRateCounter() - : m_currentFrameNumber(1) - , m_droppedFrameCount(0) -{ - m_timeStampHistory[0] = currentTime(); - m_timeStampHistory[1] = m_timeStampHistory[0]; - for (int i = 2; i < kTimeStampHistorySize; i++) - m_timeStampHistory[i] = 0; -} - -void CCFrameRateCounter::markBeginningOfFrame(double timestamp) -{ - m_timeStampHistory[frameIndex(m_currentFrameNumber)] = timestamp; - double frameIntervalSeconds = frameInterval(m_currentFrameNumber); - - if (CCProxy::hasImplThread() && m_currentFrameNumber > 0) { - double drawDelayMs = frameIntervalSeconds * 1000.0; - WebKit::Platform::current()->histogramCustomCounts("Renderer4.CompositorThreadImplDrawDelay", static_cast<int>(drawDelayMs), 1, 120, 60); - } - - if (!isBadFrameInterval(frameIntervalSeconds) && frameIntervalSeconds > kDroppedFrameTime) - ++m_droppedFrameCount; -} - -void CCFrameRateCounter::markEndOfFrame() -{ - m_currentFrameNumber += 1; -} - -bool CCFrameRateCounter::isBadFrameInterval(double intervalBetweenConsecutiveFrames) const -{ - bool schedulerAllowsDoubleFrames = !CCProxy::hasImplThread(); - bool intervalTooFast = schedulerAllowsDoubleFrames && intervalBetweenConsecutiveFrames < kFrameTooFast; - bool intervalTooSlow = intervalBetweenConsecutiveFrames > kFrameTooSlow; - return intervalTooFast || intervalTooSlow; -} - -bool CCFrameRateCounter::isBadFrame(int frameNumber) const -{ - return isBadFrameInterval(frameInterval(frameNumber)); -} - -void CCFrameRateCounter::getAverageFPSAndStandardDeviation(double& averageFPS, double& standardDeviation) const -{ - int frame = m_currentFrameNumber - 1; - averageFPS = 0; - int averageFPSCount = 0; - double fpsVarianceNumerator = 0; - - // Walk backwards through the samples looking for a run of good frame - // timings from which to compute the mean and standard deviation. - // - // Slow frames occur just because the user is inactive, and should be - // ignored. Fast frames are ignored if the scheduler is in single-thread - // mode in order to represent the true frame rate in spite of the fact that - // the first few swapbuffers happen instantly which skews the statistics - // too much for short lived animations. - // - // isBadFrame encapsulates the frame too slow/frame too fast logic. - while (1) { - if (!isBadFrame(frame)) { - averageFPSCount++; - double secForLastFrame = m_timeStampHistory[frameIndex(frame)] - - m_timeStampHistory[frameIndex(frame - 1)]; - double x = 1.0 / secForLastFrame; - double deltaFromAverage = x - averageFPS; - // Change with caution - numerics. http://en.wikipedia.org/wiki/Standard_deviation - averageFPS = averageFPS + deltaFromAverage / averageFPSCount; - fpsVarianceNumerator = fpsVarianceNumerator + deltaFromAverage * (x - averageFPS); - } - if (averageFPSCount && isBadFrame(frame)) { - // We've gathered a run of good samples, so stop. - break; - } - --frame; - if (frameIndex(frame) == frameIndex(m_currentFrameNumber) || frame < 0) { - // We've gone through all available historical data, so stop. - break; - } - } - - standardDeviation = sqrt(fpsVarianceNumerator / averageFPSCount); -} - -double CCFrameRateCounter::timeStampOfRecentFrame(int n) -{ - ASSERT(n >= 0 && n < kTimeStampHistorySize); - int desiredIndex = (frameIndex(m_currentFrameNumber) + n) % kTimeStampHistorySize; - return m_timeStampHistory[desiredIndex]; -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateCounter.h b/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateCounter.h deleted file mode 100644 index fc23e26e3..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCFrameRateCounter.h +++ /dev/null @@ -1,91 +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 CCFrameRateCounter_h -#define CCFrameRateCounter_h - -#if USE(ACCELERATED_COMPOSITING) - -#include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -// This class maintains a history of timestamps, and provides functionality to -// intelligently compute average frames per second (and standard deviation). -class CCFrameRateCounter { - WTF_MAKE_NONCOPYABLE(CCFrameRateCounter); -public: - static PassOwnPtr<CCFrameRateCounter> create() - { - return adoptPtr(new CCFrameRateCounter()); - } - - void markBeginningOfFrame(double timestamp); - void markEndOfFrame(); - int currentFrameNumber() const { return m_currentFrameNumber; } - void getAverageFPSAndStandardDeviation(double& averageFPS, double& standardDeviation) const; - int timeStampHistorySize() const { return kTimeStampHistorySize; } - - // n = 0 returns the oldest frame retained in the history, - // while n = timeStampHistorySize() - 1 returns the timestamp most recent frame. - double timeStampOfRecentFrame(int /* n */); - - // This is a heuristic that can be used to ignore frames in a reasonable way. Returns - // true if the given frame interval is too fast or too slow, based on constant thresholds. - bool isBadFrameInterval(double intervalBetweenConsecutiveFrames) const; - - int droppedFrameCount() const { return m_droppedFrameCount; } - -private: - CCFrameRateCounter(); - - double frameInterval(int frameNumber) const; - int frameIndex(int frameNumber) const; - bool isBadFrame(int frameNumber) const; - - // Two thresholds (measured in seconds) that describe what is considered to be a "no-op frame" that should not be counted. - // - if the frame is too fast, then given our compositor implementation, the frame probably was a no-op and did not draw. - // - if the frame is too slow, then there is probably not animating content, so we should not pollute the average. - static const double kFrameTooFast; - static const double kFrameTooSlow; - - // If a frame takes longer than this threshold (measured in seconds) then we - // (naively) assume that it missed a screen refresh; that is, we dropped a frame. - // FIXME: Determine this threshold based on monitor refresh rate, crbug.com/138642. - static const double kDroppedFrameTime; - - static const int kTimeStampHistorySize = 120; - - int m_currentFrameNumber; - double m_timeStampHistory[kTimeStampHistorySize]; - - int m_droppedFrameCount; -}; - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCGraphicsContext.h b/Source/WebCore/platform/graphics/chromium/cc/CCGraphicsContext.h deleted file mode 100644 index 5e35f5967..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCGraphicsContext.h +++ /dev/null @@ -1,42 +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 CCGraphicsContext_h -#define CCGraphicsContext_h - -#include <public/WebCompositorOutputSurface.h> -#include <public/WebGraphicsContext3D.h> -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -// FIXME: rename fully to CCOutputSurface. -typedef WebKit::WebCompositorOutputSurface CCGraphicsContext; - -} - -#endif // CCGraphicsContext_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.cpp deleted file mode 100644 index 508a50bff..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.cpp +++ /dev/null @@ -1,306 +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 "CCHeadsUpDisplayLayerImpl.h" - -#include "CCDebugRectHistory.h" -#include "CCFontAtlas.h" -#include "CCFrameRateCounter.h" -#include "CCLayerTreeHostImpl.h" -#include "CCQuadSink.h" -#include "CCTextureDrawQuad.h" -#include "Extensions3DChromium.h" -#include "GraphicsContext3D.h" -#include "SkBitmap.h" -#include "SkColorMatrixFilter.h" -#include "SkPaint.h" -#include "skia/ext/platform_canvas.h" -#include <wtf/text/WTFString.h> - -namespace WebCore { - -static inline SkPaint createPaint() -{ - // The SkCanvas is in RGBA but the shader is expecting BGRA, so we need to - // swizzle our colors when drawing to the SkCanvas. - SkColorMatrix swizzleMatrix; - for (int i = 0; i < 20; ++i) - swizzleMatrix.fMat[i] = 0; - swizzleMatrix.fMat[0 + 5 * 2] = 1; - swizzleMatrix.fMat[1 + 5 * 1] = 1; - swizzleMatrix.fMat[2 + 5 * 0] = 1; - swizzleMatrix.fMat[3 + 5 * 3] = 1; - - SkPaint paint; - paint.setColorFilter(new SkColorMatrixFilter(swizzleMatrix))->unref(); - return paint; -} - -CCHeadsUpDisplayLayerImpl::CCHeadsUpDisplayLayerImpl(int id) - : CCLayerImpl(id) -{ -} - -CCHeadsUpDisplayLayerImpl::~CCHeadsUpDisplayLayerImpl() -{ -} - -void CCHeadsUpDisplayLayerImpl::setFontAtlas(PassOwnPtr<CCFontAtlas> fontAtlas) -{ - m_fontAtlas = fontAtlas; -} - -void CCHeadsUpDisplayLayerImpl::willDraw(CCResourceProvider* resourceProvider) -{ - CCLayerImpl::willDraw(resourceProvider); - - if (!m_hudTexture) - m_hudTexture = CCScopedTexture::create(resourceProvider); - - // FIXME: Scale the HUD by deviceScale to make it more friendly under high DPI. - - if (m_hudTexture->size() != bounds()) - m_hudTexture->free(); - - if (!m_hudTexture->id()) - m_hudTexture->allocate(CCRenderer::ImplPool, bounds(), GraphicsContext3D::RGBA, CCResourceProvider::TextureUsageAny); -} - -void CCHeadsUpDisplayLayerImpl::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData) -{ - if (!m_hudTexture->id()) - return; - - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState()); - - IntRect quadRect(IntPoint(), bounds()); - bool premultipliedAlpha = true; - FloatRect uvRect(0, 0, 1, 1); - bool flipped = false; - quadSink.append(CCTextureDrawQuad::create(sharedQuadState, quadRect, m_hudTexture->id(), premultipliedAlpha, uvRect, flipped), appendQuadsData); -} - -void CCHeadsUpDisplayLayerImpl::updateHudTexture(CCResourceProvider* resourceProvider) -{ - if (!m_hudTexture->id()) - return; - - SkISize canvasSize; - if (m_hudCanvas) - canvasSize = m_hudCanvas->getDeviceSize(); - else - canvasSize.set(0, 0); - - if (canvasSize.fWidth != bounds().width() || canvasSize.fHeight != bounds().height() || !m_hudCanvas) - m_hudCanvas = adoptPtr(skia::CreateBitmapCanvas(bounds().width(), bounds().height(), false /* opaque */)); - - m_hudCanvas->clear(SkColorSetARGB(0, 0, 0, 0)); - drawHudContents(m_hudCanvas.get()); - - const SkBitmap* bitmap = &m_hudCanvas->getDevice()->accessBitmap(false); - SkAutoLockPixels locker(*bitmap); - - IntRect layerRect(IntPoint(), bounds()); - ASSERT(bitmap->config() == SkBitmap::kARGB_8888_Config); - resourceProvider->upload(m_hudTexture->id(), static_cast<const uint8_t*>(bitmap->getPixels()), layerRect, layerRect, IntSize()); -} - -void CCHeadsUpDisplayLayerImpl::didDraw(CCResourceProvider* resourceProvider) -{ - CCLayerImpl::didDraw(resourceProvider); - - if (!m_hudTexture->id()) - return; - - // FIXME: the following assert will not be true when sending resources to a - // parent compositor. We will probably need to hold on to m_hudTexture for - // longer, and have several HUD textures in the pipeline. - ASSERT(!resourceProvider->inUseByConsumer(m_hudTexture->id())); -} - -void CCHeadsUpDisplayLayerImpl::didLoseContext() -{ - m_hudTexture.clear(); -} - -void CCHeadsUpDisplayLayerImpl::drawHudContents(SkCanvas* canvas) -{ - const CCLayerTreeSettings& settings = layerTreeHostImpl()->settings(); - - if (settings.showPlatformLayerTree) { - SkPaint paint = createPaint(); - paint.setColor(SkColorSetARGB(192, 0, 0, 0)); - canvas->drawRect(SkRect::MakeXYWH(0, 0, bounds().width(), bounds().height()), paint); - } - - int fpsCounterHeight = 40; - int fpsCounterTop = 2; - int platformLayerTreeTop; - - if (settings.showFPSCounter) - platformLayerTreeTop = fpsCounterTop + fpsCounterHeight; - else - platformLayerTreeTop = 0; - - if (settings.showFPSCounter) - drawFPSCounter(canvas, layerTreeHostImpl()->fpsCounter(), fpsCounterTop, fpsCounterHeight); - - if (settings.showPlatformLayerTree && m_fontAtlas) { - String layerTree = layerTreeHostImpl()->layerTreeAsText(); - m_fontAtlas->drawText(canvas, createPaint(), layerTree, IntPoint(2, platformLayerTreeTop), bounds()); - } - - if (settings.showDebugRects()) - drawDebugRects(canvas, layerTreeHostImpl()->debugRectHistory()); -} - -void CCHeadsUpDisplayLayerImpl::drawFPSCounter(SkCanvas* canvas, CCFrameRateCounter* fpsCounter, int top, int height) -{ - float textWidth = 170; // so text fits on linux. - float graphWidth = fpsCounter->timeStampHistorySize(); - - // Draw the FPS text. - drawFPSCounterText(canvas, fpsCounter, top, textWidth, height); - - // Draw FPS graph. - const double loFPS = 0; - const double hiFPS = 80; - SkPaint paint = createPaint(); - paint.setColor(SkColorSetRGB(154, 205, 50)); - canvas->drawRect(SkRect::MakeXYWH(2 + textWidth, top, graphWidth, height / 2), paint); - - paint.setColor(SkColorSetRGB(255, 250, 205)); - canvas->drawRect(SkRect::MakeXYWH(2 + textWidth, top + height / 2, graphWidth, height / 2), paint); - - int graphLeft = static_cast<int>(textWidth + 3); - int x = 0; - double h = static_cast<double>(height - 2); - SkPath path; - for (int i = 0; i < fpsCounter->timeStampHistorySize() - 1; ++i) { - int j = i + 1; - double delta = fpsCounter->timeStampOfRecentFrame(j) - fpsCounter->timeStampOfRecentFrame(i); - - // Skip plotting this particular instantaneous frame rate if it is not likely to have been valid. - if (fpsCounter->isBadFrameInterval(delta)) { - x += 1; - continue; - } - - double fps = 1.0 / delta; - - // Clamp the FPS to the range we want to plot visually. - double p = 1 - ((fps - loFPS) / (hiFPS - loFPS)); - if (p < 0) - p = 0; - if (p > 1) - p = 1; - - // Plot this data point. - SkPoint cur = SkPoint::Make(graphLeft + x, 1 + top + p*h); - if (path.isEmpty()) - path.moveTo(cur); - else - path.lineTo(cur); - x += 1; - } - paint.setColor(SK_ColorRED); - paint.setStyle(SkPaint::kStroke_Style); - paint.setStrokeWidth(1); - paint.setAntiAlias(true); - canvas->drawPath(path, paint); -} - -void CCHeadsUpDisplayLayerImpl::drawFPSCounterText(SkCanvas* canvas, CCFrameRateCounter* fpsCounter, int top, int width, int height) -{ - double averageFPS, stdDeviation; - fpsCounter->getAverageFPSAndStandardDeviation(averageFPS, stdDeviation); - - // Draw background. - SkPaint paint = createPaint(); - paint.setColor(SK_ColorBLACK); - canvas->drawRect(SkRect::MakeXYWH(2, top, width, height), paint); - - // Draw FPS text. - if (m_fontAtlas) - m_fontAtlas->drawText(canvas, createPaint(), String::format("FPS: %4.1f +/- %3.1f", averageFPS, stdDeviation), IntPoint(10, height / 3), IntSize(width, height)); -} - -void CCHeadsUpDisplayLayerImpl::drawDebugRects(SkCanvas* canvas, CCDebugRectHistory* debugRectHistory) -{ - const Vector<CCDebugRect>& debugRects = debugRectHistory->debugRects(); - - for (size_t i = 0; i < debugRects.size(); ++i) { - SkColor strokeColor = 0; - SkColor fillColor = 0; - - switch (debugRects[i].type) { - case PaintRectType: - // Paint rects in red - strokeColor = SkColorSetARGB(255, 255, 0, 0); - fillColor = SkColorSetARGB(30, 255, 0, 0); - break; - case PropertyChangedRectType: - // Property-changed rects in blue - strokeColor = SkColorSetARGB(255, 255, 0, 0); - fillColor = SkColorSetARGB(30, 0, 0, 255); - break; - case SurfaceDamageRectType: - // Surface damage rects in yellow-orange - strokeColor = SkColorSetARGB(255, 200, 100, 0); - fillColor = SkColorSetARGB(30, 200, 100, 0); - break; - case ReplicaScreenSpaceRectType: - // Screen space rects in green. - strokeColor = SkColorSetARGB(255, 100, 200, 0); - fillColor = SkColorSetARGB(30, 100, 200, 0); - break; - case ScreenSpaceRectType: - // Screen space rects in purple. - strokeColor = SkColorSetARGB(255, 100, 0, 200); - fillColor = SkColorSetARGB(10, 100, 0, 200); - break; - case OccludingRectType: - // Occluding rects in a reddish color. - strokeColor = SkColorSetARGB(255, 200, 0, 100); - fillColor = SkColorSetARGB(10, 200, 0, 100); - break; - } - - const FloatRect& rect = debugRects[i].rect; - SkRect skRect = SkRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height()); - SkPaint paint = createPaint(); - paint.setColor(fillColor); - canvas->drawRect(skRect, paint); - - paint.setColor(strokeColor); - paint.setStyle(SkPaint::kStroke_Style); - paint.setStrokeWidth(2); - canvas->drawRect(skRect, paint); - } -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.h deleted file mode 100644 index a4dd74183..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCHeadsUpDisplayLayerImpl.h +++ /dev/null @@ -1,77 +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 CCHeadsUpDisplayLayerImpl_h -#define CCHeadsUpDisplayLayerImpl_h - -#include "CCFontAtlas.h" -#include "CCLayerImpl.h" -#include "CCScopedTexture.h" - -class SkCanvas; - -namespace WebCore { - -class CCDebugRectHistory; -class CCFontAtlas; -class CCFrameRateCounter; - -class CCHeadsUpDisplayLayerImpl : public CCLayerImpl { -public: - static PassOwnPtr<CCHeadsUpDisplayLayerImpl> create(int id) - { - return adoptPtr(new CCHeadsUpDisplayLayerImpl(id)); - } - virtual ~CCHeadsUpDisplayLayerImpl(); - - void setFontAtlas(PassOwnPtr<CCFontAtlas>); - - virtual void willDraw(CCResourceProvider*) OVERRIDE; - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) OVERRIDE; - void updateHudTexture(CCResourceProvider*); - virtual void didDraw(CCResourceProvider*) OVERRIDE; - - virtual void didLoseContext() OVERRIDE; - - virtual bool layerIsAlwaysDamaged() const OVERRIDE { return true; } - -private: - explicit CCHeadsUpDisplayLayerImpl(int); - - virtual const char* layerTypeAsString() const OVERRIDE { return "HeadsUpDisplayLayer"; } - - void drawHudContents(SkCanvas*); - void drawFPSCounter(SkCanvas*, CCFrameRateCounter*, int top, int height); - void drawFPSCounterText(SkCanvas*, CCFrameRateCounter*, int top, int width, int height); - void drawDebugRects(SkCanvas*, CCDebugRectHistory*); - - OwnPtr<CCFontAtlas> m_fontAtlas; - OwnPtr<CCScopedTexture> m_hudTexture; - OwnPtr<SkCanvas> m_hudCanvas; -}; - -} - -#endif // CCHeadsUpDisplayLayerImpl_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.cpp deleted file mode 100644 index 11b54b266..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.cpp +++ /dev/null @@ -1,51 +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 "CCIOSurfaceDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCIOSurfaceDrawQuad> CCIOSurfaceDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, const IntSize& ioSurfaceSize, unsigned ioSurfaceTextureId, Orientation orientation) -{ - return adoptPtr(new CCIOSurfaceDrawQuad(sharedQuadState, quadRect, ioSurfaceSize, ioSurfaceTextureId, orientation)); -} - -CCIOSurfaceDrawQuad::CCIOSurfaceDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, const IntSize& ioSurfaceSize, unsigned ioSurfaceTextureId, Orientation orientation) - : CCDrawQuad(sharedQuadState, CCDrawQuad::IOSurfaceContent, quadRect) - , m_ioSurfaceSize(ioSurfaceSize) - , m_ioSurfaceTextureId(ioSurfaceTextureId) - , m_orientation(orientation) -{ -} - -const CCIOSurfaceDrawQuad* CCIOSurfaceDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::IOSurfaceContent); - return static_cast<const CCIOSurfaceDrawQuad*>(quad); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.h deleted file mode 100644 index 6abbed1fc..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceDrawQuad.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 CCIOSurfaceDrawQuad_h -#define CCIOSurfaceDrawQuad_h - -#include "CCDrawQuad.h" -#include "IntSize.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -#pragma pack(push, 4) - -class CCIOSurfaceDrawQuad : public CCDrawQuad { -public: - enum Orientation { - Flipped, - Unflipped - }; - - static PassOwnPtr<CCIOSurfaceDrawQuad> create(const CCSharedQuadState*, const IntRect&, const IntSize& ioSurfaceSize, unsigned ioSurfaceTextureId, Orientation); - - IntSize ioSurfaceSize() const { return m_ioSurfaceSize; } - unsigned ioSurfaceTextureId() const { return m_ioSurfaceTextureId; } - Orientation orientation() const { return m_orientation; } - - static const CCIOSurfaceDrawQuad* materialCast(const CCDrawQuad*); -private: - CCIOSurfaceDrawQuad(const CCSharedQuadState*, const IntRect&, const IntSize& ioSurfaceSize, unsigned ioSurfaceTextureId, Orientation); - - IntSize m_ioSurfaceSize; - unsigned m_ioSurfaceTextureId; - Orientation m_orientation; -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.cpp deleted file mode 100644 index 5241c0bed..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 USE(ACCELERATED_COMPOSITING) - -#include "CCIOSurfaceLayerImpl.h" - -#include "CCGraphicsContext.h" -#include "CCIOSurfaceDrawQuad.h" -#include "CCLayerTreeHostImpl.h" -#include "CCQuadSink.h" -#include "CCRendererGL.h" // For the GLC() macro. -#include "Extensions3D.h" -#include "TextStream.h" -#include <public/WebGraphicsContext3D.h> - -namespace WebCore { - -CCIOSurfaceLayerImpl::CCIOSurfaceLayerImpl(int id) - : CCLayerImpl(id) - , m_ioSurfaceId(0) - , m_ioSurfaceChanged(false) - , m_ioSurfaceTextureId(0) -{ -} - -CCIOSurfaceLayerImpl::~CCIOSurfaceLayerImpl() -{ - if (!m_ioSurfaceTextureId) - return; - - CCGraphicsContext* context = layerTreeHostImpl()->context(); - // FIXME: Implement this path for software compositing. - WebKit::WebGraphicsContext3D* context3d = context->context3D(); - if (context3d) - context3d->deleteTexture(m_ioSurfaceTextureId); -} - -void CCIOSurfaceLayerImpl::willDraw(CCResourceProvider* resourceProvider) -{ - CCLayerImpl::willDraw(resourceProvider); - - if (m_ioSurfaceChanged) { - WebKit::WebGraphicsContext3D* context3d = resourceProvider->graphicsContext3D(); - if (!context3d) { - // FIXME: Implement this path for software compositing. - return; - } - - // FIXME: Do this in a way that we can track memory usage. - if (!m_ioSurfaceTextureId) - m_ioSurfaceTextureId = context3d->createTexture(); - - GLC(context3d, context3d->activeTexture(GraphicsContext3D::TEXTURE0)); - GLC(context3d, context3d->bindTexture(Extensions3D::TEXTURE_RECTANGLE_ARB, m_ioSurfaceTextureId)); - GLC(context3d, context3d->texParameteri(Extensions3D::TEXTURE_RECTANGLE_ARB, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR)); - GLC(context3d, context3d->texParameteri(Extensions3D::TEXTURE_RECTANGLE_ARB, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR)); - GLC(context3d, context3d->texParameteri(Extensions3D::TEXTURE_RECTANGLE_ARB, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE)); - GLC(context3d, context3d->texParameteri(Extensions3D::TEXTURE_RECTANGLE_ARB, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE)); - context3d->texImageIOSurface2DCHROMIUM(Extensions3D::TEXTURE_RECTANGLE_ARB, - m_ioSurfaceSize.width(), - m_ioSurfaceSize.height(), - m_ioSurfaceId, - 0); - // Do not check for error conditions. texImageIOSurface2DCHROMIUM is supposed to hold on to - // the last good IOSurface if the new one is already closed. This is only a possibility - // during live resizing of plugins. However, it seems that this is not sufficient to - // completely guard against garbage being drawn. If this is found to be a significant issue, - // it may be necessary to explicitly tell the embedder when to free the surfaces it has - // allocated. - m_ioSurfaceChanged = false; - } -} - -void CCIOSurfaceLayerImpl::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData) -{ - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState()); - appendDebugBorderQuad(quadSink, sharedQuadState, appendQuadsData); - - IntRect quadRect(IntPoint(), contentBounds()); - quadSink.append(CCIOSurfaceDrawQuad::create(sharedQuadState, quadRect, m_ioSurfaceSize, m_ioSurfaceTextureId, CCIOSurfaceDrawQuad::Flipped), appendQuadsData); -} - -void CCIOSurfaceLayerImpl::dumpLayerProperties(TextStream& ts, int indent) const -{ - writeIndent(ts, indent); - ts << "iosurface id: " << m_ioSurfaceId << " texture id: " << m_ioSurfaceTextureId; - CCLayerImpl::dumpLayerProperties(ts, indent); -} - -void CCIOSurfaceLayerImpl::didLoseContext() -{ - // We don't have a valid texture ID in the new context; however, - // the IOSurface is still valid. - m_ioSurfaceTextureId = 0; - m_ioSurfaceChanged = true; -} - -void CCIOSurfaceLayerImpl::setIOSurfaceProperties(unsigned ioSurfaceId, const IntSize& size) -{ - if (m_ioSurfaceId != ioSurfaceId) - m_ioSurfaceChanged = true; - - m_ioSurfaceId = ioSurfaceId; - m_ioSurfaceSize = size; -} -} - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.h deleted file mode 100644 index fbbc04fbc..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCIOSurfaceLayerImpl.h +++ /dev/null @@ -1,64 +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 CCIOSurfaceLayerImpl_h -#define CCIOSurfaceLayerImpl_h - -#include "CCLayerImpl.h" -#include "IntSize.h" - -namespace WebCore { - -class CCIOSurfaceLayerImpl : public CCLayerImpl { -public: - static PassOwnPtr<CCIOSurfaceLayerImpl> create(int id) - { - return adoptPtr(new CCIOSurfaceLayerImpl(id)); - } - virtual ~CCIOSurfaceLayerImpl(); - - void setIOSurfaceProperties(unsigned ioSurfaceId, const IntSize&); - - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) OVERRIDE; - - virtual void willDraw(CCResourceProvider*) OVERRIDE; - virtual void didLoseContext() OVERRIDE; - - virtual void dumpLayerProperties(TextStream&, int indent) const OVERRIDE; - -private: - explicit CCIOSurfaceLayerImpl(int); - - virtual const char* layerTypeAsString() const OVERRIDE { return "IOSurfaceLayer"; } - - unsigned m_ioSurfaceId; - IntSize m_ioSurfaceSize; - bool m_ioSurfaceChanged; - unsigned m_ioSurfaceTextureId; -}; - -} - -#endif // CCIOSurfaceLayerImpl_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCInputHandler.h b/Source/WebCore/platform/graphics/chromium/cc/CCInputHandler.h deleted file mode 100644 index 13fd568fa..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCInputHandler.h +++ /dev/null @@ -1,98 +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 CCInputHandler_h -#define CCInputHandler_h - -#include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class IntPoint; -class IntSize; - -// The CCInputHandler is a way for the embedders to interact with -// the impl thread side of the compositor implementation. -// -// There is one CCInputHandler for every CCLayerTreeHost. It is -// created on the main thread and used only on the impl thread. -// -// The CCInputHandler is constructed with a CCInputHandlerClient, which is the -// interface by which the handler can manipulate the LayerTree. -class CCInputHandlerClient { - WTF_MAKE_NONCOPYABLE(CCInputHandlerClient); -public: - enum ScrollStatus { ScrollOnMainThread, ScrollStarted, ScrollIgnored }; - enum ScrollInputType { Gesture, Wheel }; - - // Selects a layer to be scrolled at a given point in window coordinates. - // Returns ScrollStarted if the layer at the coordinates can be scrolled, - // ScrollOnMainThread if the scroll event should instead be delegated to the - // main thread, or ScrollIgnored if there is nothing to be scrolled at the - // given coordinates. - virtual ScrollStatus scrollBegin(const IntPoint&, ScrollInputType) = 0; - - // Scroll the selected layer starting at the given window coordinate. If - // there is no room to move the layer in the requested direction, its first - // ancestor layer that can be scrolled will be moved instead. Should only be - // called if scrollBegin() returned ScrollStarted. - virtual void scrollBy(const IntPoint&, const IntSize&) = 0; - - // Stop scrolling the selected layer. Should only be called if scrollBegin() - // returned ScrollStarted. - virtual void scrollEnd() = 0; - - virtual void pinchGestureBegin() = 0; - virtual void pinchGestureUpdate(float magnifyDelta, const IntPoint& anchor) = 0; - virtual void pinchGestureEnd() = 0; - - virtual void startPageScaleAnimation(const IntSize& targetPosition, - bool anchorPoint, - float pageScale, - double startTime, - double duration) = 0; - - // Request another callback to CCInputHandler::animate(). - virtual void scheduleAnimation() = 0; - -protected: - CCInputHandlerClient() { } - virtual ~CCInputHandlerClient() { } -}; - -class CCInputHandler { - WTF_MAKE_NONCOPYABLE(CCInputHandler); -public: - virtual ~CCInputHandler() { } - - virtual void bindToClient(CCInputHandlerClient*) = 0; - virtual void animate(double monotonicTime) = 0; - -protected: - CCInputHandler() { } -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCKeyframedAnimationCurve.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCKeyframedAnimationCurve.cpp deleted file mode 100644 index 790370f4b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCKeyframedAnimationCurve.cpp +++ /dev/null @@ -1,241 +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 "CCKeyframedAnimationCurve.h" - -#include <wtf/OwnPtr.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -namespace { - -template <class Keyframe> -void insertKeyframe(PassOwnPtr<Keyframe> popKeyframe, Vector<OwnPtr<Keyframe> >& keyframes) -{ - OwnPtr<Keyframe> keyframe = popKeyframe; - - // Usually, the keyframes will be added in order, so this loop would be unnecessary and - // we should skip it if possible. - if (!keyframes.isEmpty() && keyframe->time() < keyframes.last()->time()) { - for (size_t i = 0; i < keyframes.size(); ++i) { - if (keyframe->time() < keyframes[i]->time()) { - keyframes.insert(i, keyframe.release()); - return; - } - } - } - - keyframes.append(keyframe.release()); -} - -PassOwnPtr<CCTimingFunction> cloneTimingFunction(const CCTimingFunction* timingFunction) -{ - ASSERT(timingFunction); - OwnPtr<CCAnimationCurve> curve(timingFunction->clone()); - return adoptPtr(static_cast<CCTimingFunction*>(curve.leakPtr())); -} - -} // namespace - -CCKeyframe::CCKeyframe(double time, PassOwnPtr<CCTimingFunction> timingFunction) - : m_time(time) - , m_timingFunction(timingFunction) -{ -} - -CCKeyframe::~CCKeyframe() -{ -} - -double CCKeyframe::time() const -{ - return m_time; -} - -const CCTimingFunction* CCKeyframe::timingFunction() const -{ - return m_timingFunction.get(); -} - -PassOwnPtr<CCFloatKeyframe> CCFloatKeyframe::create(double time, float value, PassOwnPtr<CCTimingFunction> timingFunction) -{ - return adoptPtr(new CCFloatKeyframe(time, value, timingFunction)); -} - -CCFloatKeyframe::CCFloatKeyframe(double time, float value, PassOwnPtr<CCTimingFunction> timingFunction) - : CCKeyframe(time, timingFunction) - , m_value(value) -{ -} - -CCFloatKeyframe::~CCFloatKeyframe() -{ -} - -float CCFloatKeyframe::value() const -{ - return m_value; -} - -PassOwnPtr<CCFloatKeyframe> CCFloatKeyframe::clone() const -{ - return CCFloatKeyframe::create(time(), value(), timingFunction() ? cloneTimingFunction(timingFunction()) : nullptr); -} - -PassOwnPtr<CCTransformKeyframe> CCTransformKeyframe::create(double time, const WebKit::WebTransformOperations& value, PassOwnPtr<CCTimingFunction> timingFunction) -{ - return adoptPtr(new CCTransformKeyframe(time, value, timingFunction)); -} - -CCTransformKeyframe::CCTransformKeyframe(double time, const WebKit::WebTransformOperations& value, PassOwnPtr<CCTimingFunction> timingFunction) - : CCKeyframe(time, timingFunction) - , m_value(value) -{ -} - -CCTransformKeyframe::~CCTransformKeyframe() -{ -} - -const WebKit::WebTransformOperations& CCTransformKeyframe::value() const -{ - return m_value; -} - -PassOwnPtr<CCTransformKeyframe> CCTransformKeyframe::clone() const -{ - return CCTransformKeyframe::create(time(), value(), timingFunction() ? cloneTimingFunction(timingFunction()) : nullptr); -} - -PassOwnPtr<CCKeyframedFloatAnimationCurve> CCKeyframedFloatAnimationCurve::create() -{ - return adoptPtr(new CCKeyframedFloatAnimationCurve); -} - -CCKeyframedFloatAnimationCurve::CCKeyframedFloatAnimationCurve() -{ -} - -CCKeyframedFloatAnimationCurve::~CCKeyframedFloatAnimationCurve() -{ -} - -void CCKeyframedFloatAnimationCurve::addKeyframe(PassOwnPtr<CCFloatKeyframe> keyframe) -{ - insertKeyframe(keyframe, m_keyframes); -} - -double CCKeyframedFloatAnimationCurve::duration() const -{ - return m_keyframes.last()->time() - m_keyframes.first()->time(); -} - -PassOwnPtr<CCAnimationCurve> CCKeyframedFloatAnimationCurve::clone() const -{ - OwnPtr<CCKeyframedFloatAnimationCurve> toReturn(CCKeyframedFloatAnimationCurve::create()); - for (size_t i = 0; i < m_keyframes.size(); ++i) - toReturn->addKeyframe(m_keyframes[i]->clone()); - return toReturn.release(); -} - -float CCKeyframedFloatAnimationCurve::getValue(double t) const -{ - if (t <= m_keyframes.first()->time()) - return m_keyframes.first()->value(); - - if (t >= m_keyframes.last()->time()) - return m_keyframes.last()->value(); - - size_t i = 0; - for (; i < m_keyframes.size() - 1; ++i) { - if (t < m_keyframes[i+1]->time()) - break; - } - - float progress = static_cast<float>((t - m_keyframes[i]->time()) / (m_keyframes[i+1]->time() - m_keyframes[i]->time())); - - if (m_keyframes[i]->timingFunction()) - progress = m_keyframes[i]->timingFunction()->getValue(progress); - - return m_keyframes[i]->value() + (m_keyframes[i+1]->value() - m_keyframes[i]->value()) * progress; -} - -PassOwnPtr<CCKeyframedTransformAnimationCurve> CCKeyframedTransformAnimationCurve::create() -{ - return adoptPtr(new CCKeyframedTransformAnimationCurve); -} - -CCKeyframedTransformAnimationCurve::CCKeyframedTransformAnimationCurve() -{ -} - -CCKeyframedTransformAnimationCurve::~CCKeyframedTransformAnimationCurve() -{ -} - -void CCKeyframedTransformAnimationCurve::addKeyframe(PassOwnPtr<CCTransformKeyframe> keyframe) -{ - insertKeyframe(keyframe, m_keyframes); -} - -double CCKeyframedTransformAnimationCurve::duration() const -{ - return m_keyframes.last()->time() - m_keyframes.first()->time(); -} - -PassOwnPtr<CCAnimationCurve> CCKeyframedTransformAnimationCurve::clone() const -{ - OwnPtr<CCKeyframedTransformAnimationCurve> toReturn(CCKeyframedTransformAnimationCurve::create()); - for (size_t i = 0; i < m_keyframes.size(); ++i) - toReturn->addKeyframe(m_keyframes[i]->clone()); - return toReturn.release(); -} - -WebTransformationMatrix CCKeyframedTransformAnimationCurve::getValue(double t) const -{ - if (t <= m_keyframes.first()->time()) - return m_keyframes.first()->value().apply(); - - if (t >= m_keyframes.last()->time()) - return m_keyframes.last()->value().apply(); - - size_t i = 0; - for (; i < m_keyframes.size() - 1; ++i) { - if (t < m_keyframes[i+1]->time()) - break; - } - - double progress = (t - m_keyframes[i]->time()) / (m_keyframes[i+1]->time() - m_keyframes[i]->time()); - - if (m_keyframes[i]->timingFunction()) - progress = m_keyframes[i]->timingFunction()->getValue(progress); - - return m_keyframes[i+1]->value().blend(m_keyframes[i]->value(), progress); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCKeyframedAnimationCurve.h b/Source/WebCore/platform/graphics/chromium/cc/CCKeyframedAnimationCurve.h deleted file mode 100644 index 1cad60435..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCKeyframedAnimationCurve.h +++ /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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCKeyframedAnimationCurve_h -#define CCKeyframedAnimationCurve_h - -#include "CCAnimationCurve.h" -#include "CCTimingFunction.h" -#include <public/WebTransformOperations.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { - -class CCKeyframe { -public: - double time() const; - const CCTimingFunction* timingFunction() const; - -protected: - CCKeyframe(double time, PassOwnPtr<CCTimingFunction>); - virtual ~CCKeyframe(); - -private: - double m_time; - OwnPtr<CCTimingFunction> m_timingFunction; -}; - -class CCFloatKeyframe : public CCKeyframe { -public: - static PassOwnPtr<CCFloatKeyframe> create(double time, float value, PassOwnPtr<CCTimingFunction>); - virtual ~CCFloatKeyframe(); - - float value() const; - - PassOwnPtr<CCFloatKeyframe> clone() const; - -private: - CCFloatKeyframe(double time, float value, PassOwnPtr<CCTimingFunction>); - - float m_value; -}; - -class CCTransformKeyframe : public CCKeyframe { -public: - static PassOwnPtr<CCTransformKeyframe> create(double time, const WebKit::WebTransformOperations& value, PassOwnPtr<CCTimingFunction>); - virtual ~CCTransformKeyframe(); - - const WebKit::WebTransformOperations& value() const; - - PassOwnPtr<CCTransformKeyframe> clone() const; - -private: - CCTransformKeyframe(double time, const WebKit::WebTransformOperations& value, PassOwnPtr<CCTimingFunction>); - - WebKit::WebTransformOperations m_value; -}; - -class CCKeyframedFloatAnimationCurve : public CCFloatAnimationCurve { -public: - // It is required that the keyframes be sorted by time. - static PassOwnPtr<CCKeyframedFloatAnimationCurve> create(); - - virtual ~CCKeyframedFloatAnimationCurve(); - - void addKeyframe(PassOwnPtr<CCFloatKeyframe>); - - // CCAnimationCurve implementation - virtual double duration() const OVERRIDE; - virtual PassOwnPtr<CCAnimationCurve> clone() const OVERRIDE; - - // CCFloatAnimationCurve implementation - virtual float getValue(double t) const OVERRIDE; - -private: - CCKeyframedFloatAnimationCurve(); - - // Always sorted in order of increasing time. No two keyframes have the - // same time. - Vector<OwnPtr<CCFloatKeyframe> > m_keyframes; -}; - -class CCKeyframedTransformAnimationCurve : public CCTransformAnimationCurve { -public: - // It is required that the keyframes be sorted by time. - static PassOwnPtr<CCKeyframedTransformAnimationCurve> create(); - - virtual ~CCKeyframedTransformAnimationCurve(); - - void addKeyframe(PassOwnPtr<CCTransformKeyframe>); - - // CCAnimationCurve implementation - virtual double duration() const OVERRIDE; - virtual PassOwnPtr<CCAnimationCurve> clone() const OVERRIDE; - - // CCTransformAnimationCurve implementation - virtual WebKit::WebTransformationMatrix getValue(double t) const OVERRIDE; - -private: - CCKeyframedTransformAnimationCurve(); - - // Always sorted in order of increasing time. No two keyframes have the - // same time. - Vector<OwnPtr<CCTransformKeyframe> > m_keyframes; -}; - -} // namespace WebCore - -#endif // CCKeyframedAnimationCurve_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerAnimationController.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerAnimationController.cpp deleted file mode 100644 index 13b9c0888..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerAnimationController.cpp +++ /dev/null @@ -1,427 +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 "CCLayerAnimationController.h" - -#include "CCActiveAnimation.h" -#include "CCKeyframedAnimationCurve.h" -#include <public/WebTransformationMatrix.h> -#include <wtf/CurrentTime.h> -#include <wtf/HashMap.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -CCLayerAnimationController::CCLayerAnimationController(CCLayerAnimationControllerClient* client) - : m_forceSync(false) - , m_client(client) -{ -} - -CCLayerAnimationController::~CCLayerAnimationController() -{ -} - -PassOwnPtr<CCLayerAnimationController> CCLayerAnimationController::create(CCLayerAnimationControllerClient* client) -{ - return adoptPtr(new CCLayerAnimationController(client)); -} - -void CCLayerAnimationController::pauseAnimation(int animationId, double timeOffset) -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->id() == animationId) - m_activeAnimations[i]->setRunState(CCActiveAnimation::Paused, timeOffset + m_activeAnimations[i]->startTime()); - } -} - -void CCLayerAnimationController::removeAnimation(int animationId) -{ - for (size_t i = 0; i < m_activeAnimations.size();) { - if (m_activeAnimations[i]->id() == animationId) - m_activeAnimations.remove(i); - else - i++; - } -} - -void CCLayerAnimationController::removeAnimation(int animationId, CCActiveAnimation::TargetProperty targetProperty) -{ - for (size_t i = 0; i < m_activeAnimations.size();) { - if (m_activeAnimations[i]->id() == animationId && m_activeAnimations[i]->targetProperty() == targetProperty) - m_activeAnimations.remove(i); - else - i++; - } -} - -// According to render layer backing, these are for testing only. -void CCLayerAnimationController::suspendAnimations(double monotonicTime) -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (!m_activeAnimations[i]->isFinished()) - m_activeAnimations[i]->setRunState(CCActiveAnimation::Paused, monotonicTime); - } -} - -// Looking at GraphicsLayerCA, this appears to be the analog to suspendAnimations, which is for testing. -void CCLayerAnimationController::resumeAnimations(double monotonicTime) -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::Paused) - m_activeAnimations[i]->setRunState(CCActiveAnimation::Running, monotonicTime); - } -} - -// Ensures that the list of active animations on the main thread and the impl thread -// are kept in sync. -void CCLayerAnimationController::pushAnimationUpdatesTo(CCLayerAnimationController* controllerImpl) -{ - if (m_forceSync) { - replaceImplThreadAnimations(controllerImpl); - m_forceSync = false; - } else { - purgeAnimationsMarkedForDeletion(); - pushNewAnimationsToImplThread(controllerImpl); - - // Remove finished impl side animations only after pushing, - // and only after the animations are deleted on the main thread - // this insures we will never push an animation twice. - removeAnimationsCompletedOnMainThread(controllerImpl); - - pushPropertiesToImplThread(controllerImpl); - } -} - -void CCLayerAnimationController::animate(double monotonicTime, CCAnimationEventsVector* events) -{ - startAnimationsWaitingForNextTick(monotonicTime, events); - startAnimationsWaitingForStartTime(monotonicTime, events); - startAnimationsWaitingForTargetAvailability(monotonicTime, events); - resolveConflicts(monotonicTime); - tickAnimations(monotonicTime); - markAnimationsForDeletion(monotonicTime, events); - startAnimationsWaitingForTargetAvailability(monotonicTime, events); -} - -void CCLayerAnimationController::addAnimation(PassOwnPtr<CCActiveAnimation> animation) -{ - m_activeAnimations.append(animation); -} - -CCActiveAnimation* CCLayerAnimationController::getActiveAnimation(int groupId, CCActiveAnimation::TargetProperty targetProperty) const -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) - if (m_activeAnimations[i]->group() == groupId && m_activeAnimations[i]->targetProperty() == targetProperty) - return m_activeAnimations[i].get(); - return 0; -} - -CCActiveAnimation* CCLayerAnimationController::getActiveAnimation(CCActiveAnimation::TargetProperty targetProperty) const -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - size_t index = m_activeAnimations.size() - i - 1; - if (m_activeAnimations[index]->targetProperty() == targetProperty) - return m_activeAnimations[index].get(); - } - return 0; -} - -bool CCLayerAnimationController::hasActiveAnimation() const -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (!m_activeAnimations[i]->isFinished()) - return true; - } - return false; -} - -bool CCLayerAnimationController::isAnimatingProperty(CCActiveAnimation::TargetProperty targetProperty) const -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() != CCActiveAnimation::Finished && m_activeAnimations[i]->runState() != CCActiveAnimation::Aborted && m_activeAnimations[i]->targetProperty() == targetProperty) - return true; - } - return false; -} - -void CCLayerAnimationController::notifyAnimationStarted(const CCAnimationEvent& event) -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->group() == event.groupId && m_activeAnimations[i]->targetProperty() == event.targetProperty && m_activeAnimations[i]->needsSynchronizedStartTime()) { - m_activeAnimations[i]->setNeedsSynchronizedStartTime(false); - m_activeAnimations[i]->setStartTime(event.monotonicTime); - return; - } - } -} - -void CCLayerAnimationController::setClient(CCLayerAnimationControllerClient* client) -{ - m_client = client; -} - -void CCLayerAnimationController::pushNewAnimationsToImplThread(CCLayerAnimationController* controllerImpl) const -{ - // Any new animations owned by the main thread's controller are cloned and adde to the impl thread's controller. - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - // If the animation is already running on the impl thread, there is no need to copy it over. - if (controllerImpl->getActiveAnimation(m_activeAnimations[i]->group(), m_activeAnimations[i]->targetProperty())) - continue; - - // If the animation is not running on the impl thread, it does not necessarily mean that it needs - // to be copied over and started; it may have already finished. In this case, the impl thread animation - // will have already notified that it has started and the main thread animation will no longer need - // a synchronized start time. - if (!m_activeAnimations[i]->needsSynchronizedStartTime()) - continue; - - // The new animation should be set to run as soon as possible. - CCActiveAnimation::RunState initialRunState = CCActiveAnimation::WaitingForTargetAvailability; - double startTime = 0; - OwnPtr<CCActiveAnimation> toAdd(m_activeAnimations[i]->cloneAndInitialize(CCActiveAnimation::ControllingInstance, initialRunState, startTime)); - ASSERT(!toAdd->needsSynchronizedStartTime()); - controllerImpl->addAnimation(toAdd.release()); - } -} - -void CCLayerAnimationController::removeAnimationsCompletedOnMainThread(CCLayerAnimationController* controllerImpl) const -{ - // Delete all impl thread animations for which there is no corresponding main thread animation. - // Each iteration, controller->m_activeAnimations.size() is decremented or i is incremented - // guaranteeing progress towards loop termination. - for (size_t i = 0; i < controllerImpl->m_activeAnimations.size();) { - CCActiveAnimation* current = getActiveAnimation(controllerImpl->m_activeAnimations[i]->group(), controllerImpl->m_activeAnimations[i]->targetProperty()); - if (!current) - controllerImpl->m_activeAnimations.remove(i); - else - i++; - } -} - -void CCLayerAnimationController::pushPropertiesToImplThread(CCLayerAnimationController* controllerImpl) const -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - CCActiveAnimation* currentImpl = controllerImpl->getActiveAnimation(m_activeAnimations[i]->group(), m_activeAnimations[i]->targetProperty()); - if (currentImpl) - m_activeAnimations[i]->pushPropertiesTo(currentImpl); - } -} - -void CCLayerAnimationController::startAnimationsWaitingForNextTick(double monotonicTime, CCAnimationEventsVector* events) -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::WaitingForNextTick) { - m_activeAnimations[i]->setRunState(CCActiveAnimation::Running, monotonicTime); - if (!m_activeAnimations[i]->hasSetStartTime()) - m_activeAnimations[i]->setStartTime(monotonicTime); - if (events) - events->append(CCAnimationEvent(CCAnimationEvent::Started, m_client->id(), m_activeAnimations[i]->group(), m_activeAnimations[i]->targetProperty(), monotonicTime)); - } - } -} - -void CCLayerAnimationController::startAnimationsWaitingForStartTime(double monotonicTime, CCAnimationEventsVector* events) -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::WaitingForStartTime && m_activeAnimations[i]->startTime() <= monotonicTime) { - m_activeAnimations[i]->setRunState(CCActiveAnimation::Running, monotonicTime); - if (events) - events->append(CCAnimationEvent(CCAnimationEvent::Started, m_client->id(), m_activeAnimations[i]->group(), m_activeAnimations[i]->targetProperty(), monotonicTime)); - } - } -} - -void CCLayerAnimationController::startAnimationsWaitingForTargetAvailability(double monotonicTime, CCAnimationEventsVector* events) -{ - // First collect running properties. - TargetProperties blockedProperties; - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::Running || m_activeAnimations[i]->runState() == CCActiveAnimation::Finished) - blockedProperties.add(m_activeAnimations[i]->targetProperty()); - } - - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::WaitingForTargetAvailability) { - // Collect all properties for animations with the same group id (they should all also be in the list of animations). - TargetProperties enqueuedProperties; - enqueuedProperties.add(m_activeAnimations[i]->targetProperty()); - for (size_t j = i + 1; j < m_activeAnimations.size(); ++j) { - if (m_activeAnimations[i]->group() == m_activeAnimations[j]->group()) - enqueuedProperties.add(m_activeAnimations[j]->targetProperty()); - } - - // Check to see if intersection of the list of properties affected by the group and the list of currently - // blocked properties is null. In any case, the group's target properties need to be added to the list - // of blocked properties. - bool nullIntersection = true; - for (TargetProperties::iterator pIter = enqueuedProperties.begin(); pIter != enqueuedProperties.end(); ++pIter) { - if (!blockedProperties.add(*pIter).isNewEntry) - nullIntersection = false; - } - - // If the intersection is null, then we are free to start the animations in the group. - if (nullIntersection) { - m_activeAnimations[i]->setRunState(CCActiveAnimation::Running, monotonicTime); - if (!m_activeAnimations[i]->hasSetStartTime()) - m_activeAnimations[i]->setStartTime(monotonicTime); - if (events) - events->append(CCAnimationEvent(CCAnimationEvent::Started, m_client->id(), m_activeAnimations[i]->group(), m_activeAnimations[i]->targetProperty(), monotonicTime)); - for (size_t j = i + 1; j < m_activeAnimations.size(); ++j) { - if (m_activeAnimations[i]->group() == m_activeAnimations[j]->group()) { - m_activeAnimations[j]->setRunState(CCActiveAnimation::Running, monotonicTime); - if (!m_activeAnimations[j]->hasSetStartTime()) - m_activeAnimations[j]->setStartTime(monotonicTime); - } - } - } - } - } -} - -void CCLayerAnimationController::resolveConflicts(double monotonicTime) -{ - // Find any animations that are animating the same property and resolve the - // confict. We could eventually blend, but for now we'll just abort the - // previous animation (where 'previous' means: (1) has a prior start time or - // (2) has an equal start time, but was added to the queue earlier, i.e., - // has a lower index in m_activeAnimations). - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::Running) { - for (size_t j = i + 1; j < m_activeAnimations.size(); ++j) { - if (m_activeAnimations[j]->runState() == CCActiveAnimation::Running && m_activeAnimations[i]->targetProperty() == m_activeAnimations[j]->targetProperty()) { - if (m_activeAnimations[i]->startTime() > m_activeAnimations[j]->startTime()) - m_activeAnimations[j]->setRunState(CCActiveAnimation::Aborted, monotonicTime); - else - m_activeAnimations[i]->setRunState(CCActiveAnimation::Aborted, monotonicTime); - } - } - } - } -} - -void CCLayerAnimationController::markAnimationsForDeletion(double monotonicTime, CCAnimationEventsVector* events) -{ - for (size_t i = 0; i < m_activeAnimations.size(); i++) { - int groupId = m_activeAnimations[i]->group(); - bool allAnimsWithSameIdAreFinished = false; - // If an animation is finished, and not already marked for deletion, - // Find out if all other animations in the same group are also finished. - if (m_activeAnimations[i]->isFinished()) { - allAnimsWithSameIdAreFinished = true; - for (size_t j = 0; j < m_activeAnimations.size(); ++j) { - if (groupId == m_activeAnimations[j]->group() && !m_activeAnimations[j]->isFinished()) { - allAnimsWithSameIdAreFinished = false; - break; - } - } - } - if (allAnimsWithSameIdAreFinished) { - // We now need to remove all animations with the same group id as groupId - // (and send along animation finished notifications, if necessary). - for (size_t j = i; j < m_activeAnimations.size(); j++) { - if (groupId == m_activeAnimations[j]->group()) { - if (events) - events->append(CCAnimationEvent(CCAnimationEvent::Finished, m_client->id(), m_activeAnimations[j]->group(), m_activeAnimations[j]->targetProperty(), monotonicTime)); - m_activeAnimations[j]->setRunState(CCActiveAnimation::WaitingForDeletion, monotonicTime); - } - } - } - } -} - -void CCLayerAnimationController::purgeAnimationsMarkedForDeletion() -{ - for (size_t i = 0; i < m_activeAnimations.size();) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::WaitingForDeletion) - m_activeAnimations.remove(i); - else - i++; - } -} - -void CCLayerAnimationController::replaceImplThreadAnimations(CCLayerAnimationController* controllerImpl) const -{ - controllerImpl->m_activeAnimations.clear(); - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - OwnPtr<CCActiveAnimation> toAdd; - if (m_activeAnimations[i]->needsSynchronizedStartTime()) { - // We haven't received an animation started notification yet, so it - // is important that we add it in a 'waiting' and not 'running' state. - CCActiveAnimation::RunState initialRunState = CCActiveAnimation::WaitingForTargetAvailability; - double startTime = 0; - toAdd = m_activeAnimations[i]->cloneAndInitialize(CCActiveAnimation::ControllingInstance, initialRunState, startTime); - } else - toAdd = m_activeAnimations[i]->clone(CCActiveAnimation::ControllingInstance); - - controllerImpl->addAnimation(toAdd.release()); - } -} - -void CCLayerAnimationController::tickAnimations(double monotonicTime) -{ - for (size_t i = 0; i < m_activeAnimations.size(); ++i) { - if (m_activeAnimations[i]->runState() == CCActiveAnimation::Running || m_activeAnimations[i]->runState() == CCActiveAnimation::Paused) { - double trimmed = m_activeAnimations[i]->trimTimeToCurrentIteration(monotonicTime); - - // Animation assumes its initial value until it gets the synchronized start time - // from the impl thread and can start ticking. - if (m_activeAnimations[i]->needsSynchronizedStartTime()) - trimmed = 0; - - switch (m_activeAnimations[i]->targetProperty()) { - - case CCActiveAnimation::Transform: { - const CCTransformAnimationCurve* transformAnimationCurve = m_activeAnimations[i]->curve()->toTransformAnimationCurve(); - const WebTransformationMatrix matrix = transformAnimationCurve->getValue(trimmed); - if (m_activeAnimations[i]->isFinishedAt(monotonicTime)) - m_activeAnimations[i]->setRunState(CCActiveAnimation::Finished, monotonicTime); - - m_client->setTransformFromAnimation(matrix); - break; - } - - case CCActiveAnimation::Opacity: { - const CCFloatAnimationCurve* floatAnimationCurve = m_activeAnimations[i]->curve()->toFloatAnimationCurve(); - const float opacity = floatAnimationCurve->getValue(trimmed); - if (m_activeAnimations[i]->isFinishedAt(monotonicTime)) - m_activeAnimations[i]->setRunState(CCActiveAnimation::Finished, monotonicTime); - - m_client->setOpacityFromAnimation(opacity); - break; - } - - // Do nothing for sentinel value. - case CCActiveAnimation::TargetPropertyEnumSize: - ASSERT_NOT_REACHED(); - - } - } - } -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerAnimationController.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerAnimationController.h deleted file mode 100644 index 343597016..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerAnimationController.h +++ /dev/null @@ -1,132 +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 CCLayerAnimationController_h -#define CCLayerAnimationController_h - -#include "CCAnimationEvents.h" - -#include <wtf/HashSet.h> -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> - -namespace WebKit { -class WebTransformationMatrix; -} - -namespace WebCore { - -class Animation; -class IntSize; -class KeyframeValueList; - -class CCLayerAnimationControllerClient { -public: - virtual ~CCLayerAnimationControllerClient() { } - - virtual int id() const = 0; - virtual void setOpacityFromAnimation(float) = 0; - virtual float opacity() const = 0; - virtual void setTransformFromAnimation(const WebKit::WebTransformationMatrix&) = 0; - virtual const WebKit::WebTransformationMatrix& transform() const = 0; -}; - -class CCLayerAnimationController { - WTF_MAKE_NONCOPYABLE(CCLayerAnimationController); -public: - static PassOwnPtr<CCLayerAnimationController> create(CCLayerAnimationControllerClient*); - - virtual ~CCLayerAnimationController(); - - // These methods are virtual for testing. - virtual void addAnimation(PassOwnPtr<CCActiveAnimation>); - virtual void pauseAnimation(int animationId, double timeOffset); - virtual void removeAnimation(int animationId); - virtual void removeAnimation(int animationId, CCActiveAnimation::TargetProperty); - virtual void suspendAnimations(double monotonicTime); - virtual void resumeAnimations(double monotonicTime); - - // Ensures that the list of active animations on the main thread and the impl thread - // are kept in sync. This function does not take ownership of the impl thread controller. - virtual void pushAnimationUpdatesTo(CCLayerAnimationController*); - - void animate(double monotonicTime, CCAnimationEventsVector*); - - // Returns the active animation in the given group, animating the given property, if such an - // animation exists. - CCActiveAnimation* getActiveAnimation(int groupId, CCActiveAnimation::TargetProperty) const; - - // Returns the active animation animating the given property that is either running, or is - // next to run, if such an animation exists. - CCActiveAnimation* getActiveAnimation(CCActiveAnimation::TargetProperty) const; - - // Returns true if there are any animations that have neither finished nor aborted. - bool hasActiveAnimation() const; - - // Returns true if there is an animation currently animating the given property, or - // if there is an animation scheduled to animate this property in the future. - bool isAnimatingProperty(CCActiveAnimation::TargetProperty) const; - - // This is called in response to an animation being started on the impl thread. This - // function updates the corresponding main thread animation's start time. - void notifyAnimationStarted(const CCAnimationEvent&); - - // If a sync is forced, then the next time animation updates are pushed to the impl - // thread, all animations will be transferred. - void setForceSync() { m_forceSync = true; } - - void setClient(CCLayerAnimationControllerClient*); - -protected: - explicit CCLayerAnimationController(CCLayerAnimationControllerClient*); - -private: - typedef HashSet<int, DefaultHash<int>::Hash, WTF::UnsignedWithZeroKeyHashTraits<int> > TargetProperties; - - void pushNewAnimationsToImplThread(CCLayerAnimationController*) const; - void removeAnimationsCompletedOnMainThread(CCLayerAnimationController*) const; - void pushPropertiesToImplThread(CCLayerAnimationController*) const; - void replaceImplThreadAnimations(CCLayerAnimationController*) const; - - void startAnimationsWaitingForNextTick(double monotonicTime, CCAnimationEventsVector*); - void startAnimationsWaitingForStartTime(double monotonicTime, CCAnimationEventsVector*); - void startAnimationsWaitingForTargetAvailability(double monotonicTime, CCAnimationEventsVector*); - void resolveConflicts(double monotonicTime); - void markAnimationsForDeletion(double monotonicTime, CCAnimationEventsVector*); - void purgeAnimationsMarkedForDeletion(); - - void tickAnimations(double monotonicTime); - - // If this is true, we force a sync to the impl thread. - bool m_forceSync; - - CCLayerAnimationControllerClient* m_client; - Vector<OwnPtr<CCActiveAnimation> > m_activeAnimations; -}; - -} // namespace WebCore - -#endif // CCLayerAnimationController_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerImpl.cpp deleted file mode 100644 index 3800b0876..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerImpl.cpp +++ /dev/null @@ -1,647 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCLayerImpl.h" - -#include "CCDebugBorderDrawQuad.h" -#include "CCLayerSorter.h" -#include "CCMathUtil.h" -#include "CCProxy.h" -#include "CCQuadSink.h" -#include "CCScrollbarAnimationController.h" -#include "TextStream.h" -#include "TraceEvent.h" -#include <wtf/text/WTFString.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -CCLayerImpl::CCLayerImpl(int id) - : m_parent(0) - , m_maskLayerId(-1) - , m_replicaLayerId(-1) - , m_layerId(id) - , m_layerTreeHostImpl(0) - , m_anchorPoint(0.5, 0.5) - , m_anchorPointZ(0) - , m_scrollable(false) - , m_shouldScrollOnMainThread(false) - , m_haveWheelEventHandlers(false) - , m_backgroundColor(0) - , m_doubleSided(true) - , m_layerPropertyChanged(false) - , m_layerSurfacePropertyChanged(false) - , m_masksToBounds(false) - , m_opaque(false) - , m_opacity(1.0) - , m_preserves3D(false) - , m_useParentBackfaceVisibility(false) - , m_drawCheckerboardForMissingTiles(false) - , m_useLCDText(false) - , m_drawsContent(false) - , m_forceRenderSurface(false) - , m_isContainerForFixedPositionLayers(false) - , m_fixedToContainerLayer(false) - , m_pageScaleDelta(1) - , m_renderTarget(0) - , m_drawDepth(0) - , m_drawOpacity(0) - , m_drawOpacityIsAnimating(false) - , m_debugBorderColor(0) - , m_debugBorderWidth(0) - , m_drawTransformIsAnimating(false) - , m_screenSpaceTransformIsAnimating(false) -#ifndef NDEBUG - , m_betweenWillDrawAndDidDraw(false) -#endif - , m_layerAnimationController(CCLayerAnimationController::create(this)) -{ - ASSERT(CCProxy::isImplThread()); - ASSERT(m_layerId > 0); -} - -CCLayerImpl::~CCLayerImpl() -{ - ASSERT(CCProxy::isImplThread()); -#ifndef NDEBUG - ASSERT(!m_betweenWillDrawAndDidDraw); -#endif -} - -void CCLayerImpl::addChild(PassOwnPtr<CCLayerImpl> child) -{ - child->setParent(this); - m_children.append(child); -} - -void CCLayerImpl::removeFromParent() -{ - if (!m_parent) - return; - - CCLayerImpl* parent = m_parent; - m_parent = 0; - - for (size_t i = 0; i < parent->m_children.size(); ++i) { - if (parent->m_children[i].get() == this) { - parent->m_children.remove(i); - return; - } - } -} - -void CCLayerImpl::removeAllChildren() -{ - while (m_children.size()) - m_children[0]->removeFromParent(); -} - -void CCLayerImpl::clearChildList() -{ - m_children.clear(); -} - -void CCLayerImpl::createRenderSurface() -{ - ASSERT(!m_renderSurface); - m_renderSurface = adoptPtr(new CCRenderSurface(this)); - setRenderTarget(this); -} - -bool CCLayerImpl::descendantDrawsContent() -{ - for (size_t i = 0; i < m_children.size(); ++i) { - if (m_children[i]->drawsContent() || m_children[i]->descendantDrawsContent()) - return true; - } - return false; -} - -PassOwnPtr<CCSharedQuadState> CCLayerImpl::createSharedQuadState() const -{ - return CCSharedQuadState::create(m_drawTransform, m_visibleContentRect, m_drawableContentRect, m_drawOpacity, m_opaque); -} - -void CCLayerImpl::willDraw(CCResourceProvider*) -{ -#ifndef NDEBUG - // willDraw/didDraw must be matched. - ASSERT(!m_betweenWillDrawAndDidDraw); - m_betweenWillDrawAndDidDraw = true; -#endif -} - -void CCLayerImpl::didDraw(CCResourceProvider*) -{ -#ifndef NDEBUG - ASSERT(m_betweenWillDrawAndDidDraw); - m_betweenWillDrawAndDidDraw = false; -#endif -} - -void CCLayerImpl::appendDebugBorderQuad(CCQuadSink& quadList, const CCSharedQuadState* sharedQuadState, CCAppendQuadsData& appendQuadsData) const -{ - if (!hasDebugBorders()) - return; - - IntRect contentRect(IntPoint(), contentBounds()); - quadList.append(CCDebugBorderDrawQuad::create(sharedQuadState, contentRect, debugBorderColor(), debugBorderWidth()), appendQuadsData); -} - -CCResourceProvider::ResourceId CCLayerImpl::contentsResourceId() const -{ - ASSERT_NOT_REACHED(); - return 0; -} - -void CCLayerImpl::scrollBy(const FloatSize& scroll) -{ - IntSize minDelta = -toSize(m_scrollPosition); - IntSize maxDelta = m_maxScrollPosition - toSize(m_scrollPosition); - // Clamp newDelta so that position + delta stays within scroll bounds. - FloatSize newDelta = (m_scrollDelta + scroll).expandedTo(minDelta).shrunkTo(maxDelta); - - if (m_scrollDelta == newDelta) - return; - - m_scrollDelta = newDelta; - if (m_scrollbarAnimationController) - m_scrollbarAnimationController->updateScrollOffset(this); - noteLayerPropertyChangedForSubtree(); -} - -CCInputHandlerClient::ScrollStatus CCLayerImpl::tryScroll(const IntPoint& viewportPoint, CCInputHandlerClient::ScrollInputType type) const -{ - if (shouldScrollOnMainThread()) { - TRACE_EVENT0("cc", "CCLayerImpl::tryScroll: Failed shouldScrollOnMainThread"); - return CCInputHandlerClient::ScrollOnMainThread; - } - - if (!screenSpaceTransform().isInvertible()) { - TRACE_EVENT0("cc", "CCLayerImpl::tryScroll: Ignored nonInvertibleTransform"); - return CCInputHandlerClient::ScrollIgnored; - } - - if (!nonFastScrollableRegion().isEmpty()) { - bool clipped = false; - FloatPoint hitTestPointInLocalSpace = CCMathUtil::projectPoint(screenSpaceTransform().inverse(), FloatPoint(viewportPoint), clipped); - if (!clipped && nonFastScrollableRegion().contains(flooredIntPoint(hitTestPointInLocalSpace))) { - TRACE_EVENT0("cc", "CCLayerImpl::tryScroll: Failed nonFastScrollableRegion"); - return CCInputHandlerClient::ScrollOnMainThread; - } - } - - if (type == CCInputHandlerClient::Wheel && haveWheelEventHandlers()) { - TRACE_EVENT0("cc", "CCLayerImpl::tryScroll: Failed wheelEventHandlers"); - return CCInputHandlerClient::ScrollOnMainThread; - } - - if (!scrollable()) { - TRACE_EVENT0("cc", "CCLayerImpl::tryScroll: Ignored not scrollable"); - return CCInputHandlerClient::ScrollIgnored; - } - - return CCInputHandlerClient::ScrollStarted; -} - -void CCLayerImpl::writeIndent(TextStream& ts, int indent) -{ - for (int i = 0; i != indent; ++i) - ts << " "; -} - -void CCLayerImpl::dumpLayerProperties(TextStream& ts, int indent) const -{ - writeIndent(ts, indent); - ts << "layer ID: " << m_layerId << "\n"; - - writeIndent(ts, indent); - ts << "bounds: " << bounds().width() << ", " << bounds().height() << "\n"; - - if (m_renderTarget) { - writeIndent(ts, indent); - ts << "renderTarget: " << m_renderTarget->m_layerId << "\n"; - } - - writeIndent(ts, indent); - ts << "drawTransform: "; - ts << m_drawTransform.m11() << ", " << m_drawTransform.m12() << ", " << m_drawTransform.m13() << ", " << m_drawTransform.m14() << " // "; - ts << m_drawTransform.m21() << ", " << m_drawTransform.m22() << ", " << m_drawTransform.m23() << ", " << m_drawTransform.m24() << " // "; - ts << m_drawTransform.m31() << ", " << m_drawTransform.m32() << ", " << m_drawTransform.m33() << ", " << m_drawTransform.m34() << " // "; - ts << m_drawTransform.m41() << ", " << m_drawTransform.m42() << ", " << m_drawTransform.m43() << ", " << m_drawTransform.m44() << "\n"; - - writeIndent(ts, indent); - ts << "drawsContent: " << (m_drawsContent ? "yes" : "no") << "\n"; -} - -void sortLayers(Vector<CCLayerImpl*>::iterator first, Vector<CCLayerImpl*>::iterator end, CCLayerSorter* layerSorter) -{ - TRACE_EVENT0("cc", "CCLayerImpl::sortLayers"); - layerSorter->sort(first, end); -} - -String CCLayerImpl::layerTreeAsText() const -{ - TextStream ts; - dumpLayer(ts, 0); - return ts.release(); -} - -void CCLayerImpl::dumpLayer(TextStream& ts, int indent) const -{ - writeIndent(ts, indent); - ts << layerTypeAsString() << "(" << m_debugName << ")\n"; - dumpLayerProperties(ts, indent+2); - if (m_replicaLayer) { - writeIndent(ts, indent+2); - ts << "Replica:\n"; - m_replicaLayer->dumpLayer(ts, indent+3); - } - if (m_maskLayer) { - writeIndent(ts, indent+2); - ts << "Mask:\n"; - m_maskLayer->dumpLayer(ts, indent+3); - } - for (size_t i = 0; i < m_children.size(); ++i) - m_children[i]->dumpLayer(ts, indent+1); -} - -void CCLayerImpl::setStackingOrderChanged(bool stackingOrderChanged) -{ - // We don't need to store this flag; we only need to track that the change occurred. - if (stackingOrderChanged) - noteLayerPropertyChangedForSubtree(); -} - -bool CCLayerImpl::layerSurfacePropertyChanged() const -{ - if (m_layerSurfacePropertyChanged) - return true; - - // If this layer's surface property hasn't changed, we want to see if - // some layer above us has changed this property. This is done for the - // case when such parent layer does not draw content, and therefore will - // not be traversed by the damage tracker. We need to make sure that - // property change on such layer will be caught by its descendants. - CCLayerImpl* current = this->m_parent; - while (current && !current->m_renderSurface) { - if (current->m_layerSurfacePropertyChanged) - return true; - current = current->m_parent; - } - - return false; -} - -void CCLayerImpl::noteLayerPropertyChangedForSubtree() -{ - m_layerPropertyChanged = true; - noteLayerPropertyChangedForDescendants(); -} - -void CCLayerImpl::noteLayerPropertyChangedForDescendants() -{ - for (size_t i = 0; i < m_children.size(); ++i) - m_children[i]->noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::resetAllChangeTrackingForSubtree() -{ - m_layerPropertyChanged = false; - m_layerSurfacePropertyChanged = false; - - m_updateRect = FloatRect(); - - if (m_renderSurface) - m_renderSurface->resetPropertyChangedFlag(); - - if (m_maskLayer) - m_maskLayer->resetAllChangeTrackingForSubtree(); - - if (m_replicaLayer) - m_replicaLayer->resetAllChangeTrackingForSubtree(); // also resets the replica mask, if it exists. - - for (size_t i = 0; i < m_children.size(); ++i) - m_children[i]->resetAllChangeTrackingForSubtree(); -} - -void CCLayerImpl::setOpacityFromAnimation(float opacity) -{ - setOpacity(opacity); -} - -void CCLayerImpl::setTransformFromAnimation(const WebTransformationMatrix& transform) -{ - setTransform(transform); -} - -void CCLayerImpl::setBounds(const IntSize& bounds) -{ - if (m_bounds == bounds) - return; - - m_bounds = bounds; - - if (masksToBounds()) - noteLayerPropertyChangedForSubtree(); - else - m_layerPropertyChanged = true; -} - -void CCLayerImpl::setMaskLayer(PassOwnPtr<CCLayerImpl> maskLayer) -{ - m_maskLayer = maskLayer; - - int newLayerId = m_maskLayer ? m_maskLayer->id() : -1; - if (newLayerId == m_maskLayerId) - return; - - m_maskLayerId = newLayerId; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setReplicaLayer(PassOwnPtr<CCLayerImpl> replicaLayer) -{ - m_replicaLayer = replicaLayer; - - int newLayerId = m_replicaLayer ? m_replicaLayer->id() : -1; - if (newLayerId == m_replicaLayerId) - return; - - m_replicaLayerId = newLayerId; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setDrawsContent(bool drawsContent) -{ - if (m_drawsContent == drawsContent) - return; - - m_drawsContent = drawsContent; - m_layerPropertyChanged = true; -} - -void CCLayerImpl::setAnchorPoint(const FloatPoint& anchorPoint) -{ - if (m_anchorPoint == anchorPoint) - return; - - m_anchorPoint = anchorPoint; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setAnchorPointZ(float anchorPointZ) -{ - if (m_anchorPointZ == anchorPointZ) - return; - - m_anchorPointZ = anchorPointZ; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setBackgroundColor(SkColor backgroundColor) -{ - if (m_backgroundColor == backgroundColor) - return; - - m_backgroundColor = backgroundColor; - m_layerPropertyChanged = true; -} - -void CCLayerImpl::setFilters(const WebKit::WebFilterOperations& filters) -{ - if (m_filters == filters) - return; - - m_filters = filters; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setBackgroundFilters(const WebKit::WebFilterOperations& backgroundFilters) -{ - if (m_backgroundFilters == backgroundFilters) - return; - - m_backgroundFilters = backgroundFilters; - m_layerPropertyChanged = true; -} - -void CCLayerImpl::setMasksToBounds(bool masksToBounds) -{ - if (m_masksToBounds == masksToBounds) - return; - - m_masksToBounds = masksToBounds; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setOpaque(bool opaque) -{ - if (m_opaque == opaque) - return; - - m_opaque = opaque; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setOpacity(float opacity) -{ - if (m_opacity == opacity) - return; - - m_opacity = opacity; - m_layerSurfacePropertyChanged = true; -} - -bool CCLayerImpl::opacityIsAnimating() const -{ - return m_layerAnimationController->isAnimatingProperty(CCActiveAnimation::Opacity); -} - -void CCLayerImpl::setPosition(const FloatPoint& position) -{ - if (m_position == position) - return; - - m_position = position; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setPreserves3D(bool preserves3D) -{ - if (m_preserves3D == preserves3D) - return; - - m_preserves3D = preserves3D; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setSublayerTransform(const WebTransformationMatrix& sublayerTransform) -{ - if (m_sublayerTransform == sublayerTransform) - return; - - m_sublayerTransform = sublayerTransform; - // sublayer transform does not affect the current layer; it affects only its children. - noteLayerPropertyChangedForDescendants(); -} - -void CCLayerImpl::setTransform(const WebTransformationMatrix& transform) -{ - if (m_transform == transform) - return; - - m_transform = transform; - m_layerSurfacePropertyChanged = true; -} - -bool CCLayerImpl::transformIsAnimating() const -{ - return m_layerAnimationController->isAnimatingProperty(CCActiveAnimation::Transform); -} - -void CCLayerImpl::setDebugBorderColor(SkColor debugBorderColor) -{ - if (m_debugBorderColor == debugBorderColor) - return; - - m_debugBorderColor = debugBorderColor; - m_layerPropertyChanged = true; -} - -void CCLayerImpl::setDebugBorderWidth(float debugBorderWidth) -{ - if (m_debugBorderWidth == debugBorderWidth) - return; - - m_debugBorderWidth = debugBorderWidth; - m_layerPropertyChanged = true; -} - -bool CCLayerImpl::hasDebugBorders() const -{ - return SkColorGetA(m_debugBorderColor) && debugBorderWidth() > 0; -} - -void CCLayerImpl::setContentBounds(const IntSize& contentBounds) -{ - if (m_contentBounds == contentBounds) - return; - - m_contentBounds = contentBounds; - m_layerPropertyChanged = true; -} - -void CCLayerImpl::setScrollPosition(const IntPoint& scrollPosition) -{ - if (m_scrollPosition == scrollPosition) - return; - - m_scrollPosition = scrollPosition; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setScrollDelta(const FloatSize& scrollDelta) -{ - if (m_scrollDelta == scrollDelta) - return; - - m_scrollDelta = scrollDelta; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setPageScaleDelta(float pageScaleDelta) -{ - if (m_pageScaleDelta == pageScaleDelta) - return; - - m_pageScaleDelta = pageScaleDelta; - noteLayerPropertyChangedForSubtree(); -} - -void CCLayerImpl::setDoubleSided(bool doubleSided) -{ - if (m_doubleSided == doubleSided) - return; - - m_doubleSided = doubleSided; - noteLayerPropertyChangedForSubtree(); -} - -Region CCLayerImpl::visibleContentOpaqueRegion() const -{ - if (opaque()) - return visibleContentRect(); - return Region(); -} - -void CCLayerImpl::didLoseContext() -{ -} - -void CCLayerImpl::setMaxScrollPosition(const IntSize& maxScrollPosition) -{ - m_maxScrollPosition = maxScrollPosition; - - if (!m_scrollbarAnimationController) - return; - m_scrollbarAnimationController->updateScrollOffset(this); -} - -CCScrollbarLayerImpl* CCLayerImpl::horizontalScrollbarLayer() const -{ - return m_scrollbarAnimationController ? m_scrollbarAnimationController->horizontalScrollbarLayer() : 0; -} - -void CCLayerImpl::setHorizontalScrollbarLayer(CCScrollbarLayerImpl* scrollbarLayer) -{ - if (!m_scrollbarAnimationController) - m_scrollbarAnimationController = CCScrollbarAnimationController::create(this); - m_scrollbarAnimationController->setHorizontalScrollbarLayer(scrollbarLayer); - m_scrollbarAnimationController->updateScrollOffset(this); -} - -CCScrollbarLayerImpl* CCLayerImpl::verticalScrollbarLayer() const -{ - return m_scrollbarAnimationController ? m_scrollbarAnimationController->verticalScrollbarLayer() : 0; -} - -void CCLayerImpl::setVerticalScrollbarLayer(CCScrollbarLayerImpl* scrollbarLayer) -{ - if (!m_scrollbarAnimationController) - m_scrollbarAnimationController = CCScrollbarAnimationController::create(this); - m_scrollbarAnimationController->setVerticalScrollbarLayer(scrollbarLayer); - m_scrollbarAnimationController->updateScrollOffset(this); -} - -} - - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerImpl.h deleted file mode 100644 index f8ad06701..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerImpl.h +++ /dev/null @@ -1,413 +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 CCLayerImpl_h -#define CCLayerImpl_h - -#include "CCInputHandler.h" -#include "CCLayerAnimationController.h" -#include "CCRenderSurface.h" -#include "CCResourceProvider.h" -#include "CCSharedQuadState.h" -#include "FloatRect.h" -#include "IntRect.h" -#include "Region.h" -#include "SkColor.h" -#include "TextStream.h" -#include <public/WebFilterOperations.h> -#include <public/WebTransformationMatrix.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefCounted.h> -#include <wtf/text/WTFString.h> - -namespace WebCore { - -class CCLayerSorter; -class CCLayerTreeHostImpl; -class CCQuadSink; -class CCRenderer; -class CCScrollbarAnimationController; -class CCScrollbarLayerImpl; -class LayerChromium; - -struct CCAppendQuadsData; - -class CCLayerImpl : public CCLayerAnimationControllerClient { -public: - static PassOwnPtr<CCLayerImpl> create(int id) - { - return adoptPtr(new CCLayerImpl(id)); - } - - virtual ~CCLayerImpl(); - - // CCLayerAnimationControllerClient implementation. - virtual int id() const OVERRIDE { return m_layerId; } - virtual void setOpacityFromAnimation(float) OVERRIDE; - virtual float opacity() const OVERRIDE { return m_opacity; } - virtual void setTransformFromAnimation(const WebKit::WebTransformationMatrix&) OVERRIDE; - virtual const WebKit::WebTransformationMatrix& transform() const OVERRIDE { return m_transform; } - - // Tree structure. - CCLayerImpl* parent() const { return m_parent; } - const Vector<OwnPtr<CCLayerImpl> >& children() const { return m_children; } - void addChild(PassOwnPtr<CCLayerImpl>); - void removeFromParent(); - void removeAllChildren(); - - void setMaskLayer(PassOwnPtr<CCLayerImpl>); - CCLayerImpl* maskLayer() const { return m_maskLayer.get(); } - - void setReplicaLayer(PassOwnPtr<CCLayerImpl>); - CCLayerImpl* replicaLayer() const { return m_replicaLayer.get(); } - - bool hasMask() const { return m_maskLayer; } - bool hasReplica() const { return m_replicaLayer; } - bool replicaHasMask() const { return m_replicaLayer && (m_maskLayer || m_replicaLayer->m_maskLayer); } - - CCLayerTreeHostImpl* layerTreeHostImpl() const { return m_layerTreeHostImpl; } - void setLayerTreeHostImpl(CCLayerTreeHostImpl* hostImpl) { m_layerTreeHostImpl = hostImpl; } - - PassOwnPtr<CCSharedQuadState> createSharedQuadState() const; - // willDraw must be called before appendQuads. If willDraw is called, - // didDraw is guaranteed to be called before another willDraw or before - // the layer is destroyed. To enforce this, any class that overrides - // willDraw/didDraw must call the base class version. - virtual void willDraw(CCResourceProvider*); - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) { } - virtual void didDraw(CCResourceProvider*); - - virtual CCResourceProvider::ResourceId contentsResourceId() const; - - // Returns true if this layer has content to draw. - void setDrawsContent(bool); - bool drawsContent() const { return m_drawsContent; } - - bool forceRenderSurface() const { return m_forceRenderSurface; } - void setForceRenderSurface(bool force) { m_forceRenderSurface = force; } - - // Returns true if any of the layer's descendants has content to draw. - bool descendantDrawsContent(); - - void setAnchorPoint(const FloatPoint&); - const FloatPoint& anchorPoint() const { return m_anchorPoint; } - - void setAnchorPointZ(float); - float anchorPointZ() const { return m_anchorPointZ; } - - void setBackgroundColor(SkColor); - SkColor backgroundColor() const { return m_backgroundColor; } - - void setFilters(const WebKit::WebFilterOperations&); - const WebKit::WebFilterOperations& filters() const { return m_filters; } - - void setBackgroundFilters(const WebKit::WebFilterOperations&); - const WebKit::WebFilterOperations& backgroundFilters() const { return m_backgroundFilters; } - - void setMasksToBounds(bool); - bool masksToBounds() const { return m_masksToBounds; } - - void setOpaque(bool); - bool opaque() const { return m_opaque; } - - void setOpacity(float); - bool opacityIsAnimating() const; - - void setPosition(const FloatPoint&); - const FloatPoint& position() const { return m_position; } - - void setIsContainerForFixedPositionLayers(bool isContainerForFixedPositionLayers) { m_isContainerForFixedPositionLayers = isContainerForFixedPositionLayers; } - bool isContainerForFixedPositionLayers() const { return m_isContainerForFixedPositionLayers; } - - void setFixedToContainerLayer(bool fixedToContainerLayer = true) { m_fixedToContainerLayer = fixedToContainerLayer;} - bool fixedToContainerLayer() const { return m_fixedToContainerLayer; } - - void setPreserves3D(bool); - bool preserves3D() const { return m_preserves3D; } - - void setUseParentBackfaceVisibility(bool useParentBackfaceVisibility) { m_useParentBackfaceVisibility = useParentBackfaceVisibility; } - bool useParentBackfaceVisibility() const { return m_useParentBackfaceVisibility; } - - void setUseLCDText(bool useLCDText) { m_useLCDText = useLCDText; } - bool useLCDText() const { return m_useLCDText; } - - void setSublayerTransform(const WebKit::WebTransformationMatrix&); - const WebKit::WebTransformationMatrix& sublayerTransform() const { return m_sublayerTransform; } - - // Debug layer border - visual effect only, do not change geometry/clipping/etc. - void setDebugBorderColor(SkColor); - SkColor debugBorderColor() const { return m_debugBorderColor; } - void setDebugBorderWidth(float); - float debugBorderWidth() const { return m_debugBorderWidth; } - bool hasDebugBorders() const; - - // Debug layer name. - void setDebugName(const String& debugName) { m_debugName = debugName; } - String debugName() const { return m_debugName; } - - CCRenderSurface* renderSurface() const { return m_renderSurface.get(); } - void createRenderSurface(); - void clearRenderSurface() { m_renderSurface.clear(); } - - float drawOpacity() const { return m_drawOpacity; } - void setDrawOpacity(float opacity) { m_drawOpacity = opacity; } - - bool drawOpacityIsAnimating() const { return m_drawOpacityIsAnimating; } - void setDrawOpacityIsAnimating(bool drawOpacityIsAnimating) { m_drawOpacityIsAnimating = drawOpacityIsAnimating; } - - CCLayerImpl* renderTarget() const { ASSERT(!m_renderTarget || m_renderTarget->renderSurface()); return m_renderTarget; } - void setRenderTarget(CCLayerImpl* target) { m_renderTarget = target; } - - void setBounds(const IntSize&); - const IntSize& bounds() const { return m_bounds; } - - const IntSize& contentBounds() const { return m_contentBounds; } - void setContentBounds(const IntSize&); - - const IntPoint& scrollPosition() const { return m_scrollPosition; } - void setScrollPosition(const IntPoint&); - - const IntSize& maxScrollPosition() const {return m_maxScrollPosition; } - void setMaxScrollPosition(const IntSize&); - - const FloatSize& scrollDelta() const { return m_scrollDelta; } - void setScrollDelta(const FloatSize&); - - float pageScaleDelta() const { return m_pageScaleDelta; } - void setPageScaleDelta(float); - - const IntSize& sentScrollDelta() const { return m_sentScrollDelta; } - void setSentScrollDelta(const IntSize& sentScrollDelta) { m_sentScrollDelta = sentScrollDelta; } - - void scrollBy(const FloatSize& scroll); - - bool scrollable() const { return m_scrollable; } - void setScrollable(bool scrollable) { m_scrollable = scrollable; } - - bool shouldScrollOnMainThread() const { return m_shouldScrollOnMainThread; } - void setShouldScrollOnMainThread(bool shouldScrollOnMainThread) { m_shouldScrollOnMainThread = shouldScrollOnMainThread; } - - bool haveWheelEventHandlers() const { return m_haveWheelEventHandlers; } - void setHaveWheelEventHandlers(bool haveWheelEventHandlers) { m_haveWheelEventHandlers = haveWheelEventHandlers; } - - const Region& nonFastScrollableRegion() const { return m_nonFastScrollableRegion; } - void setNonFastScrollableRegion(const Region& region) { m_nonFastScrollableRegion = region; } - - void setDrawCheckerboardForMissingTiles(bool checkerboard) { m_drawCheckerboardForMissingTiles = checkerboard; } - bool drawCheckerboardForMissingTiles() const { return m_drawCheckerboardForMissingTiles; } - - CCInputHandlerClient::ScrollStatus tryScroll(const IntPoint& viewportPoint, CCInputHandlerClient::ScrollInputType) const; - - const IntRect& visibleContentRect() const { return m_visibleContentRect; } - void setVisibleContentRect(const IntRect& visibleContentRect) { m_visibleContentRect = visibleContentRect; } - - bool doubleSided() const { return m_doubleSided; } - void setDoubleSided(bool); - - void setTransform(const WebKit::WebTransformationMatrix&); - bool transformIsAnimating() const; - - const WebKit::WebTransformationMatrix& drawTransform() const { return m_drawTransform; } - void setDrawTransform(const WebKit::WebTransformationMatrix& matrix) { m_drawTransform = matrix; } - const WebKit::WebTransformationMatrix& screenSpaceTransform() const { return m_screenSpaceTransform; } - void setScreenSpaceTransform(const WebKit::WebTransformationMatrix& matrix) { m_screenSpaceTransform = matrix; } - - bool drawTransformIsAnimating() const { return m_drawTransformIsAnimating; } - void setDrawTransformIsAnimating(bool animating) { m_drawTransformIsAnimating = animating; } - bool screenSpaceTransformIsAnimating() const { return m_screenSpaceTransformIsAnimating; } - void setScreenSpaceTransformIsAnimating(bool animating) { m_screenSpaceTransformIsAnimating = animating; } - - const IntRect& drawableContentRect() const { return m_drawableContentRect; } - void setDrawableContentRect(const IntRect& rect) { m_drawableContentRect = rect; } - const FloatRect& updateRect() const { return m_updateRect; } - void setUpdateRect(const FloatRect& updateRect) { m_updateRect = updateRect; } - - String layerTreeAsText() const; - - void setStackingOrderChanged(bool); - - bool layerPropertyChanged() const { return m_layerPropertyChanged || layerIsAlwaysDamaged(); } - bool layerSurfacePropertyChanged() const; - - void resetAllChangeTrackingForSubtree(); - - virtual bool layerIsAlwaysDamaged() const { return false; } - - CCLayerAnimationController* layerAnimationController() { return m_layerAnimationController.get(); } - - virtual Region visibleContentOpaqueRegion() const; - - // Indicates that the context previously used to render this layer - // was lost and that a new one has been created. Won't be called - // until the new context has been created successfully. - virtual void didLoseContext(); - - CCScrollbarAnimationController* scrollbarAnimationController() const { return m_scrollbarAnimationController.get(); } - - CCScrollbarLayerImpl* horizontalScrollbarLayer() const; - void setHorizontalScrollbarLayer(CCScrollbarLayerImpl*); - - CCScrollbarLayerImpl* verticalScrollbarLayer() const; - void setVerticalScrollbarLayer(CCScrollbarLayerImpl*); - -protected: - explicit CCLayerImpl(int); - - void appendDebugBorderQuad(CCQuadSink&, const CCSharedQuadState*, CCAppendQuadsData&) const; - - virtual void dumpLayerProperties(TextStream&, int indent) const; - static void writeIndent(TextStream&, int indent); - -private: - void setParent(CCLayerImpl* parent) { m_parent = parent; } - friend class TreeSynchronizer; - void clearChildList(); // Warning: This does not preserve tree structure invariants and so is only exposed to the tree synchronizer. - - void noteLayerPropertyChangedForSubtree(); - - // Note carefully this does not affect the current layer. - void noteLayerPropertyChangedForDescendants(); - - virtual const char* layerTypeAsString() const { return "LayerChromium"; } - - void dumpLayer(TextStream&, int indent) const; - - // Properties internal to CCLayerImpl - CCLayerImpl* m_parent; - Vector<OwnPtr<CCLayerImpl> > m_children; - // m_maskLayer can be temporarily stolen during tree sync, we need this ID to confirm newly assigned layer is still the previous one - int m_maskLayerId; - OwnPtr<CCLayerImpl> m_maskLayer; - int m_replicaLayerId; // ditto - OwnPtr<CCLayerImpl> m_replicaLayer; - int m_layerId; - CCLayerTreeHostImpl* m_layerTreeHostImpl; - - // Properties synchronized from the associated LayerChromium. - FloatPoint m_anchorPoint; - float m_anchorPointZ; - IntSize m_bounds; - IntSize m_contentBounds; - IntPoint m_scrollPosition; - bool m_scrollable; - bool m_shouldScrollOnMainThread; - bool m_haveWheelEventHandlers; - Region m_nonFastScrollableRegion; - SkColor m_backgroundColor; - - // Whether the "back" of this layer should draw. - bool m_doubleSided; - - // Tracks if drawing-related properties have changed since last redraw. - bool m_layerPropertyChanged; - - // Indicates that a property has changed on this layer that would not - // affect the pixels on its target surface, but would require redrawing - // but would require redrawing the targetSurface onto its ancestor targetSurface. - // For layers that do not own a surface this flag acts as m_layerPropertyChanged. - bool m_layerSurfacePropertyChanged; - - // Uses layer's content space. - IntRect m_visibleContentRect; - bool m_masksToBounds; - bool m_opaque; - float m_opacity; - FloatPoint m_position; - bool m_preserves3D; - bool m_useParentBackfaceVisibility; - bool m_drawCheckerboardForMissingTiles; - WebKit::WebTransformationMatrix m_sublayerTransform; - WebKit::WebTransformationMatrix m_transform; - bool m_useLCDText; - - bool m_drawsContent; - bool m_forceRenderSurface; - - // Set for the layer that other layers are fixed to. - bool m_isContainerForFixedPositionLayers; - // This is true if the layer should be fixed to the closest ancestor container. - bool m_fixedToContainerLayer; - - FloatSize m_scrollDelta; - IntSize m_sentScrollDelta; - IntSize m_maxScrollPosition; - float m_pageScaleDelta; - - // The layer whose coordinate space this layer draws into. This can be - // either the same layer (m_renderTarget == this) or an ancestor of this - // layer. - CCLayerImpl* m_renderTarget; - - // The global depth value of the center of the layer. This value is used - // to sort layers from back to front. - float m_drawDepth; - float m_drawOpacity; - bool m_drawOpacityIsAnimating; - - // Debug borders. - SkColor m_debugBorderColor; - float m_debugBorderWidth; - - // Debug layer name. - String m_debugName; - - WebKit::WebFilterOperations m_filters; - WebKit::WebFilterOperations m_backgroundFilters; - - WebKit::WebTransformationMatrix m_drawTransform; - WebKit::WebTransformationMatrix m_screenSpaceTransform; - bool m_drawTransformIsAnimating; - bool m_screenSpaceTransformIsAnimating; - -#ifndef NDEBUG - bool m_betweenWillDrawAndDidDraw; -#endif - - // Render surface associated with this layer. The layer and its descendants - // will render to this surface. - OwnPtr<CCRenderSurface> m_renderSurface; - - // Hierarchical bounding rect containing the layer and its descendants. - // Uses target surface's space. - IntRect m_drawableContentRect; - - // Rect indicating what was repainted/updated during update. - // Note that plugin layers bypass this and leave it empty. - // Uses layer's content space. - FloatRect m_updateRect; - - // Manages animations for this layer. - OwnPtr<CCLayerAnimationController> m_layerAnimationController; - - // Manages scrollbars for this layer - OwnPtr<CCScrollbarAnimationController> m_scrollbarAnimationController; -}; - -void sortLayers(Vector<CCLayerImpl*>::iterator first, Vector<CCLayerImpl*>::iterator end, CCLayerSorter*); - -} - -#endif // CCLayerImpl_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerIterator.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerIterator.cpp deleted file mode 100644 index bb5929f0f..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerIterator.cpp +++ /dev/null @@ -1,170 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCLayerIterator.h" - -#include "CCLayerImpl.h" -#include "CCRenderSurface.h" -#include "LayerChromium.h" -#include "RenderSurfaceChromium.h" - -namespace WebCore { - -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> -void CCLayerIteratorActions::BackToFront::begin(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>& it) -{ - it.m_targetRenderSurfaceLayerIndex = 0; - it.m_currentLayerIndex = CCLayerIteratorValue::LayerIndexRepresentingTargetRenderSurface; - - m_highestTargetRenderSurfaceLayer = 0; -} - -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> -void CCLayerIteratorActions::BackToFront::end(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>& it) -{ - it.m_targetRenderSurfaceLayerIndex = CCLayerIteratorValue::InvalidTargetRenderSurfaceLayerIndex; - it.m_currentLayerIndex = 0; -} - -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> -void CCLayerIteratorActions::BackToFront::next(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>& it) -{ - // If the current layer has a RS, move to its layer list. Otherwise, visit the next layer in the current RS layer list. - if (it.currentLayerRepresentsContributingRenderSurface()) { - // Save our position in the childLayer list for the RenderSurface, then jump to the next RenderSurface. Save where we - // came from in the next RenderSurface so we can get back to it. - it.targetRenderSurface()->m_currentLayerIndexHistory = it.m_currentLayerIndex; - int previousTargetRenderSurfaceLayer = it.m_targetRenderSurfaceLayerIndex; - - it.m_targetRenderSurfaceLayerIndex = ++m_highestTargetRenderSurfaceLayer; - it.m_currentLayerIndex = CCLayerIteratorValue::LayerIndexRepresentingTargetRenderSurface; - - it.targetRenderSurface()->m_targetRenderSurfaceLayerIndexHistory = previousTargetRenderSurfaceLayer; - } else { - ++it.m_currentLayerIndex; - - int targetRenderSurfaceNumChildren = it.targetRenderSurfaceChildren().size(); - while (it.m_currentLayerIndex == targetRenderSurfaceNumChildren) { - // Jump back to the previous RenderSurface, and get back the position where we were in that list, and move to the next position there. - if (!it.m_targetRenderSurfaceLayerIndex) { - // End of the list - it.m_targetRenderSurfaceLayerIndex = CCLayerIteratorValue::InvalidTargetRenderSurfaceLayerIndex; - it.m_currentLayerIndex = 0; - return; - } - it.m_targetRenderSurfaceLayerIndex = it.targetRenderSurface()->m_targetRenderSurfaceLayerIndexHistory; - it.m_currentLayerIndex = it.targetRenderSurface()->m_currentLayerIndexHistory + 1; - - targetRenderSurfaceNumChildren = it.targetRenderSurfaceChildren().size(); - } - } -} - -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> -void CCLayerIteratorActions::FrontToBack::begin(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>& it) -{ - it.m_targetRenderSurfaceLayerIndex = 0; - it.m_currentLayerIndex = it.targetRenderSurfaceChildren().size() - 1; - goToHighestInSubtree(it); -} - -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> -void CCLayerIteratorActions::FrontToBack::end(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>& it) -{ - it.m_targetRenderSurfaceLayerIndex = CCLayerIteratorValue::InvalidTargetRenderSurfaceLayerIndex; - it.m_currentLayerIndex = 0; -} - -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> -void CCLayerIteratorActions::FrontToBack::next(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>& it) -{ - // Moves to the previous layer in the current RS layer list. Then we check if the - // new current layer has its own RS, in which case there are things in that RS layer list that are higher, so - // we find the highest layer in that subtree. - // If we move back past the front of the list, we jump up to the previous RS layer list, picking up again where we - // had previously recursed into the current RS layer list. - - if (!it.currentLayerRepresentsTargetRenderSurface()) { - // Subtracting one here will eventually cause the current layer to become that layer - // representing the target render surface. - --it.m_currentLayerIndex; - goToHighestInSubtree(it); - } else { - while (it.currentLayerRepresentsTargetRenderSurface()) { - if (!it.m_targetRenderSurfaceLayerIndex) { - // End of the list - it.m_targetRenderSurfaceLayerIndex = CCLayerIteratorValue::InvalidTargetRenderSurfaceLayerIndex; - it.m_currentLayerIndex = 0; - return; - } - it.m_targetRenderSurfaceLayerIndex = it.targetRenderSurface()->m_targetRenderSurfaceLayerIndexHistory; - it.m_currentLayerIndex = it.targetRenderSurface()->m_currentLayerIndexHistory; - } - } -} - -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> -void CCLayerIteratorActions::FrontToBack::goToHighestInSubtree(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>& it) -{ - if (it.currentLayerRepresentsTargetRenderSurface()) - return; - while (it.currentLayerRepresentsContributingRenderSurface()) { - // Save where we were in the current target surface, move to the next one, and save the target surface that we - // came from there so we can go back to it. - it.targetRenderSurface()->m_currentLayerIndexHistory = it.m_currentLayerIndex; - int previousTargetRenderSurfaceLayer = it.m_targetRenderSurfaceLayerIndex; - - for (LayerType* layer = it.currentLayer(); it.targetRenderSurfaceLayer() != layer; ++it.m_targetRenderSurfaceLayerIndex) { } - it.m_currentLayerIndex = it.targetRenderSurfaceChildren().size() - 1; - - it.targetRenderSurface()->m_targetRenderSurfaceLayerIndexHistory = previousTargetRenderSurfaceLayer; - } -} - -// Declare each of the above functions for LayerChromium and CCLayerImpl classes so that they are linked. -template void CCLayerIteratorActions::BackToFront::begin(CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, BackToFront> &); -template void CCLayerIteratorActions::BackToFront::end(CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, BackToFront>&); -template void CCLayerIteratorActions::BackToFront::next(CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, BackToFront>&); - -template void CCLayerIteratorActions::BackToFront::begin(CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, BackToFront>&); -template void CCLayerIteratorActions::BackToFront::end(CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, BackToFront>&); -template void CCLayerIteratorActions::BackToFront::next(CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, BackToFront>&); - -template void CCLayerIteratorActions::FrontToBack::next(CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, FrontToBack>&); -template void CCLayerIteratorActions::FrontToBack::end(CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, FrontToBack>&); -template void CCLayerIteratorActions::FrontToBack::begin(CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, FrontToBack>&); -template void CCLayerIteratorActions::FrontToBack::goToHighestInSubtree(CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, FrontToBack>&); - -template void CCLayerIteratorActions::FrontToBack::next(CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, FrontToBack>&); -template void CCLayerIteratorActions::FrontToBack::end(CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, FrontToBack>&); -template void CCLayerIteratorActions::FrontToBack::begin(CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, FrontToBack>&); -template void CCLayerIteratorActions::FrontToBack::goToHighestInSubtree(CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, FrontToBack>&); - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerIterator.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerIterator.h deleted file mode 100644 index 9e71c4db2..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerIterator.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCLayerIterator_h -#define CCLayerIterator_h - -#include "CCLayerTreeHostCommon.h" - -#include <wtf/PassOwnPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { - -// These classes provide means to iterate over the RenderSurface-Layer tree. - -// Example code follows, for a tree of LayerChromium/RenderSurfaceChromium objects. See below for details. -// -// void doStuffOnLayers(const Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList) -// { -// typedef CCLayerIterator<LayerChromium, RenderSurfaceChromium, CCLayerIteratorActions::FrontToBack> CCLayerIteratorType; -// -// CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList); -// for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) { -// // Only one of these will be true -// if (it.representsTargetRenderSurface()) -// foo(*it); // *it is a layer representing a target RenderSurface -// if (it.representsContributingRenderSurface()) -// bar(*it); // *it is a layer representing a RenderSurface that contributes to the layer's target RenderSurface -// if (it.representsItself()) -// baz(*it); // *it is a layer representing itself, as it contributes to its own target RenderSurface -// } -// } - -// A RenderSurface R may be referred to in one of two different contexts. One RenderSurface is "current" at any time, for -// whatever operation is being performed. This current surface is referred to as a target surface. For example, when R is -// being painted it would be the target surface. Once R has been painted, its contents may be included into another -// surface S. While S is considered the target surface when it is being painted, R is called a contributing surface -// in this context as it contributes to the content of the target surface S. -// -// The iterator's current position in the tree always points to some layer. The state of the iterator indicates the role of the -// layer, and will be one of the following three states. A single layer L will appear in the iteration process in at least one, -// and possibly all, of these states. -// 1. Representing the target surface: The iterator in this state, pointing at layer L, indicates that the target RenderSurface -// is now the surface owned by L. This will occur exactly once for each RenderSurface in the tree. -// 2. Representing a contributing surface: The iterator in this state, pointing at layer L, refers to the RenderSurface owned -// by L as a contributing surface, without changing the current target RenderSurface. -// 3. Representing itself: The iterator in this state, pointing at layer L, refers to the layer itself, as a child of the -// current target RenderSurface. -// -// The BackToFront iterator will return a layer representing the target surface before returning layers representing themselves -// as children of the current target surface. Whereas the FrontToBack ordering will iterate over children layers of a surface -// before the layer representing the surface as a target surface. -// -// To use the iterators: -// -// Create a stepping iterator and end iterator by calling CCLayerIterator::begin() and CCLayerIterator::end() and passing in the -// list of layers owning target RenderSurfaces. Step through the tree by incrementing the stepping iterator while it is != to -// the end iterator. At each step the iterator knows what the layer is representing, and you can query the iterator to decide -// what actions to perform with the layer given what it represents. - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Non-templated constants -struct CCLayerIteratorValue { - static const int InvalidTargetRenderSurfaceLayerIndex = -1; - // This must be -1 since the iterator action code assumes that this value can be - // reached by subtracting one from the position of the first layer in the current - // target surface's child layer list, which is 0. - static const int LayerIndexRepresentingTargetRenderSurface = -1; -}; - -// The position of a layer iterator that is independent of its many template types. -template <typename LayerType> -struct CCLayerIteratorPosition { - bool representsTargetRenderSurface; - bool representsContributingRenderSurface; - bool representsItself; - LayerType* targetRenderSurfaceLayer; - LayerType* currentLayer; -}; - -// An iterator class for walking over layers in the RenderSurface-Layer tree. -template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename IteratorActionType> -class CCLayerIterator { - typedef CCLayerIterator<LayerType, LayerList, RenderSurfaceType, IteratorActionType> CCLayerIteratorType; - -public: - CCLayerIterator() : m_renderSurfaceLayerList(0) { } - - static CCLayerIteratorType begin(const LayerList* renderSurfaceLayerList) { return CCLayerIteratorType(renderSurfaceLayerList, true); } - static CCLayerIteratorType end(const LayerList* renderSurfaceLayerList) { return CCLayerIteratorType(renderSurfaceLayerList, false); } - - CCLayerIteratorType& operator++() { m_actions.next(*this); return *this; } - bool operator==(const CCLayerIterator& other) const - { - return m_targetRenderSurfaceLayerIndex == other.m_targetRenderSurfaceLayerIndex - && m_currentLayerIndex == other.m_currentLayerIndex; - } - bool operator!=(const CCLayerIteratorType& other) const { return !(*this == other); } - - LayerType* operator->() const { return currentLayer(); } - LayerType* operator*() const { return currentLayer(); } - - bool representsTargetRenderSurface() const { return currentLayerRepresentsTargetRenderSurface(); } - bool representsContributingRenderSurface() const { return !representsTargetRenderSurface() && currentLayerRepresentsContributingRenderSurface(); } - bool representsItself() const { return !representsTargetRenderSurface() && !representsContributingRenderSurface(); } - - LayerType* targetRenderSurfaceLayer() const { return getRawPtr((*m_renderSurfaceLayerList)[m_targetRenderSurfaceLayerIndex]); } - - operator const CCLayerIteratorPosition<LayerType>() const - { - CCLayerIteratorPosition<LayerType> position; - position.representsTargetRenderSurface = representsTargetRenderSurface(); - position.representsContributingRenderSurface = representsContributingRenderSurface(); - position.representsItself = representsItself(); - position.targetRenderSurfaceLayer = targetRenderSurfaceLayer(); - position.currentLayer = currentLayer(); - return position; - } - -private: - CCLayerIterator(const LayerList* renderSurfaceLayerList, bool start) - : m_renderSurfaceLayerList(renderSurfaceLayerList) - , m_targetRenderSurfaceLayerIndex(0) - { - for (size_t i = 0; i < renderSurfaceLayerList->size(); ++i) { - if (!(*renderSurfaceLayerList)[i]->renderSurface()) { - ASSERT_NOT_REACHED(); - m_actions.end(*this); - return; - } - } - - if (start && !renderSurfaceLayerList->isEmpty()) - m_actions.begin(*this); - else - m_actions.end(*this); - } - - inline static LayerChromium* getRawPtr(const RefPtr<LayerChromium>& ptr) { return ptr.get(); } - inline static CCLayerImpl* getRawPtr(CCLayerImpl* ptr) { return ptr; } - - inline LayerType* currentLayer() const { return currentLayerRepresentsTargetRenderSurface() ? targetRenderSurfaceLayer() : getRawPtr(targetRenderSurfaceChildren()[m_currentLayerIndex]); } - - inline bool currentLayerRepresentsContributingRenderSurface() const { return CCLayerTreeHostCommon::renderSurfaceContributesToTarget<LayerType>(currentLayer(), targetRenderSurfaceLayer()->id()); } - inline bool currentLayerRepresentsTargetRenderSurface() const { return m_currentLayerIndex == CCLayerIteratorValue::LayerIndexRepresentingTargetRenderSurface; } - - inline RenderSurfaceType* targetRenderSurface() const { return targetRenderSurfaceLayer()->renderSurface(); } - inline const LayerList& targetRenderSurfaceChildren() const { return targetRenderSurface()->layerList(); } - - IteratorActionType m_actions; - const LayerList* m_renderSurfaceLayerList; - - // The iterator's current position. - - // A position in the renderSurfaceLayerList. This points to a layer which owns the current target surface. - // This is a value from 0 to n-1 (n = size of renderSurfaceLayerList = number of surfaces). A value outside of - // this range (for example, CCLayerIteratorValue::InvalidTargetRenderSurfaceLayerIndex) is used to - // indicate a position outside the bounds of the tree. - int m_targetRenderSurfaceLayerIndex; - // A position in the list of layers that are children of the current target surface. When pointing to one of - // these layers, this is a value from 0 to n-1 (n = number of children). Since the iterator must also stop at - // the layers representing the target surface, this is done by setting the currentLayerIndex to a value of - // CCLayerIteratorValue::LayerRepresentingTargetRenderSurface. - int m_currentLayerIndex; - - friend struct CCLayerIteratorActions; -}; - -// Orderings for iterating over the RenderSurface-Layer tree. -struct CCLayerIteratorActions { - // Walks layers sorted by z-order from back to front. - class BackToFront { - public: - template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> - void begin(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>&); - - template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> - void end(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>&); - - template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> - void next(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>&); - - private: - int m_highestTargetRenderSurfaceLayer; - }; - - // Walks layers sorted by z-order from front to back - class FrontToBack { - public: - template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> - void begin(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>&); - - template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> - void end(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>&); - - template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> - void next(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>&); - - private: - template <typename LayerType, typename LayerList, typename RenderSurfaceType, typename ActionType> - void goToHighestInSubtree(CCLayerIterator<LayerType, LayerList, RenderSurfaceType, ActionType>&); - }; -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerQuad.cpp deleted file mode 100644 index e8c6da29f..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerQuad.cpp +++ /dev/null @@ -1,87 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCLayerQuad.h" - -namespace WebCore { - -CCLayerQuad::Edge::Edge(const FloatPoint& p, const FloatPoint& q) -{ - ASSERT(p != q); - - FloatPoint tangent(p.y() - q.y(), q.x() - p.x()); - float cross2 = p.x() * q.y() - q.x() * p.y(); - - set(tangent.x(), tangent.y(), cross2); - scale(1.0f / tangent.length()); -} - -CCLayerQuad::CCLayerQuad(const FloatQuad& quad) -{ - // Create edges. - m_left = Edge(quad.p4(), quad.p1()); - m_right = Edge(quad.p2(), quad.p3()); - m_top = Edge(quad.p1(), quad.p2()); - m_bottom = Edge(quad.p3(), quad.p4()); - - float sign = quad.isCounterclockwise() ? -1 : 1; - m_left.scale(sign); - m_right.scale(sign); - m_top.scale(sign); - m_bottom.scale(sign); -} - -FloatQuad CCLayerQuad::floatQuad() const -{ - return FloatQuad(m_left.intersect(m_top), - m_top.intersect(m_right), - m_right.intersect(m_bottom), - m_bottom.intersect(m_left)); -} - -void CCLayerQuad::toFloatArray(float flattened[12]) const -{ - flattened[0] = m_left.x(); - flattened[1] = m_left.y(); - flattened[2] = m_left.z(); - flattened[3] = m_top.x(); - flattened[4] = m_top.y(); - flattened[5] = m_top.z(); - flattened[6] = m_right.x(); - flattened[7] = m_right.y(); - flattened[8] = m_right.z(); - flattened[9] = m_bottom.x(); - flattened[10] = m_bottom.y(); - flattened[11] = m_bottom.z(); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerQuad.h deleted file mode 100644 index fcf818e6c..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerQuad.h +++ /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. - */ - - -#ifndef CCLayerQuad_h -#define CCLayerQuad_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "FloatPoint3D.h" -#include "FloatQuad.h" - -static const float kAntiAliasingInflateDistance = 0.5f; - -namespace WebCore { - -class CCLayerQuad { -public: - class Edge { - public: - Edge() - : m_x(0) - , m_y(0) - , m_z(0) - { - } - Edge(const FloatPoint&, const FloatPoint&); - - float x() const { return m_x; } - float y() const { return m_y; } - float z() const { return m_z; } - - void setX(float x) { m_x = x; } - void setY(float y) { m_y = y; } - 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 moveX(float dx) { m_x += dx; } - void moveY(float dy) { m_y += dy; } - void moveZ(float dz) { m_z += dz; } - void move(float dx, float dy, float dz) - { - m_x += dx; - m_y += dy; - m_z += dz; - } - - void scaleX(float sx) { m_x *= sx; } - void scaleY(float sy) { m_y *= sy; } - void scaleZ(float sz) { m_z *= sz; } - void scale(float sx, float sy, float sz) - { - m_x *= sx; - m_y *= sy; - m_z *= sz; - } - void scale(float s) { scale(s, s, s); } - - FloatPoint intersect(const Edge& e) const - { - return FloatPoint( - (y() * e.z() - e.y() * z()) / (x() * e.y() - e.x() * y()), - (x() * e.z() - e.x() * z()) / (e.x() * y() - x() * e.y())); - } - - private: - float m_x; - float m_y; - float m_z; - }; - - CCLayerQuad(const Edge& left, const Edge& top, const Edge& right, const Edge& bottom) - : m_left(left) - , m_top(top) - , m_right(right) - , m_bottom(bottom) - { - } - CCLayerQuad(const FloatQuad&); - - Edge left() const { return m_left; } - Edge top() const { return m_top; } - Edge right() const { return m_right; } - Edge bottom() const { return m_bottom; } - - void inflateX(float dx) { m_left.moveZ(dx); m_right.moveZ(dx); } - void inflateY(float dy) { m_top.moveZ(dy); m_bottom.moveZ(dy); } - void inflate(float d) { inflateX(d); inflateY(d); } - void inflateAntiAliasingDistance() { inflate(kAntiAliasingInflateDistance); } - - FloatQuad floatQuad() const; - - void toFloatArray(float[12]) const; - -private: - Edge m_left; - Edge m_top; - Edge m_right; - Edge m_bottom; -}; - -} - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerSorter.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerSorter.cpp deleted file mode 100644 index 40dd77734..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerSorter.cpp +++ /dev/null @@ -1,442 +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 "CCLayerSorter.h" - -#include "CCMathUtil.h" -#include "CCRenderSurface.h" -#include <limits.h> -#include <public/WebTransformationMatrix.h> -#include <wtf/Deque.h> - -using namespace std; -using WebKit::WebTransformationMatrix; - -#define LOG_CHANNEL_PREFIX Log -#define SHOW_DEBUG_LOG 0 - -#if !defined( NDEBUG ) -#if SHOW_DEBUG_LOG -static WTFLogChannel LogCCLayerSorter = { 0x00000000, "", WTFLogChannelOn }; -#else -static WTFLogChannel LogCCLayerSorter = { 0x00000000, "", WTFLogChannelOff }; -#endif -#endif - -namespace WebCore { - -inline static float perpProduct(const FloatSize& u, const FloatSize& v) -{ - return u.width() * v.height() - u.height() * v.width(); -} - -// Tests if two edges defined by their endpoints (a,b) and (c,d) intersect. Returns true and the -// point of intersection if they do and false otherwise. -static bool edgeEdgeTest(const FloatPoint& a, const FloatPoint& b, const FloatPoint& c, const FloatPoint& d, FloatPoint& r) -{ - FloatSize u = b - a; - FloatSize v = d - c; - FloatSize w = a - c; - - float denom = perpProduct(u, v); - - // If denom == 0 then the edges are parallel. While they could be overlapping - // we don't bother to check here as the we'll find their intersections from the - // corner to quad tests. - if (!denom) - return false; - - float s = perpProduct(v, w) / denom; - if (s < 0 || s > 1) - return false; - - float t = perpProduct(u, w) / denom; - if (t < 0 || t > 1) - return false; - - u.scale(s); - r = a + u; - return true; -} - -// Checks whether layer "a" draws on top of layer "b". The weight value returned is an indication of -// the maximum z-depth difference between the layers or zero if the layers are found to be intesecting -// (some features are in front and some are behind). -CCLayerSorter::ABCompareResult CCLayerSorter::checkOverlap(LayerShape* a, LayerShape* b, float zThreshold, float& weight) -{ - weight = 0; - - // Early out if the projected bounds don't overlap. - if (!a->projectedBounds.intersects(b->projectedBounds)) - return None; - - FloatPoint aPoints[4] = {a->projectedQuad.p1(), a->projectedQuad.p2(), a->projectedQuad.p3(), a->projectedQuad.p4() }; - FloatPoint bPoints[4] = {b->projectedQuad.p1(), b->projectedQuad.p2(), b->projectedQuad.p3(), b->projectedQuad.p4() }; - - // Make a list of points that inside both layer quad projections. - Vector<FloatPoint> overlapPoints; - - // Check all four corners of one layer against the other layer's quad. - for (int i = 0; i < 4; ++i) { - if (a->projectedQuad.containsPoint(bPoints[i])) - overlapPoints.append(bPoints[i]); - if (b->projectedQuad.containsPoint(aPoints[i])) - overlapPoints.append(aPoints[i]); - } - - // Check all the edges of one layer for intersection with the other layer's edges. - FloatPoint r; - for (int ea = 0; ea < 4; ++ea) - for (int eb = 0; eb < 4; ++eb) - if (edgeEdgeTest(aPoints[ea], aPoints[(ea + 1) % 4], - bPoints[eb], bPoints[(eb + 1) % 4], - r)) - overlapPoints.append(r); - - if (!overlapPoints.size()) - return None; - - // Check the corresponding layer depth value for all overlap points to determine - // which layer is in front. - float maxPositive = 0; - float maxNegative = 0; - for (unsigned o = 0; o < overlapPoints.size(); o++) { - float za = a->layerZFromProjectedPoint(overlapPoints[o]); - float zb = b->layerZFromProjectedPoint(overlapPoints[o]); - - float diff = za - zb; - if (diff > maxPositive) - maxPositive = diff; - if (diff < maxNegative) - maxNegative = diff; - } - - float maxDiff = (fabsf(maxPositive) > fabsf(maxNegative) ? maxPositive : maxNegative); - - // If the results are inconsistent (and the z difference substantial to rule out - // numerical errors) then the layers are intersecting. We will still return an - // order based on the maximum depth difference but with an edge weight of zero - // these layers will get priority if a graph cycle is present and needs to be broken. - if (maxPositive > zThreshold && maxNegative < -zThreshold) - weight = 0; - else - weight = fabsf(maxDiff); - - // Maintain relative order if the layers have the same depth at all intersection points. - if (maxDiff <= 0) - return ABeforeB; - - return BBeforeA; -} - -CCLayerSorter::LayerShape::LayerShape(float width, float height, const WebTransformationMatrix& drawTransform) -{ - FloatQuad layerQuad(FloatRect(0, 0, width, height)); - - // Compute the projection of the layer quad onto the z = 0 plane. - - FloatPoint clippedQuad[8]; - int numVerticesInClippedQuad; - CCMathUtil::mapClippedQuad(drawTransform, layerQuad, clippedQuad, numVerticesInClippedQuad); - - if (numVerticesInClippedQuad < 3) { - projectedBounds = FloatRect(); - return; - } - - projectedBounds = CCMathUtil::computeEnclosingRectOfVertices(clippedQuad, numVerticesInClippedQuad); - - // NOTE: it will require very significant refactoring and overhead to deal with - // generalized polygons or multiple quads per layer here. For the sake of layer - // sorting it is equally correct to take a subsection of the polygon that can be made - // into a quad. This will only be incorrect in the case of intersecting layers, which - // are not supported yet anyway. - projectedQuad.setP1(clippedQuad[0]); - projectedQuad.setP2(clippedQuad[1]); - projectedQuad.setP3(clippedQuad[2]); - if (numVerticesInClippedQuad >= 4) - projectedQuad.setP4(clippedQuad[3]); - else - projectedQuad.setP4(clippedQuad[2]); // this will be a degenerate quad that is actually a triangle. - - // Compute the normal of the layer's plane. - bool clipped = false; - FloatPoint3D c1 = CCMathUtil::mapPoint(drawTransform, FloatPoint3D(0, 0, 0), clipped); - FloatPoint3D c2 = CCMathUtil::mapPoint(drawTransform, FloatPoint3D(0, 1, 0), clipped); - FloatPoint3D c3 = CCMathUtil::mapPoint(drawTransform, FloatPoint3D(1, 0, 0), clipped); - // FIXME: Deal with clipping. - FloatPoint3D c12 = c2 - c1; - FloatPoint3D c13 = c3 - c1; - layerNormal = c13.cross(c12); - - transformOrigin = c1; -} - -// Returns the Z coordinate of a point on the layer that projects -// to point p which lies on the z = 0 plane. It does it by computing the -// intersection of a line starting from p along the Z axis and the plane -// of the layer. -float CCLayerSorter::LayerShape::layerZFromProjectedPoint(const FloatPoint& p) const -{ - const FloatPoint3D zAxis(0, 0, 1); - FloatPoint3D w = FloatPoint3D(p) - transformOrigin; - - float d = layerNormal.dot(zAxis); - float n = -layerNormal.dot(w); - - // Check if layer is parallel to the z = 0 axis which will make it - // invisible and hence returning zero is fine. - if (!d) - return 0; - - // The intersection point would be given by: - // p + (n / d) * u but since we are only interested in the - // z coordinate and p's z coord is zero, all we need is the value of n/d. - return n / d; -} - -void CCLayerSorter::createGraphNodes(LayerList::iterator first, LayerList::iterator last) -{ -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "Creating graph nodes:\n"); -#endif - float minZ = FLT_MAX; - float maxZ = -FLT_MAX; - for (LayerList::const_iterator it = first; it < last; it++) { - m_nodes.append(GraphNode(*it)); - GraphNode& node = m_nodes.at(m_nodes.size() - 1); - CCRenderSurface* renderSurface = node.layer->renderSurface(); - if (!node.layer->drawsContent() && !renderSurface) - continue; - -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "Layer %d (%d x %d)\n", node.layer->id(), node.layer->bounds().width(), node.layer->bounds().height()); -#endif - - WebTransformationMatrix drawTransform; - float layerWidth, layerHeight; - if (renderSurface) { - drawTransform = renderSurface->drawTransform(); - layerWidth = renderSurface->contentRect().width(); - layerHeight = renderSurface->contentRect().height(); - } else { - drawTransform = node.layer->drawTransform(); - layerWidth = node.layer->contentBounds().width(); - layerHeight = node.layer->contentBounds().height(); - } - - node.shape = LayerShape(layerWidth, layerHeight, drawTransform); - - maxZ = max(maxZ, node.shape.transformOrigin.z()); - minZ = min(minZ, node.shape.transformOrigin.z()); - } - - m_zRange = fabsf(maxZ - minZ); -} - -void CCLayerSorter::createGraphEdges() -{ -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "Edges:\n"); -#endif - // Fraction of the total zRange below which z differences - // are not considered reliable. - const float zThresholdFactor = 0.01f; - float zThreshold = m_zRange * zThresholdFactor; - - for (unsigned na = 0; na < m_nodes.size(); na++) { - GraphNode& nodeA = m_nodes[na]; - if (!nodeA.layer->drawsContent() && !nodeA.layer->renderSurface()) - continue; - for (unsigned nb = na + 1; nb < m_nodes.size(); nb++) { - GraphNode& nodeB = m_nodes[nb]; - if (!nodeB.layer->drawsContent() && !nodeB.layer->renderSurface()) - continue; - float weight = 0; - ABCompareResult overlapResult = checkOverlap(&nodeA.shape, &nodeB.shape, zThreshold, weight); - GraphNode* startNode = 0; - GraphNode* endNode = 0; - if (overlapResult == ABeforeB) { - startNode = &nodeA; - endNode = &nodeB; - } else if (overlapResult == BBeforeA) { - startNode = &nodeB; - endNode = &nodeA; - } - - if (startNode) { -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "%d -> %d\n", startNode->layer->id(), endNode->layer->id()); -#endif - m_edges.append(GraphEdge(startNode, endNode, weight)); - } - } - } - - for (unsigned i = 0; i < m_edges.size(); i++) { - GraphEdge& edge = m_edges[i]; - m_activeEdges.add(&edge, &edge); - edge.from->outgoing.append(&edge); - edge.to->incoming.append(&edge); - edge.to->incomingEdgeWeight += edge.weight; - } -} - -// Finds and removes an edge from the list by doing a swap with the -// last element of the list. -void CCLayerSorter::removeEdgeFromList(GraphEdge* edge, Vector<GraphEdge*>& list) -{ - size_t edgeIndex = list.find(edge); - ASSERT(edgeIndex != notFound); - if (list.size() == 1) { - ASSERT(!edgeIndex); - list.clear(); - return; - } - if (edgeIndex != list.size() - 1) - list[edgeIndex] = list[list.size() - 1]; - - list.removeLast(); -} - -// Sorts the given list of layers such that they can be painted in a back-to-front -// order. Sorting produces correct results for non-intersecting layers that don't have -// cyclical order dependencies. Cycles and intersections are broken (somewhat) aribtrarily. -// Sorting of layers is done via a topological sort of a directed graph whose nodes are -// the layers themselves. An edge from node A to node B signifies that layer A needs to -// be drawn before layer B. If A and B have no dependency between each other, then we -// preserve the ordering of those layers as they were in the original list. -// -// The draw order between two layers is determined by projecting the two triangles making -// up each layer quad to the Z = 0 plane, finding points of intersection between the triangles -// and backprojecting those points to the plane of the layer to determine the corresponding Z -// coordinate. The layer with the lower Z coordinate (farther from the eye) needs to be rendered -// first. -// -// If the layer projections don't intersect, then no edges (dependencies) are created -// between them in the graph. HOWEVER, in this case we still need to preserve the ordering -// of the original list of layers, since that list should already have proper z-index -// ordering of layers. -// -void CCLayerSorter::sort(LayerList::iterator first, LayerList::iterator last) -{ -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "Sorting start ----\n"); -#endif - createGraphNodes(first, last); - - createGraphEdges(); - - Vector<GraphNode*> sortedList; - Deque<GraphNode*> noIncomingEdgeNodeList; - - // Find all the nodes that don't have incoming edges. - for (NodeList::iterator la = m_nodes.begin(); la < m_nodes.end(); la++) { - if (!la->incoming.size()) - noIncomingEdgeNodeList.append(la); - } - -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "Sorted list: "); -#endif - while (m_activeEdges.size() || noIncomingEdgeNodeList.size()) { - while (noIncomingEdgeNodeList.size()) { - - // It is necessary to preserve the existing ordering of layers, when there are - // no explicit dependencies (because this existing ordering has correct - // z-index/layout ordering). To preserve this ordering, we process Nodes in - // the same order that they were added to the list. - GraphNode* fromNode = noIncomingEdgeNodeList.takeFirst(); - - // Add it to the final list. - sortedList.append(fromNode); - -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "%d, ", fromNode->layer->id()); -#endif - - // Remove all its outgoing edges from the graph. - for (unsigned i = 0; i < fromNode->outgoing.size(); i++) { - GraphEdge* outgoingEdge = fromNode->outgoing[i]; - - m_activeEdges.remove(outgoingEdge); - removeEdgeFromList(outgoingEdge, outgoingEdge->to->incoming); - outgoingEdge->to->incomingEdgeWeight -= outgoingEdge->weight; - - if (!outgoingEdge->to->incoming.size()) - noIncomingEdgeNodeList.append(outgoingEdge->to); - } - fromNode->outgoing.clear(); - } - - if (!m_activeEdges.size()) - break; - - // If there are still active edges but the list of nodes without incoming edges - // is empty then we have run into a cycle. Break the cycle by finding the node - // with the smallest overall incoming edge weight and use it. This will favor - // nodes that have zero-weight incoming edges i.e. layers that are being - // occluded by a layer that intersects them. - float minIncomingEdgeWeight = FLT_MAX; - GraphNode* nextNode = 0; - for (unsigned i = 0; i < m_nodes.size(); i++) { - if (m_nodes[i].incoming.size() && m_nodes[i].incomingEdgeWeight < minIncomingEdgeWeight) { - minIncomingEdgeWeight = m_nodes[i].incomingEdgeWeight; - nextNode = &m_nodes[i]; - } - } - ASSERT(nextNode); - // Remove all its incoming edges. - for (unsigned e = 0; e < nextNode->incoming.size(); e++) { - GraphEdge* incomingEdge = nextNode->incoming[e]; - - m_activeEdges.remove(incomingEdge); - removeEdgeFromList(incomingEdge, incomingEdge->from->outgoing); - } - nextNode->incoming.clear(); - nextNode->incomingEdgeWeight = 0; - noIncomingEdgeNodeList.append(nextNode); -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "Breaking cycle by cleaning up incoming edges from %d (weight = %f)\n", nextNode->layer->id(), minIncomingEdgeWeight); -#endif - } - - // Note: The original elements of the list are in no danger of having their ref count go to zero - // here as they are all nodes of the layer hierarchy and are kept alive by their parent nodes. - int count = 0; - for (LayerList::iterator it = first; it < last; it++) - *it = sortedList[count++]->layer; - -#if !defined( NDEBUG ) - LOG(CCLayerSorter, "Sorting end ----\n"); -#endif - - m_nodes.clear(); - m_edges.clear(); - m_activeEdges.clear(); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerSorter.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerSorter.h deleted file mode 100644 index 3592cad4d..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerSorter.h +++ /dev/null @@ -1,108 +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 CCLayerSorter_h -#define CCLayerSorter_h - -#include "CCLayerImpl.h" -#include "FloatPoint3D.h" -#include "FloatQuad.h" -#include "FloatRect.h" -#include <wtf/HashMap.h> -#include <wtf/Noncopyable.h> -#include <wtf/Vector.h> - -namespace WebKit { -class WebTransformationMatrix; -} - -namespace WebCore { - -class CCLayerSorter { - WTF_MAKE_NONCOPYABLE(CCLayerSorter); -public: - CCLayerSorter() : m_zRange(0) { } - - typedef Vector<CCLayerImpl*> LayerList; - - void sort(LayerList::iterator first, LayerList::iterator last); - - // Holds various useful properties derived from a layer's 3D outline. - struct LayerShape { - LayerShape() { } - LayerShape(float width, float height, const WebKit::WebTransformationMatrix& drawTransform); - - float layerZFromProjectedPoint(const FloatPoint&) const; - - FloatPoint3D layerNormal; - FloatPoint3D transformOrigin; - FloatQuad projectedQuad; - FloatRect projectedBounds; - }; - - enum ABCompareResult { - ABeforeB, - BBeforeA, - None - }; - - static ABCompareResult checkOverlap(LayerShape*, LayerShape*, float zThreshold, float& weight); - -private: - struct GraphEdge; - - struct GraphNode { - explicit GraphNode(CCLayerImpl* cclayer) : layer(cclayer), incomingEdgeWeight(0) { } - - CCLayerImpl* layer; - LayerShape shape; - Vector<GraphEdge*> incoming; - Vector<GraphEdge*> outgoing; - float incomingEdgeWeight; - }; - - struct GraphEdge { - GraphEdge(GraphNode* fromNode, GraphNode* toNode, float weight) : from(fromNode), to(toNode), weight(weight) { }; - - GraphNode* from; - GraphNode* to; - float weight; - }; - - typedef Vector<GraphNode> NodeList; - typedef Vector<GraphEdge> EdgeList; - NodeList m_nodes; - EdgeList m_edges; - float m_zRange; - - typedef HashMap<GraphEdge*, GraphEdge*> EdgeMap; - EdgeMap m_activeEdges; - - void createGraphNodes(LayerList::iterator first, LayerList::iterator last); - void createGraphEdges(); - void removeEdgeFromList(GraphEdge*, Vector<GraphEdge*>&); -}; - -} -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTilingData.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTilingData.cpp deleted file mode 100644 index 9b55156d9..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTilingData.cpp +++ /dev/null @@ -1,170 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCLayerTilingData.h" - -using namespace std; - -namespace WebCore { - -PassOwnPtr<CCLayerTilingData> CCLayerTilingData::create(const IntSize& tileSize, BorderTexelOption border) -{ - return adoptPtr(new CCLayerTilingData(tileSize, border)); -} - -CCLayerTilingData::CCLayerTilingData(const IntSize& tileSize, BorderTexelOption border) - : m_tilingData(tileSize, IntSize(), border == HasBorderTexels) -{ - setTileSize(tileSize); -} - -void CCLayerTilingData::setTileSize(const IntSize& size) -{ - if (tileSize() == size) - return; - - reset(); - - m_tilingData.setMaxTextureSize(size); -} - -const IntSize& CCLayerTilingData::tileSize() const -{ - return m_tilingData.maxTextureSize(); -} - -void CCLayerTilingData::setBorderTexelOption(BorderTexelOption borderTexelOption) -{ - bool borderTexels = borderTexelOption == HasBorderTexels; - if (hasBorderTexels() == borderTexels) - return; - - reset(); - m_tilingData.setHasBorderTexels(borderTexels); -} - -const CCLayerTilingData& CCLayerTilingData::operator=(const CCLayerTilingData& tiler) -{ - m_tilingData = tiler.m_tilingData; - - return *this; -} - -void CCLayerTilingData::addTile(PassOwnPtr<Tile> tile, int i, int j) -{ - ASSERT(!tileAt(i, j)); - tile->moveTo(i, j); - m_tiles.add(make_pair(i, j), tile); -} - -PassOwnPtr<CCLayerTilingData::Tile> CCLayerTilingData::takeTile(int i, int j) -{ - return m_tiles.take(make_pair(i, j)); -} - -CCLayerTilingData::Tile* CCLayerTilingData::tileAt(int i, int j) const -{ - return m_tiles.get(make_pair(i, j)); -} - -void CCLayerTilingData::reset() -{ - m_tiles.clear(); -} - -void CCLayerTilingData::contentRectToTileIndices(const IntRect& contentRect, int& left, int& top, int& right, int& bottom) const -{ - // An empty rect doesn't result in an empty set of tiles, so don't pass an empty rect. - // FIXME: Possibly we should fill a vector of tiles instead, - // since the normal use of this function is to enumerate some tiles. - ASSERT(!contentRect.isEmpty()); - - left = m_tilingData.tileXIndexFromSrcCoord(contentRect.x()); - top = m_tilingData.tileYIndexFromSrcCoord(contentRect.y()); - right = m_tilingData.tileXIndexFromSrcCoord(contentRect.maxX() - 1); - bottom = m_tilingData.tileYIndexFromSrcCoord(contentRect.maxY() - 1); -} - -IntRect CCLayerTilingData::tileRect(const Tile* tile) const -{ - IntRect tileRect = m_tilingData.tileBoundsWithBorder(tile->i(), tile->j()); - tileRect.setSize(tileSize()); - return tileRect; -} - -Region CCLayerTilingData::opaqueRegionInContentRect(const IntRect& contentRect) const -{ - if (contentRect.isEmpty()) - return Region(); - - Region opaqueRegion; - int left, top, right, bottom; - contentRectToTileIndices(contentRect, left, top, right, bottom); - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - Tile* tile = tileAt(i, j); - if (!tile) - continue; - - IntRect tileOpaqueRect = intersection(contentRect, tile->opaqueRect()); - opaqueRegion.unite(tileOpaqueRect); - } - } - return opaqueRegion; -} - -void CCLayerTilingData::setBounds(const IntSize& size) -{ - m_tilingData.setTotalSize(size); - if (size.isEmpty()) { - m_tiles.clear(); - return; - } - - // Any tiles completely outside our new bounds are invalid and should be dropped. - int left, top, right, bottom; - contentRectToTileIndices(IntRect(IntPoint(), size), left, top, right, bottom); - Vector<TileMapKey> invalidTileKeys; - for (TileMap::const_iterator it = m_tiles.begin(); it != m_tiles.end(); ++it) { - if (it->first.first > right || it->first.second > bottom) - invalidTileKeys.append(it->first); - } - for (size_t i = 0; i < invalidTileKeys.size(); ++i) - m_tiles.remove(invalidTileKeys[i]); -} - -IntSize CCLayerTilingData::bounds() const -{ - return m_tilingData.totalSize(); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTilingData.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTilingData.h deleted file mode 100644 index 25ff179ca..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTilingData.h +++ /dev/null @@ -1,119 +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 CCLayerTilingData_h -#define CCLayerTilingData_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "IntRect.h" -#include "Region.h" -#include "TilingData.h" -#include <wtf/HashMap.h> -#include <wtf/HashTraits.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCLayerTilingData { -public: - enum BorderTexelOption { HasBorderTexels, NoBorderTexels }; - - static PassOwnPtr<CCLayerTilingData> create(const IntSize& tileSize, BorderTexelOption); - - bool hasEmptyBounds() const { return m_tilingData.hasEmptyBounds(); } - int numTilesX() const { return m_tilingData.numTilesX(); } - int numTilesY() const { return m_tilingData.numTilesY(); } - IntRect tileBounds(int i, int j) const { return m_tilingData.tileBounds(i, j); } - IntPoint textureOffset(int xIndex, int yIndex) const { return m_tilingData.textureOffset(xIndex, yIndex); } - - // Change the tile size. This may invalidate all the existing tiles. - void setTileSize(const IntSize&); - const IntSize& tileSize() const; - // Change the border texel setting. This may invalidate all existing tiles. - void setBorderTexelOption(BorderTexelOption); - bool hasBorderTexels() const { return m_tilingData.borderTexels(); } - - bool isEmpty() const { return hasEmptyBounds() || !tiles().size(); } - - const CCLayerTilingData& operator=(const CCLayerTilingData&); - - class Tile { - WTF_MAKE_NONCOPYABLE(Tile); - public: - Tile() : m_i(-1), m_j(-1) { } - virtual ~Tile() { } - - int i() const { return m_i; } - int j() const { return m_j; } - void moveTo(int i, int j) { m_i = i; m_j = j; } - - const IntRect& opaqueRect() const { return m_opaqueRect; } - void setOpaqueRect(const IntRect& opaqueRect) { m_opaqueRect = opaqueRect; } - private: - int m_i; - int m_j; - IntRect m_opaqueRect; - }; - // Default hash key traits for integers disallow 0 and -1 as a key, so - // use a custom hash trait which disallows -1 and -2 instead. - typedef std::pair<int, int> TileMapKey; - struct TileMapKeyTraits : HashTraits<TileMapKey> { - static const bool emptyValueIsZero = false; - static const bool needsDestruction = false; - static TileMapKey emptyValue() { return std::make_pair(-1, -1); } - static void constructDeletedValue(TileMapKey& slot) { slot = std::make_pair(-2, -2); } - static bool isDeletedValue(TileMapKey value) { return value.first == -2 && value.second == -2; } - }; - typedef HashMap<TileMapKey, OwnPtr<Tile>, DefaultHash<TileMapKey>::Hash, TileMapKeyTraits> TileMap; - - void addTile(PassOwnPtr<Tile>, int, int); - PassOwnPtr<Tile> takeTile(int, int); - Tile* tileAt(int, int) const; - const TileMap& tiles() const { return m_tiles; } - - void setBounds(const IntSize&); - IntSize bounds() const; - - void contentRectToTileIndices(const IntRect&, int &left, int &top, int &right, int &bottom) const; - IntRect tileRect(const Tile*) const; - - Region opaqueRegionInContentRect(const IntRect&) const; - - void reset(); - -protected: - CCLayerTilingData(const IntSize& tileSize, BorderTexelOption); - - TileMap m_tiles; - TilingData m_tilingData; -}; - -} - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHost.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHost.cpp deleted file mode 100644 index 9fed479f7..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHost.cpp +++ /dev/null @@ -1,823 +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 "CCLayerTreeHost.h" - -#include "CCFontAtlas.h" -#include "CCGraphicsContext.h" -#include "CCHeadsUpDisplayLayerImpl.h" -#include "CCLayerAnimationController.h" -#include "CCLayerIterator.h" -#include "CCLayerTreeHostClient.h" -#include "CCLayerTreeHostCommon.h" -#include "CCLayerTreeHostImpl.h" -#include "CCOcclusionTracker.h" -#include "CCOverdrawMetrics.h" -#include "CCSettings.h" -#include "CCSingleThreadProxy.h" -#include "CCThreadProxy.h" -#include "HeadsUpDisplayLayerChromium.h" -#include "LayerChromium.h" -#include "Region.h" -#include "TraceEvent.h" -#include "TreeSynchronizer.h" - -using namespace std; -using WebKit::WebTransformationMatrix; - -namespace { -static int numLayerTreeInstances; -} - -namespace WebCore { - -bool CCLayerTreeHost::s_needsFilterContext = false; - -bool CCLayerTreeHost::anyLayerTreeHostInstanceExists() -{ - return numLayerTreeInstances > 0; -} - -PassOwnPtr<CCLayerTreeHost> CCLayerTreeHost::create(CCLayerTreeHostClient* client, const CCLayerTreeSettings& settings) -{ - OwnPtr<CCLayerTreeHost> layerTreeHost = adoptPtr(new CCLayerTreeHost(client, settings)); - if (!layerTreeHost->initialize()) - return nullptr; - return layerTreeHost.release(); -} - -CCLayerTreeHost::CCLayerTreeHost(CCLayerTreeHostClient* client, const CCLayerTreeSettings& settings) - : m_animating(false) - , m_needsAnimateLayers(false) - , m_client(client) - , m_commitNumber(0) - , m_renderingStats() - , m_rendererInitialized(false) - , m_contextLost(false) - , m_numTimesRecreateShouldFail(0) - , m_numFailedRecreateAttempts(0) - , m_settings(settings) - , m_deviceScaleFactor(1) - , m_visible(true) - , m_pageScaleFactor(1) - , m_minPageScaleFactor(1) - , m_maxPageScaleFactor(1) - , m_triggerIdleUpdates(true) - , m_backgroundColor(SK_ColorWHITE) - , m_hasTransparentBackground(false) - , m_partialTextureUpdateRequests(0) -{ - ASSERT(CCProxy::isMainThread()); - numLayerTreeInstances++; -} - -bool CCLayerTreeHost::initialize() -{ - TRACE_EVENT0("cc", "CCLayerTreeHost::initialize"); - - if (CCProxy::hasImplThread()) - m_proxy = CCThreadProxy::create(this); - else - m_proxy = CCSingleThreadProxy::create(this); - m_proxy->start(); - - return m_proxy->initializeContext(); -} - -CCLayerTreeHost::~CCLayerTreeHost() -{ - if (m_rootLayer) - m_rootLayer->setLayerTreeHost(0); - ASSERT(CCProxy::isMainThread()); - TRACE_EVENT0("cc", "CCLayerTreeHost::~CCLayerTreeHost"); - ASSERT(m_proxy); - m_proxy->stop(); - m_proxy.clear(); - numLayerTreeInstances--; - RateLimiterMap::iterator it = m_rateLimiters.begin(); - if (it != m_rateLimiters.end()) - it->second->stop(); -} - -void CCLayerTreeHost::setSurfaceReady() -{ - m_proxy->setSurfaceReady(); -} - -void CCLayerTreeHost::initializeRenderer() -{ - TRACE_EVENT0("cc", "CCLayerTreeHost::initializeRenderer"); - if (!m_proxy->initializeRenderer()) { - // Uh oh, better tell the client that we can't do anything with this context. - m_client->didRecreateOutputSurface(false); - return; - } - - // Update m_settings based on capabilities that we got back from the renderer. - m_settings.acceleratePainting = m_proxy->rendererCapabilities().usingAcceleratedPainting; - - // Update m_settings based on partial update capability. - m_settings.maxPartialTextureUpdates = min(m_settings.maxPartialTextureUpdates, m_proxy->maxPartialTextureUpdates()); - - m_contentsTextureManager = CCPrioritizedTextureManager::create(0, m_proxy->rendererCapabilities().maxTextureSize, CCRenderer::ContentPool); - m_surfaceMemoryPlaceholder = m_contentsTextureManager->createTexture(IntSize(), GraphicsContext3D::RGBA); - - m_rendererInitialized = true; - - m_settings.defaultTileSize = IntSize(min(m_settings.defaultTileSize.width(), m_proxy->rendererCapabilities().maxTextureSize), - min(m_settings.defaultTileSize.height(), m_proxy->rendererCapabilities().maxTextureSize)); - m_settings.maxUntiledLayerSize = IntSize(min(m_settings.maxUntiledLayerSize.width(), m_proxy->rendererCapabilities().maxTextureSize), - min(m_settings.maxUntiledLayerSize.height(), m_proxy->rendererCapabilities().maxTextureSize)); -} - -CCLayerTreeHost::RecreateResult CCLayerTreeHost::recreateContext() -{ - TRACE_EVENT0("cc", "CCLayerTreeHost::recreateContext"); - ASSERT(m_contextLost); - - bool recreated = false; - if (!m_numTimesRecreateShouldFail) - recreated = m_proxy->recreateContext(); - else - m_numTimesRecreateShouldFail--; - - if (recreated) { - m_client->didRecreateOutputSurface(true); - m_contextLost = false; - return RecreateSucceeded; - } - - // Tolerate a certain number of recreation failures to work around races - // in the context-lost machinery. - m_numFailedRecreateAttempts++; - if (m_numFailedRecreateAttempts < 5) { - // FIXME: The single thread does not self-schedule context - // recreation. So force another recreation attempt to happen by requesting - // another commit. - if (!CCProxy::hasImplThread()) - setNeedsCommit(); - return RecreateFailedButTryAgain; - } - - // We have tried too many times to recreate the context. Tell the host to fall - // back to software rendering. - m_client->didRecreateOutputSurface(false); - return RecreateFailedAndGaveUp; -} - -void CCLayerTreeHost::deleteContentsTexturesOnImplThread(CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - if (m_rendererInitialized) - m_contentsTextureManager->clearAllMemory(resourceProvider); -} - -void CCLayerTreeHost::acquireLayerTextures() -{ - ASSERT(CCProxy::isMainThread()); - m_proxy->acquireLayerTextures(); -} - -void CCLayerTreeHost::updateAnimations(double monotonicFrameBeginTime) -{ - m_animating = true; - m_client->animate(monotonicFrameBeginTime); - animateLayers(monotonicFrameBeginTime); - m_animating = false; - - m_renderingStats.numAnimationFrames++; -} - -void CCLayerTreeHost::layout() -{ - m_client->layout(); -} - -void CCLayerTreeHost::beginCommitOnImplThread(CCLayerTreeHostImpl* hostImpl) -{ - ASSERT(CCProxy::isImplThread()); - TRACE_EVENT0("cc", "CCLayerTreeHost::commitTo"); - - m_contentsTextureManager->reduceMemory(hostImpl->resourceProvider()); -} - -// This function commits the CCLayerTreeHost to an impl tree. When modifying -// this function, keep in mind that the function *runs* on the impl thread! Any -// code that is logically a main thread operation, e.g. deletion of a LayerChromium, -// should be delayed until the CCLayerTreeHost::commitComplete, which will run -// after the commit, but on the main thread. -void CCLayerTreeHost::finishCommitOnImplThread(CCLayerTreeHostImpl* hostImpl) -{ - ASSERT(CCProxy::isImplThread()); - - hostImpl->setRootLayer(TreeSynchronizer::synchronizeTrees(rootLayer(), hostImpl->detachLayerTree(), hostImpl)); - - if (m_rootLayer && m_hudLayer) - hostImpl->setHudLayer(static_cast<CCHeadsUpDisplayLayerImpl*>(CCLayerTreeHostCommon::findLayerInSubtree(hostImpl->rootLayer(), m_hudLayer->id()))); - else - hostImpl->setHudLayer(0); - - // We may have added an animation during the tree sync. This will cause both layer tree hosts - // to visit their controllers. - if (rootLayer() && m_needsAnimateLayers) - hostImpl->setNeedsAnimateLayers(); - - hostImpl->setSourceFrameNumber(commitNumber()); - hostImpl->setViewportSize(layoutViewportSize(), deviceViewportSize()); - hostImpl->setDeviceScaleFactor(deviceScaleFactor()); - hostImpl->setPageScaleFactorAndLimits(m_pageScaleFactor, m_minPageScaleFactor, m_maxPageScaleFactor); - hostImpl->setBackgroundColor(m_backgroundColor); - hostImpl->setHasTransparentBackground(m_hasTransparentBackground); - - m_commitNumber++; -} - -void CCLayerTreeHost::setFontAtlas(PassOwnPtr<CCFontAtlas> fontAtlas) -{ - m_fontAtlas = fontAtlas; - setNeedsCommit(); -} - -void CCLayerTreeHost::willCommit() -{ - m_client->willCommit(); - if (m_rootLayer && m_settings.showDebugInfo()) { - if (!m_hudLayer) - m_hudLayer = HeadsUpDisplayLayerChromium::create(); - - if (m_fontAtlas) - m_hudLayer->setFontAtlas(m_fontAtlas.release()); - - if (!m_hudLayer->parent()) - m_rootLayer->addChild(m_hudLayer); - } -} - -void CCLayerTreeHost::commitComplete() -{ - m_deleteTextureAfterCommitList.clear(); - m_client->didCommit(); -} - -PassOwnPtr<CCGraphicsContext> CCLayerTreeHost::createContext() -{ - return m_client->createOutputSurface(); -} - -PassOwnPtr<CCInputHandler> CCLayerTreeHost::createInputHandler() -{ - return m_client->createInputHandler(); -} - -PassOwnPtr<CCLayerTreeHostImpl> CCLayerTreeHost::createLayerTreeHostImpl(CCLayerTreeHostImplClient* client) -{ - return CCLayerTreeHostImpl::create(m_settings, client); -} - -void CCLayerTreeHost::didLoseContext() -{ - TRACE_EVENT0("cc", "CCLayerTreeHost::didLoseContext"); - ASSERT(CCProxy::isMainThread()); - m_contextLost = true; - m_numFailedRecreateAttempts = 0; - setNeedsCommit(); -} - -bool CCLayerTreeHost::compositeAndReadback(void *pixels, const IntRect& rect) -{ - m_triggerIdleUpdates = false; - bool ret = m_proxy->compositeAndReadback(pixels, rect); - m_triggerIdleUpdates = true; - return ret; -} - -void CCLayerTreeHost::finishAllRendering() -{ - if (!m_rendererInitialized) - return; - m_proxy->finishAllRendering(); -} - -void CCLayerTreeHost::renderingStats(CCRenderingStats& stats) const -{ - stats = m_renderingStats; - m_proxy->implSideRenderingStats(stats); -} - -const RendererCapabilities& CCLayerTreeHost::rendererCapabilities() const -{ - return m_proxy->rendererCapabilities(); -} - -void CCLayerTreeHost::setNeedsAnimate() -{ - ASSERT(CCProxy::hasImplThread()); - m_proxy->setNeedsAnimate(); -} - -void CCLayerTreeHost::setNeedsCommit() -{ - m_proxy->setNeedsCommit(); -} - -void CCLayerTreeHost::setNeedsRedraw() -{ - m_proxy->setNeedsRedraw(); - if (!CCThreadProxy::implThread()) - m_client->scheduleComposite(); -} - -bool CCLayerTreeHost::commitRequested() const -{ - return m_proxy->commitRequested(); -} - -void CCLayerTreeHost::setAnimationEvents(PassOwnPtr<CCAnimationEventsVector> events, double wallClockTime) -{ - ASSERT(CCThreadProxy::isMainThread()); - setAnimationEventsRecursive(*events, m_rootLayer.get(), wallClockTime); -} - -void CCLayerTreeHost::didAddAnimation() -{ - m_needsAnimateLayers = true; - m_proxy->didAddAnimation(); -} - -void CCLayerTreeHost::setRootLayer(PassRefPtr<LayerChromium> rootLayer) -{ - if (m_rootLayer == rootLayer) - return; - - if (m_rootLayer) - m_rootLayer->setLayerTreeHost(0); - m_rootLayer = rootLayer; - if (m_rootLayer) - m_rootLayer->setLayerTreeHost(this); - - if (m_hudLayer) - m_hudLayer->removeFromParent(); - - setNeedsCommit(); -} - -void CCLayerTreeHost::setViewportSize(const IntSize& layoutViewportSize, const IntSize& deviceViewportSize) -{ - if (layoutViewportSize == m_layoutViewportSize && deviceViewportSize == m_deviceViewportSize) - return; - - m_layoutViewportSize = layoutViewportSize; - m_deviceViewportSize = deviceViewportSize; - - setNeedsCommit(); -} - -void CCLayerTreeHost::setPageScaleFactorAndLimits(float pageScaleFactor, float minPageScaleFactor, float maxPageScaleFactor) -{ - if (pageScaleFactor == m_pageScaleFactor && minPageScaleFactor == m_minPageScaleFactor && maxPageScaleFactor == m_maxPageScaleFactor) - return; - - m_pageScaleFactor = pageScaleFactor; - m_minPageScaleFactor = minPageScaleFactor; - m_maxPageScaleFactor = maxPageScaleFactor; - setNeedsCommit(); -} - -void CCLayerTreeHost::setVisible(bool visible) -{ - if (m_visible == visible) - return; - m_visible = visible; - m_proxy->setVisible(visible); -} - -void CCLayerTreeHost::reduceContentsTexturesMemoryOnImplThread(size_t limitBytes, CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - ASSERT(m_contentsTextureManager.get()); - m_contentsTextureManager->reduceMemoryOnImplThread(limitBytes, resourceProvider); -} - -void CCLayerTreeHost::getEvictedContentTexturesBackings(CCPrioritizedTextureManager::BackingVector& evictedBackings) -{ - ASSERT(CCProxy::isImplThread()); - evictedBackings.clear(); - if (m_rendererInitialized) - m_contentsTextureManager->getEvictedBackings(evictedBackings); -} - -void CCLayerTreeHost::unlinkEvictedContentTexturesBackings(const CCPrioritizedTextureManager::BackingVector& evictedBackings) -{ - ASSERT(CCProxy::isMainThread()); - ASSERT(m_contentsTextureManager.get()); - m_contentsTextureManager->unlinkEvictedBackings(evictedBackings); -} - -bool CCLayerTreeHost::deleteEvictedContentTexturesBackings() -{ - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - ASSERT(m_contentsTextureManager.get()); - return m_contentsTextureManager->deleteEvictedBackings(); -} - -void CCLayerTreeHost::startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, double durationSec) -{ - m_proxy->startPageScaleAnimation(targetPosition, useAnchor, scale, durationSec); -} - -void CCLayerTreeHost::loseContext(int numTimes) -{ - TRACE_EVENT1("cc", "CCLayerTreeHost::loseCompositorContext", "numTimes", numTimes); - m_numTimesRecreateShouldFail = numTimes - 1; - m_proxy->loseContext(); -} - -CCPrioritizedTextureManager* CCLayerTreeHost::contentsTextureManager() const -{ - return m_contentsTextureManager.get(); -} - -void CCLayerTreeHost::composite() -{ - ASSERT(!CCThreadProxy::implThread()); - static_cast<CCSingleThreadProxy*>(m_proxy.get())->compositeImmediately(); -} - -void CCLayerTreeHost::scheduleComposite() -{ - m_client->scheduleComposite(); -} - -bool CCLayerTreeHost::initializeRendererIfNeeded() -{ - if (!m_rendererInitialized) { - initializeRenderer(); - // If we couldn't initialize, then bail since we're returning to software mode. - if (!m_rendererInitialized) - return false; - } - if (m_contextLost) { - if (recreateContext() != RecreateSucceeded) - return false; - } - return true; -} - -void CCLayerTreeHost::updateLayers(CCTextureUpdateQueue& queue, size_t memoryAllocationLimitBytes) -{ - ASSERT(m_rendererInitialized); - ASSERT(memoryAllocationLimitBytes); - - if (!rootLayer()) - return; - - if (layoutViewportSize().isEmpty()) - return; - - m_contentsTextureManager->setMaxMemoryLimitBytes(memoryAllocationLimitBytes); - - updateLayers(rootLayer(), queue); -} - -static void setScale(LayerChromium* layer, float deviceScaleFactor, float pageScaleFactor) -{ - if (layer->boundsContainPageScale()) - layer->setContentsScale(deviceScaleFactor); - else - layer->setContentsScale(deviceScaleFactor * pageScaleFactor); -} - -static void updateLayerScale(LayerChromium* layer, float deviceScaleFactor, float pageScaleFactor) -{ - setScale(layer, deviceScaleFactor, pageScaleFactor); - - LayerChromium* maskLayer = layer->maskLayer(); - if (maskLayer) - setScale(maskLayer, deviceScaleFactor, pageScaleFactor); - - LayerChromium* replicaMaskLayer = layer->replicaLayer() ? layer->replicaLayer()->maskLayer() : 0; - if (replicaMaskLayer) - setScale(replicaMaskLayer, deviceScaleFactor, pageScaleFactor); - - const Vector<RefPtr<LayerChromium> >& children = layer->children(); - for (unsigned int i = 0; i < children.size(); ++i) - updateLayerScale(children[i].get(), deviceScaleFactor, pageScaleFactor); -} - -void CCLayerTreeHost::updateLayers(LayerChromium* rootLayer, CCTextureUpdateQueue& queue) -{ - TRACE_EVENT0("cc", "CCLayerTreeHost::updateLayers"); - - updateLayerScale(rootLayer, m_deviceScaleFactor, m_pageScaleFactor); - - LayerList updateList; - - { - TRACE_EVENT0("cc", "CCLayerTreeHost::updateLayers::calcDrawEtc"); - CCLayerTreeHostCommon::calculateDrawTransforms(rootLayer, deviceViewportSize(), m_deviceScaleFactor, rendererCapabilities().maxTextureSize, updateList); - CCLayerTreeHostCommon::calculateVisibleRects(updateList); - } - - // Reset partial texture update requests. - m_partialTextureUpdateRequests = 0; - - bool needMoreUpdates = paintLayerContents(updateList, queue); - if (m_triggerIdleUpdates && needMoreUpdates) - setNeedsCommit(); - - for (size_t i = 0; i < updateList.size(); ++i) - updateList[i]->clearRenderSurface(); -} - -void CCLayerTreeHost::setPrioritiesForSurfaces(size_t surfaceMemoryBytes) -{ - // Surfaces have a place holder for their memory since they are managed - // independantly but should still be tracked and reduce other memory usage. - m_surfaceMemoryPlaceholder->setTextureManager(m_contentsTextureManager.get()); - m_surfaceMemoryPlaceholder->setRequestPriority(CCPriorityCalculator::renderSurfacePriority()); - m_surfaceMemoryPlaceholder->setToSelfManagedMemoryPlaceholder(surfaceMemoryBytes); -} - -void CCLayerTreeHost::setPrioritiesForLayers(const LayerList& updateList) -{ - // Use BackToFront since it's cheap and this isn't order-dependent. - typedef CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, CCLayerIteratorActions::BackToFront> CCLayerIteratorType; - - CCPriorityCalculator calculator; - CCLayerIteratorType end = CCLayerIteratorType::end(&updateList); - for (CCLayerIteratorType it = CCLayerIteratorType::begin(&updateList); it != end; ++it) { - if (it.representsItself()) - it->setTexturePriorities(calculator); - else if (it.representsTargetRenderSurface()) { - if (it->maskLayer()) - it->maskLayer()->setTexturePriorities(calculator); - if (it->replicaLayer() && it->replicaLayer()->maskLayer()) - it->replicaLayer()->maskLayer()->setTexturePriorities(calculator); - } - } -} - -void CCLayerTreeHost::prioritizeTextures(const LayerList& renderSurfaceLayerList, CCOverdrawMetrics& metrics) -{ - m_contentsTextureManager->clearPriorities(); - - size_t memoryForRenderSurfacesMetric = calculateMemoryForRenderSurfaces(renderSurfaceLayerList); - - setPrioritiesForLayers(renderSurfaceLayerList); - setPrioritiesForSurfaces(memoryForRenderSurfacesMetric); - - metrics.didUseContentsTextureMemoryBytes(m_contentsTextureManager->memoryAboveCutoffBytes()); - metrics.didUseRenderSurfaceTextureMemoryBytes(memoryForRenderSurfacesMetric); - - m_contentsTextureManager->prioritizeTextures(); -} - -size_t CCLayerTreeHost::calculateMemoryForRenderSurfaces(const LayerList& updateList) -{ - size_t readbackBytes = 0; - size_t maxBackgroundTextureBytes = 0; - size_t contentsTextureBytes = 0; - - // Start iteration at 1 to skip the root surface as it does not have a texture cost. - for (size_t i = 1; i < updateList.size(); ++i) { - LayerChromium* renderSurfaceLayer = updateList[i].get(); - RenderSurfaceChromium* renderSurface = renderSurfaceLayer->renderSurface(); - - size_t bytes = CCTexture::memorySizeBytes(renderSurface->contentRect().size(), GraphicsContext3D::RGBA); - contentsTextureBytes += bytes; - - if (renderSurfaceLayer->backgroundFilters().isEmpty()) - continue; - - if (bytes > maxBackgroundTextureBytes) - maxBackgroundTextureBytes = bytes; - if (!readbackBytes) - readbackBytes = CCTexture::memorySizeBytes(m_deviceViewportSize, GraphicsContext3D::RGBA); - } - return readbackBytes + maxBackgroundTextureBytes + contentsTextureBytes; -} - -bool CCLayerTreeHost::paintMasksForRenderSurface(LayerChromium* renderSurfaceLayer, CCTextureUpdateQueue& queue) -{ - // Note: Masks and replicas only exist for layers that own render surfaces. If we reach this point - // in code, we already know that at least something will be drawn into this render surface, so the - // mask and replica should be painted. - - bool needMoreUpdates = false; - LayerChromium* maskLayer = renderSurfaceLayer->maskLayer(); - if (maskLayer) { - maskLayer->update(queue, 0, m_renderingStats); - needMoreUpdates |= maskLayer->needMoreUpdates(); - } - - LayerChromium* replicaMaskLayer = renderSurfaceLayer->replicaLayer() ? renderSurfaceLayer->replicaLayer()->maskLayer() : 0; - if (replicaMaskLayer) { - replicaMaskLayer->update(queue, 0, m_renderingStats); - needMoreUpdates |= replicaMaskLayer->needMoreUpdates(); - } - return needMoreUpdates; -} - -bool CCLayerTreeHost::paintLayerContents(const LayerList& renderSurfaceLayerList, CCTextureUpdateQueue& queue) -{ - // Use FrontToBack to allow for testing occlusion and performing culling during the tree walk. - typedef CCLayerIterator<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, CCLayerIteratorActions::FrontToBack> CCLayerIteratorType; - - bool needMoreUpdates = false; - bool recordMetricsForFrame = true; // FIXME: In the future, disable this when about:tracing is off. - CCOcclusionTracker occlusionTracker(m_rootLayer->renderSurface()->contentRect(), recordMetricsForFrame); - occlusionTracker.setMinimumTrackingSize(m_settings.minimumOcclusionTrackingSize); - - prioritizeTextures(renderSurfaceLayerList, occlusionTracker.overdrawMetrics()); - - CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList); - for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) { - occlusionTracker.enterLayer(it); - - if (it.representsTargetRenderSurface()) { - ASSERT(it->renderSurface()->drawOpacity() || it->renderSurface()->drawOpacityIsAnimating()); - needMoreUpdates |= paintMasksForRenderSurface(*it, queue); - } else if (it.representsItself()) { - ASSERT(!it->bounds().isEmpty()); - it->update(queue, &occlusionTracker, m_renderingStats); - needMoreUpdates |= it->needMoreUpdates(); - } - - occlusionTracker.leaveLayer(it); - } - - occlusionTracker.overdrawMetrics().recordMetrics(this); - - return needMoreUpdates; -} - -static LayerChromium* findFirstScrollableLayer(LayerChromium* layer) -{ - if (!layer) - return 0; - - if (layer->scrollable()) - return layer; - - for (size_t i = 0; i < layer->children().size(); ++i) { - LayerChromium* found = findFirstScrollableLayer(layer->children()[i].get()); - if (found) - return found; - } - - return 0; -} - -void CCLayerTreeHost::applyScrollAndScale(const CCScrollAndScaleSet& info) -{ - if (!m_rootLayer) - return; - - LayerChromium* rootScrollLayer = findFirstScrollableLayer(m_rootLayer.get()); - IntSize rootScrollDelta; - - for (size_t i = 0; i < info.scrolls.size(); ++i) { - LayerChromium* layer = CCLayerTreeHostCommon::findLayerInSubtree(m_rootLayer.get(), info.scrolls[i].layerId); - if (!layer) - continue; - if (layer == rootScrollLayer) - rootScrollDelta += info.scrolls[i].scrollDelta; - else - layer->setScrollPosition(layer->scrollPosition() + info.scrolls[i].scrollDelta); - } - if (!rootScrollDelta.isZero() || info.pageScaleDelta != 1) - m_client->applyScrollAndScale(rootScrollDelta, info.pageScaleDelta); -} - -void CCLayerTreeHost::startRateLimiter(WebKit::WebGraphicsContext3D* context) -{ - if (m_animating) - return; - - ASSERT(context); - RateLimiterMap::iterator it = m_rateLimiters.find(context); - if (it != m_rateLimiters.end()) - it->second->start(); - else { - RefPtr<RateLimiter> rateLimiter = RateLimiter::create(context, this); - m_rateLimiters.set(context, rateLimiter); - rateLimiter->start(); - } -} - -void CCLayerTreeHost::stopRateLimiter(WebKit::WebGraphicsContext3D* context) -{ - RateLimiterMap::iterator it = m_rateLimiters.find(context); - if (it != m_rateLimiters.end()) { - it->second->stop(); - m_rateLimiters.remove(it); - } -} - -void CCLayerTreeHost::rateLimit() -{ - // Force a no-op command on the compositor context, so that any ratelimiting commands will wait for the compositing - // context, and therefore for the SwapBuffers. - m_proxy->forceSerializeOnSwapBuffers(); -} - -bool CCLayerTreeHost::bufferedUpdates() -{ - return m_settings.maxPartialTextureUpdates != numeric_limits<size_t>::max(); -} - -bool CCLayerTreeHost::requestPartialTextureUpdate() -{ - if (m_partialTextureUpdateRequests >= m_settings.maxPartialTextureUpdates) - return false; - - m_partialTextureUpdateRequests++; - return true; -} - -void CCLayerTreeHost::deleteTextureAfterCommit(PassOwnPtr<CCPrioritizedTexture> texture) -{ - m_deleteTextureAfterCommitList.append(texture); -} - -void CCLayerTreeHost::setDeviceScaleFactor(float deviceScaleFactor) -{ - if (deviceScaleFactor == m_deviceScaleFactor) - return; - m_deviceScaleFactor = deviceScaleFactor; - - setNeedsCommit(); -} - -void CCLayerTreeHost::animateLayers(double monotonicTime) -{ - if (!CCSettings::acceleratedAnimationEnabled() || !m_needsAnimateLayers) - return; - - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::animateLayers"); - m_needsAnimateLayers = animateLayersRecursive(m_rootLayer.get(), monotonicTime); -} - -bool CCLayerTreeHost::animateLayersRecursive(LayerChromium* current, double monotonicTime) -{ - if (!current) - return false; - - bool subtreeNeedsAnimateLayers = false; - CCLayerAnimationController* currentController = current->layerAnimationController(); - currentController->animate(monotonicTime, 0); - - // If the current controller still has an active animation, we must continue animating layers. - if (currentController->hasActiveAnimation()) - subtreeNeedsAnimateLayers = true; - - for (size_t i = 0; i < current->children().size(); ++i) { - if (animateLayersRecursive(current->children()[i].get(), monotonicTime)) - subtreeNeedsAnimateLayers = true; - } - - return subtreeNeedsAnimateLayers; -} - -void CCLayerTreeHost::setAnimationEventsRecursive(const CCAnimationEventsVector& events, LayerChromium* layer, double wallClockTime) -{ - if (!layer) - return; - - for (size_t eventIndex = 0; eventIndex < events.size(); ++eventIndex) { - if (layer->id() == events[eventIndex].layerId) { - if (events[eventIndex].type == CCAnimationEvent::Started) - layer->notifyAnimationStarted(events[eventIndex], wallClockTime); - else - layer->notifyAnimationFinished(wallClockTime); - } - } - - for (size_t childIndex = 0; childIndex < layer->children().size(); ++childIndex) - setAnimationEventsRecursive(events, layer->children()[childIndex].get(), wallClockTime); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHost.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHost.h deleted file mode 100644 index 9ba1fc206..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHost.h +++ /dev/null @@ -1,324 +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 CCLayerTreeHost_h -#define CCLayerTreeHost_h - -#include "CCAnimationEvents.h" -#include "CCGraphicsContext.h" -#include "CCLayerTreeHostClient.h" -#include "CCLayerTreeHostCommon.h" -#include "CCOcclusionTracker.h" -#include "CCPrioritizedTextureManager.h" -#include "CCProxy.h" -#include "CCRenderingStats.h" -#include "IntRect.h" -#include "RateLimiter.h" -#include "SkColor.h" -#include <limits> -#include <wtf/HashMap.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/PassRefPtr.h> - -namespace WebCore { - -class CCFontAtlas; -class CCLayerChromium; -class CCLayerTreeHostImpl; -class CCLayerTreeHostImplClient; -class CCPrioritizedTextureManager; -class CCTextureUpdateQueue; -class HeadsUpDisplayLayerChromium; -class Region; -struct CCScrollAndScaleSet; - -struct CCLayerTreeSettings { - CCLayerTreeSettings() - : acceleratePainting(false) - , showFPSCounter(false) - , showPlatformLayerTree(false) - , showPaintRects(false) - , showPropertyChangedRects(false) - , showSurfaceDamageRects(false) - , showScreenSpaceRects(false) - , showReplicaScreenSpaceRects(false) - , showOccludingRects(false) - , renderVSyncEnabled(true) - , refreshRate(0) - , maxPartialTextureUpdates(std::numeric_limits<size_t>::max()) - , defaultTileSize(IntSize(256, 256)) - , maxUntiledLayerSize(IntSize(512, 512)) - , minimumOcclusionTrackingSize(IntSize(160, 160)) - { } - - bool acceleratePainting; - bool showFPSCounter; - bool showPlatformLayerTree; - bool showPaintRects; - bool showPropertyChangedRects; - bool showSurfaceDamageRects; - bool showScreenSpaceRects; - bool showReplicaScreenSpaceRects; - bool showOccludingRects; - bool renderVSyncEnabled; - double refreshRate; - size_t maxPartialTextureUpdates; - IntSize defaultTileSize; - IntSize maxUntiledLayerSize; - IntSize minimumOcclusionTrackingSize; - - bool showDebugInfo() const { return showPlatformLayerTree || showFPSCounter || showDebugRects(); } - bool showDebugRects() const { return showPaintRects || showPropertyChangedRects || showSurfaceDamageRects || showScreenSpaceRects || showReplicaScreenSpaceRects || showOccludingRects; } -}; - -// Provides information on an Impl's rendering capabilities back to the CCLayerTreeHost -struct RendererCapabilities { - RendererCapabilities() - : bestTextureFormat(0) - , contextHasCachedFrontBuffer(false) - , usingPartialSwap(false) - , usingAcceleratedPainting(false) - , usingSetVisibility(false) - , usingSwapCompleteCallback(false) - , usingGpuMemoryManager(false) - , usingDiscardFramebuffer(false) - , usingEglImage(false) - , maxTextureSize(0) { } - - GC3Denum bestTextureFormat; - bool contextHasCachedFrontBuffer; - bool usingPartialSwap; - bool usingAcceleratedPainting; - bool usingSetVisibility; - bool usingSwapCompleteCallback; - bool usingGpuMemoryManager; - bool usingDiscardFramebuffer; - bool usingEglImage; - int maxTextureSize; -}; - -class CCLayerTreeHost : public RateLimiterClient { - WTF_MAKE_NONCOPYABLE(CCLayerTreeHost); -public: - static PassOwnPtr<CCLayerTreeHost> create(CCLayerTreeHostClient*, const CCLayerTreeSettings&); - virtual ~CCLayerTreeHost(); - - void setSurfaceReady(); - - // Returns true if any CCLayerTreeHost is alive. - static bool anyLayerTreeHostInstanceExists(); - - static bool needsFilterContext() { return s_needsFilterContext; } - static void setNeedsFilterContext(bool needsFilterContext) { s_needsFilterContext = needsFilterContext; } - bool needsSharedContext() const { return needsFilterContext() || settings().acceleratePainting; } - - // CCLayerTreeHost interface to CCProxy. - void willBeginFrame() { m_client->willBeginFrame(); } - void didBeginFrame() { m_client->didBeginFrame(); } - void updateAnimations(double monotonicFrameBeginTime); - void layout(); - void beginCommitOnImplThread(CCLayerTreeHostImpl*); - void finishCommitOnImplThread(CCLayerTreeHostImpl*); - void willCommit(); - void commitComplete(); - PassOwnPtr<CCGraphicsContext> createContext(); - PassOwnPtr<CCInputHandler> createInputHandler(); - virtual PassOwnPtr<CCLayerTreeHostImpl> createLayerTreeHostImpl(CCLayerTreeHostImplClient*); - void didLoseContext(); - enum RecreateResult { - RecreateSucceeded, - RecreateFailedButTryAgain, - RecreateFailedAndGaveUp, - }; - RecreateResult recreateContext(); - void didCommitAndDrawFrame() { m_client->didCommitAndDrawFrame(); } - void didCompleteSwapBuffers() { m_client->didCompleteSwapBuffers(); } - void deleteContentsTexturesOnImplThread(CCResourceProvider*); - virtual void acquireLayerTextures(); - // Returns false if we should abort this frame due to initialization failure. - bool initializeRendererIfNeeded(); - void updateLayers(CCTextureUpdateQueue&, size_t contentsMemoryLimitBytes); - - CCLayerTreeHostClient* client() { return m_client; } - - // Only used when compositing on the main thread. - void composite(); - void scheduleComposite(); - - // Composites and attempts to read back the result into the provided - // buffer. If it wasn't possible, e.g. due to context lost, will return - // false. - bool compositeAndReadback(void *pixels, const IntRect&); - - void finishAllRendering(); - - int commitNumber() const { return m_commitNumber; } - - void renderingStats(CCRenderingStats&) const; - - const RendererCapabilities& rendererCapabilities() const; - - // Test only hook - void loseContext(int numTimes); - - void setNeedsAnimate(); - // virtual for testing - virtual void setNeedsCommit(); - void setNeedsRedraw(); - bool commitRequested() const; - - void setAnimationEvents(PassOwnPtr<CCAnimationEventsVector>, double wallClockTime); - virtual void didAddAnimation(); - - LayerChromium* rootLayer() { return m_rootLayer.get(); } - const LayerChromium* rootLayer() const { return m_rootLayer.get(); } - void setRootLayer(PassRefPtr<LayerChromium>); - - const CCLayerTreeSettings& settings() const { return m_settings; } - - void setViewportSize(const IntSize& layoutViewportSize, const IntSize& deviceViewportSize); - - const IntSize& layoutViewportSize() const { return m_layoutViewportSize; } - const IntSize& deviceViewportSize() const { return m_deviceViewportSize; } - - void setPageScaleFactorAndLimits(float pageScaleFactor, float minPageScaleFactor, float maxPageScaleFactor); - - void setBackgroundColor(SkColor color) { m_backgroundColor = color; } - - void setHasTransparentBackground(bool transparent) { m_hasTransparentBackground = transparent; } - - CCPrioritizedTextureManager* contentsTextureManager() const; - - // Delete contents textures' backing resources until they use only bytesLimit bytes. This may - // be called on the impl thread while the main thread is running. - void reduceContentsTexturesMemoryOnImplThread(size_t bytesLimit, CCResourceProvider*); - // Retrieve the list of all contents textures' backings that have been evicted, to pass to the - // main thread to unlink them from their owning textures. - void getEvictedContentTexturesBackings(CCPrioritizedTextureManager::BackingVector&); - // Unlink the list of contents textures' backings from their owning textures on the main thread - // before updating layers. - void unlinkEvictedContentTexturesBackings(const CCPrioritizedTextureManager::BackingVector&); - // Deletes all evicted backings, unlinking them from their owning textures if needed. - // Returns true if this function had to unlink any backings from their owning texture when - // destroying them. If this was the case, the impl layer tree may contain invalid resources. - bool deleteEvictedContentTexturesBackings(); - - bool visible() const { return m_visible; } - void setVisible(bool); - - void startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, double durationSec); - - void applyScrollAndScale(const CCScrollAndScaleSet&); - - void startRateLimiter(WebKit::WebGraphicsContext3D*); - void stopRateLimiter(WebKit::WebGraphicsContext3D*); - - // RateLimitClient implementation - virtual void rateLimit() OVERRIDE; - - bool bufferedUpdates(); - bool requestPartialTextureUpdate(); - void deleteTextureAfterCommit(PassOwnPtr<CCPrioritizedTexture>); - - void setDeviceScaleFactor(float); - float deviceScaleFactor() const { return m_deviceScaleFactor; } - - void setFontAtlas(PassOwnPtr<CCFontAtlas>); - - HeadsUpDisplayLayerChromium* hudLayer() const { return m_hudLayer.get(); } - -protected: - CCLayerTreeHost(CCLayerTreeHostClient*, const CCLayerTreeSettings&); - bool initialize(); - -private: - typedef Vector<RefPtr<LayerChromium> > LayerList; - typedef Vector<OwnPtr<CCPrioritizedTexture> > TextureList; - - void initializeRenderer(); - - void update(LayerChromium*, CCTextureUpdateQueue&, const CCOcclusionTracker*); - bool paintLayerContents(const LayerList&, CCTextureUpdateQueue&); - bool paintMasksForRenderSurface(LayerChromium*, CCTextureUpdateQueue&); - - void updateLayers(LayerChromium*, CCTextureUpdateQueue&); - - void prioritizeTextures(const LayerList&, CCOverdrawMetrics&); - void setPrioritiesForSurfaces(size_t surfaceMemoryBytes); - void setPrioritiesForLayers(const LayerList&); - size_t calculateMemoryForRenderSurfaces(const LayerList& updateList); - - void animateLayers(double monotonicTime); - bool animateLayersRecursive(LayerChromium* current, double monotonicTime); - void setAnimationEventsRecursive(const CCAnimationEventsVector&, LayerChromium*, double wallClockTime); - - bool m_animating; - bool m_needsAnimateLayers; - - CCLayerTreeHostClient* m_client; - - int m_commitNumber; - CCRenderingStats m_renderingStats; - - OwnPtr<CCProxy> m_proxy; - bool m_rendererInitialized; - bool m_contextLost; - int m_numTimesRecreateShouldFail; - int m_numFailedRecreateAttempts; - - RefPtr<LayerChromium> m_rootLayer; - RefPtr<HeadsUpDisplayLayerChromium> m_hudLayer; - OwnPtr<CCFontAtlas> m_fontAtlas; - - OwnPtr<CCPrioritizedTextureManager> m_contentsTextureManager; - OwnPtr<CCPrioritizedTexture> m_surfaceMemoryPlaceholder; - - CCLayerTreeSettings m_settings; - - IntSize m_layoutViewportSize; - IntSize m_deviceViewportSize; - float m_deviceScaleFactor; - - bool m_visible; - - typedef HashMap<WebKit::WebGraphicsContext3D*, RefPtr<RateLimiter> > RateLimiterMap; - RateLimiterMap m_rateLimiters; - - float m_pageScaleFactor; - float m_minPageScaleFactor, m_maxPageScaleFactor; - bool m_triggerIdleUpdates; - - SkColor m_backgroundColor; - bool m_hasTransparentBackground; - - TextureList m_deleteTextureAfterCommitList; - size_t m_partialTextureUpdateRequests; - - static bool s_needsFilterContext; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostClient.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostClient.h deleted file mode 100644 index 3d5cb37cb..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostClient.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 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 CCLayerTreeHostClient_h -#define CCLayerTreeHostClient_h - -#include <wtf/PassOwnPtr.h> - -namespace WebKit { -class WebCompositorOutputSurface; -} - -namespace WebCore { -class CCInputHandler; -class IntSize; - -class CCLayerTreeHostClient { -public: - virtual void willBeginFrame() = 0; - // Marks finishing compositing-related tasks on the main thread. In threaded mode, this corresponds to didCommit(). - virtual void didBeginFrame() = 0; - virtual void animate(double frameBeginTime) = 0; - virtual void layout() = 0; - virtual void applyScrollAndScale(const IntSize& scrollDelta, float pageScale) = 0; - virtual PassOwnPtr<WebKit::WebCompositorOutputSurface> createOutputSurface() = 0; - virtual void didRecreateOutputSurface(bool success) = 0; - virtual PassOwnPtr<CCInputHandler> createInputHandler() = 0; - virtual void willCommit() = 0; - virtual void didCommit() = 0; - virtual void didCommitAndDrawFrame() = 0; - virtual void didCompleteSwapBuffers() = 0; - - // Used only in the single-threaded path. - virtual void scheduleComposite() = 0; - -protected: - virtual ~CCLayerTreeHostClient() { } -}; - -} - -#endif // CCLayerTreeHostClient_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostCommon.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostCommon.cpp deleted file mode 100644 index 2140df056..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostCommon.cpp +++ /dev/null @@ -1,905 +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 "CCLayerTreeHostCommon.h" - -#include "CCLayerImpl.h" -#include "CCLayerIterator.h" -#include "CCLayerSorter.h" -#include "CCMathUtil.h" -#include "CCRenderSurface.h" -#include "FloatQuad.h" -#include "IntRect.h" -#include "LayerChromium.h" -#include "RenderSurfaceChromium.h" -#include <public/WebTransformationMatrix.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -IntRect CCLayerTreeHostCommon::calculateVisibleRect(const IntRect& targetSurfaceRect, const IntRect& layerBoundRect, const WebTransformationMatrix& transform) -{ - // Is this layer fully contained within the target surface? - IntRect layerInSurfaceSpace = CCMathUtil::mapClippedRect(transform, layerBoundRect); - if (targetSurfaceRect.contains(layerInSurfaceSpace)) - return layerBoundRect; - - // If the layer doesn't fill up the entire surface, then find the part of - // the surface rect where the layer could be visible. This avoids trying to - // project surface rect points that are behind the projection point. - IntRect minimalSurfaceRect = targetSurfaceRect; - minimalSurfaceRect.intersect(layerInSurfaceSpace); - - // Project the corners of the target surface rect into the layer space. - // This bounding rectangle may be larger than it needs to be (being - // axis-aligned), but is a reasonable filter on the space to consider. - // Non-invertible transforms will create an empty rect here. - const WebTransformationMatrix surfaceToLayer = transform.inverse(); - IntRect layerRect = enclosingIntRect(CCMathUtil::projectClippedRect(surfaceToLayer, FloatRect(minimalSurfaceRect))); - layerRect.intersect(layerBoundRect); - return layerRect; -} - -template<typename LayerType> -static inline bool layerIsInExisting3DRenderingContext(LayerType* layer) -{ - // According to current W3C spec on CSS transforms, a layer is part of an established - // 3d rendering context if its parent has transform-style of preserves-3d. - return layer->parent() && layer->parent()->preserves3D(); -} - -template<typename LayerType> -static bool layerIsRootOfNewRenderingContext(LayerType* layer) -{ - // According to current W3C spec on CSS transforms (Section 6.1), a layer is the - // beginning of 3d rendering context if its parent does not have transform-style: - // preserve-3d, but this layer itself does. - if (layer->parent()) - return !layer->parent()->preserves3D() && layer->preserves3D(); - - return layer->preserves3D(); -} - -template<typename LayerType> -static bool isLayerBackFaceVisible(LayerType* layer) -{ - // The current W3C spec on CSS transforms says that backface visibility should be - // determined differently depending on whether the layer is in a "3d rendering - // context" or not. For Chromium code, we can determine whether we are in a 3d - // rendering context by checking if the parent preserves 3d. - - if (layerIsInExisting3DRenderingContext(layer)) - return layer->drawTransform().isBackFaceVisible(); - - // In this case, either the layer establishes a new 3d rendering context, or is not in - // a 3d rendering context at all. - return layer->transform().isBackFaceVisible(); -} - -template<typename LayerType> -static bool isSurfaceBackFaceVisible(LayerType* layer, const WebTransformationMatrix& drawTransform) -{ - if (layerIsInExisting3DRenderingContext(layer)) - return drawTransform.isBackFaceVisible(); - - if (layerIsRootOfNewRenderingContext(layer)) - return layer->transform().isBackFaceVisible(); - - // If the renderSurface is not part of a new or existing rendering context, then the - // layers that contribute to this surface will decide back-face visibility for themselves. - return false; -} - -template<typename LayerType> -static inline bool layerClipsSubtree(LayerType* layer) -{ - return layer->masksToBounds() || layer->maskLayer(); -} - -template<typename LayerType> -static IntRect calculateVisibleContentRect(LayerType* layer) -{ - ASSERT(layer->renderTarget()); - - IntRect targetSurfaceRect = layer->renderTarget()->renderSurface()->contentRect(); - - targetSurfaceRect.intersect(layer->drawableContentRect()); - - if (targetSurfaceRect.isEmpty() || layer->contentBounds().isEmpty()) - return IntRect(); - - const IntRect contentRect = IntRect(IntPoint(), layer->contentBounds()); - IntRect visibleContentRect = CCLayerTreeHostCommon::calculateVisibleRect(targetSurfaceRect, contentRect, layer->drawTransform()); - return visibleContentRect; -} - -static bool isScaleOrTranslation(const WebTransformationMatrix& m) -{ - return !m.m12() && !m.m13() && !m.m14() - && !m.m21() && !m.m23() && !m.m24() - && !m.m31() && !m.m32() && !m.m43() - && m.m44(); -} - -static inline bool transformToParentIsKnown(CCLayerImpl*) -{ - return true; -} - -static inline bool transformToParentIsKnown(LayerChromium* layer) -{ - return !layer->transformIsAnimating(); -} - -static inline bool transformToScreenIsKnown(CCLayerImpl*) -{ - return true; -} - -static inline bool transformToScreenIsKnown(LayerChromium* layer) -{ - return !layer->screenSpaceTransformIsAnimating(); -} - -template<typename LayerType> -static bool layerShouldBeSkipped(LayerType* layer) -{ - // Layers can be skipped if any of these conditions are met. - // - does not draw content. - // - is transparent - // - has empty bounds - // - the layer is not double-sided, but its back face is visible. - // - // Some additional conditions need to be computed at a later point after the recursion is finished. - // - the intersection of render surface content and layer clipRect is empty - // - the visibleContentRect is empty - // - // Note, if the layer should not have been drawn due to being fully transparent, - // we would have skipped the entire subtree and never made it into this function, - // so it is safe to omit this check here. - - if (!layer->drawsContent() || layer->bounds().isEmpty()) - return true; - - LayerType* backfaceTestLayer = layer; - if (layer->useParentBackfaceVisibility()) { - ASSERT(layer->parent()); - ASSERT(!layer->parent()->useParentBackfaceVisibility()); - backfaceTestLayer = layer->parent(); - } - - // The layer should not be drawn if (1) it is not double-sided and (2) the back of the layer is known to be facing the screen. - if (!backfaceTestLayer->doubleSided() && transformToScreenIsKnown(backfaceTestLayer) && isLayerBackFaceVisible(backfaceTestLayer)) - return true; - - return false; -} - -static inline bool subtreeShouldBeSkipped(CCLayerImpl* layer) -{ - // The opacity of a layer always applies to its children (either implicitly - // via a render surface or explicitly if the parent preserves 3D), so the - // entire subtree can be skipped if this layer is fully transparent. - return !layer->opacity(); -} - -static inline bool subtreeShouldBeSkipped(LayerChromium* layer) -{ - // If the opacity is being animated then the opacity on the main thread is unreliable - // (since the impl thread may be using a different opacity), so it should not be trusted. - // In particular, it should not cause the subtree to be skipped. - return !layer->opacity() && !layer->opacityIsAnimating(); -} - -template<typename LayerType> -static bool subtreeShouldRenderToSeparateSurface(LayerType* layer, bool axisAlignedWithRespectToParent) -{ - // The root layer has a special render surface that is set up externally, so - // it shouldn't be treated as a surface in this code. - if (!layer->parent()) - return false; - - // Cache this value, because otherwise it walks the entire subtree several times. - bool descendantDrawsContent = layer->descendantDrawsContent(); - - // - // A layer and its descendants should render onto a new RenderSurface if any of these rules hold: - // - - // If we force it. - if (layer->forceRenderSurface()) - return true; - - // If the layer uses a mask. - if (layer->maskLayer()) - return true; - - // If the layer has a reflection. - if (layer->replicaLayer()) - return true; - - // If the layer uses a CSS filter. - if (!layer->filters().isEmpty() || !layer->backgroundFilters().isEmpty()) - return true; - - // If the layer flattens its subtree (i.e. the layer doesn't preserve-3d), but it is - // treated as a 3D object by its parent (i.e. parent does preserve-3d). - if (layerIsInExisting3DRenderingContext(layer) && !layer->preserves3D() && descendantDrawsContent) - return true; - - // If the layer clips its descendants but it is not axis-aligned with respect to its parent. - if (layerClipsSubtree(layer) && !axisAlignedWithRespectToParent && descendantDrawsContent) - return true; - - // If the layer has opacity != 1 and does not have a preserves-3d transform style. - if (layer->opacity() != 1 && !layer->preserves3D() && descendantDrawsContent) - return true; - - return false; -} - -WebTransformationMatrix computeScrollCompensationForThisLayer(CCLayerImpl* scrollingLayer, const WebTransformationMatrix& parentMatrix) -{ - // For every layer that has non-zero scrollDelta, we have to compute a transform that can undo the - // scrollDelta translation. In particular, we want this matrix to premultiply a fixed-position layer's - // parentMatrix, so we design this transform in three steps as follows. The steps described here apply - // from right-to-left, so Step 1 would be the right-most matrix: - // - // Step 1. transform from target surface space to the exact space where scrollDelta is actually applied. - // -- this is inverse of the matrix in step 3 - // Step 2. undo the scrollDelta - // -- this is just a translation by scrollDelta. - // Step 3. transform back to target surface space. - // -- this transform is the "partialLayerOriginTransform" = (parentMatrix * scale(layer->pageScaleDelta())); - // - // These steps create a matrix that both start and end in targetSurfaceSpace. So this matrix can - // pre-multiply any fixed-position layer's drawTransform to undo the scrollDeltas -- as long as - // that fixed position layer is fixed onto the same renderTarget as this scrollingLayer. - // - - WebTransformationMatrix partialLayerOriginTransform = parentMatrix; - partialLayerOriginTransform.scale(scrollingLayer->pageScaleDelta()); - - WebTransformationMatrix scrollCompensationForThisLayer = partialLayerOriginTransform; // Step 3 - scrollCompensationForThisLayer.translate(scrollingLayer->scrollDelta().width(), scrollingLayer->scrollDelta().height()); // Step 2 - scrollCompensationForThisLayer.multiply(partialLayerOriginTransform.inverse()); // Step 1 - return scrollCompensationForThisLayer; -} - -WebTransformationMatrix computeScrollCompensationMatrixForChildren(LayerChromium* currentLayer, const WebTransformationMatrix& currentParentMatrix, const WebTransformationMatrix& currentScrollCompensation) -{ - // The main thread (i.e. LayerChromium) does not need to worry about scroll compensation. - // So we can just return an identity matrix here. - return WebTransformationMatrix(); -} - -WebTransformationMatrix computeScrollCompensationMatrixForChildren(CCLayerImpl* layer, const WebTransformationMatrix& parentMatrix, const WebTransformationMatrix& currentScrollCompensationMatrix) -{ - // "Total scroll compensation" is the transform needed to cancel out all scrollDelta translations that - // occurred since the nearest container layer, even if there are renderSurfaces in-between. - // - // There are some edge cases to be aware of, that are not explicit in the code: - // - A layer that is both a fixed-position and container should not be its own container, instead, that means - // it is fixed to an ancestor, and is a container for any fixed-position descendants. - // - A layer that is a fixed-position container and has a renderSurface should behave the same as a container - // without a renderSurface, the renderSurface is irrelevant in that case. - // - A layer that does not have an explicit container is simply fixed to the viewport - // (i.e. the root renderSurface, and it would still compensate for root layer's scrollDelta). - // - If the fixed-position layer has its own renderSurface, then the renderSurface is - // the one who gets fixed. - // - // This function needs to be called AFTER layers create their own renderSurfaces. - // - - // Avoid the overheads (including stack allocation and matrix initialization/copy) if we know that the scroll compensation doesn't need to be reset or adjusted. - if (!layer->isContainerForFixedPositionLayers() && layer->scrollDelta().isZero() && !layer->renderSurface()) - return currentScrollCompensationMatrix; - - // Start as identity matrix. - WebTransformationMatrix nextScrollCompensationMatrix; - - // If this layer is not a container, then it inherits the existing scroll compensations. - if (!layer->isContainerForFixedPositionLayers()) - nextScrollCompensationMatrix = currentScrollCompensationMatrix; - - // If the current layer has a non-zero scrollDelta, then we should compute its local scrollCompensation - // and accumulate it to the nextScrollCompensationMatrix. - if (!layer->scrollDelta().isZero()) { - WebTransformationMatrix scrollCompensationForThisLayer = computeScrollCompensationForThisLayer(layer, parentMatrix); - nextScrollCompensationMatrix.multiply(scrollCompensationForThisLayer); - } - - // If the layer created its own renderSurface, we have to adjust nextScrollCompensationMatrix. - // The adjustment allows us to continue using the scrollCompensation on the next surface. - // Step 1 (right-most in the math): transform from the new surface to the original ancestor surface - // Step 2: apply the scroll compensation - // Step 3: transform back to the new surface. - if (layer->renderSurface() && !nextScrollCompensationMatrix.isIdentity()) - nextScrollCompensationMatrix = layer->renderSurface()->drawTransform().inverse() * nextScrollCompensationMatrix * layer->renderSurface()->drawTransform(); - - return nextScrollCompensationMatrix; -} - -// Should be called just before the recursive calculateDrawTransformsInternal(). -template<typename LayerType, typename LayerList> -void setupRootLayerAndSurfaceForRecursion(LayerType* rootLayer, LayerList& renderSurfaceLayerList, const IntSize& deviceViewportSize) -{ - if (!rootLayer->renderSurface()) - rootLayer->createRenderSurface(); - - rootLayer->renderSurface()->setContentRect(IntRect(IntPoint::zero(), deviceViewportSize)); - rootLayer->renderSurface()->clearLayerList(); - - ASSERT(renderSurfaceLayerList.isEmpty()); - renderSurfaceLayerList.append(rootLayer); -} - -// Recursively walks the layer tree starting at the given node and computes all the -// necessary transformations, clipRects, render surfaces, etc. -template<typename LayerType, typename LayerList, typename RenderSurfaceType, typename LayerSorter> -static void calculateDrawTransformsInternal(LayerType* layer, LayerType* rootLayer, const WebTransformationMatrix& parentMatrix, - const WebTransformationMatrix& fullHierarchyMatrix, const WebTransformationMatrix& currentScrollCompensationMatrix, - const IntRect& clipRectFromAncestor, bool ancestorClipsSubtree, - RenderSurfaceType* nearestAncestorThatMovesPixels, LayerList& renderSurfaceLayerList, LayerList& layerList, - LayerSorter* layerSorter, int maxTextureSize, float deviceScaleFactor, IntRect& drawableContentRectOfSubtree) -{ - // This function computes the new matrix transformations recursively for this - // layer and all its descendants. It also computes the appropriate render surfaces. - // Some important points to remember: - // - // 0. Here, transforms are notated in Matrix x Vector order, and in words we describe what - // the transform does from left to right. - // - // 1. In our terminology, the "layer origin" refers to the top-left corner of a layer, and the - // positive Y-axis points downwards. This interpretation is valid because the orthographic - // projection applied at draw time flips the Y axis appropriately. - // - // 2. The anchor point, when given as a FloatPoint object, is specified in "unit layer space", - // where the bounds of the layer map to [0, 1]. However, as a WebTransformationMatrix object, - // the transform to the anchor point is specified in "pixel layer space", where the bounds - // of the layer map to [bounds.width(), bounds.height()]. - // - // 3. Definition of various transforms used: - // M[parent] is the parent matrix, with respect to the nearest render surface, passed down recursively. - // M[root] is the full hierarchy, with respect to the root, passed down recursively. - // Tr[origin] is the translation matrix from the parent's origin to this layer's origin. - // Tr[origin2anchor] is the translation from the layer's origin to its anchor point - // Tr[origin2center] is the translation from the layer's origin to its center - // M[layer] is the layer's matrix (applied at the anchor point) - // M[sublayer] is the layer's sublayer transform (applied at the layer's center) - // Tr[anchor2center] is the translation offset from the anchor point and the center of the layer - // S[content2layer] is the ratio of a layer's contentBounds() to its bounds(). - // - // Some shortcuts and substitutions are used in the code to reduce matrix multiplications: - // Tr[anchor2center] = Tr[origin2anchor].inverse() * Tr[origin2center] - // - // Some composite transforms can help in understanding the sequence of transforms: - // compositeLayerTransform = Tr[origin2anchor] * M[layer] * Tr[origin2anchor].inverse() - // compositeSublayerTransform = Tr[origin2center] * M[sublayer] * Tr[origin2center].inverse() - // - // In words, the layer transform is applied about the anchor point, and the sublayer transform is - // applied about the center of the layer. - // - // 4. When a layer (or render surface) is drawn, it is drawn into a "target render surface". Therefore the draw - // transform does not necessarily transform from screen space to local layer space. Instead, the draw transform - // is the transform between the "target render surface space" and local layer space. Note that render surfaces, - // except for the root, also draw themselves into a different target render surface, and so their draw - // transform and origin transforms are also described with respect to the target. - // - // Using these definitions, then: - // - // The draw transform for the layer is: - // M[draw] = M[parent] * Tr[origin] * compositeLayerTransform * S[content2layer] - // = M[parent] * Tr[layer->position()] * M[layer] * Tr[anchor2origin] * S[content2layer] - // - // Interpreting the math left-to-right, this transforms from the layer's render surface to the origin of the layer in content space. - // - // The screen space transform is: - // M[screenspace] = M[root] * Tr[origin] * compositeLayerTransform * S[content2layer] - // = M[root] * Tr[layer->position()] * M[layer] * Tr[origin2anchor].inverse() * S[content2layer] - // - // Interpreting the math left-to-right, this transforms from the root render surface's content space to the local layer's origin in layer space. - // - // The transform hierarchy that is passed on to children (i.e. the child's parentMatrix) is: - // M[parent]_for_child = M[parent] * Tr[origin] * compositeLayerTransform * compositeSublayerTransform - // = M[parent] * Tr[layer->position()] * M[layer] * Tr[anchor2center] * M[sublayer] * Tr[origin2center].inverse() - // = M[draw] * M[sublayer] * Tr[origin2center].inverse() - // - // and a similar matrix for the full hierarchy with respect to the root. - // - // Finally, note that the final matrix used by the shader for the layer is P * M[draw] * S . This final product - // is computed in drawTexturedQuad(), where: - // P is the projection matrix - // S is the scale adjustment (to scale up to the layer size) - // - // When a render surface has a replica layer, that layer's transform is used to draw a second copy of the surface. - // Transforms named here are relative to the surface, unless they specify they are relative to the replica layer. - // - // We will denote a scale by device scale S[deviceScale] - // - // The render surface draw transform to its target surface origin is: - // M[surfaceDraw] = M[owningLayer->Draw] - // - // The render surface origin transform to its the root (screen space) origin is: - // M[surface2root] = M[owningLayer->screenspace] * S[deviceScale].inverse() - // - // The replica draw transform to its target surface origin is: - // M[replicaDraw] = S[deviceScale] * M[surfaceDraw] * Tr[replica->position() + replica->anchor()] * Tr[replica] * Tr[origin2anchor].inverse() * S[contentsScale].inverse() - // - // The replica draw transform to the root (screen space) origin is: - // M[replica2root] = M[surface2root] * Tr[replica->position()] * Tr[replica] * Tr[origin2anchor].inverse() - // - - // If we early-exit anywhere in this function, the drawableContentRect of this subtree should be considered empty. - drawableContentRectOfSubtree = IntRect(); - - if (subtreeShouldBeSkipped(layer)) - return; - - IntRect clipRectForSubtree; - bool subtreeShouldBeClipped = false; - - float drawOpacity = layer->opacity(); - bool drawOpacityIsAnimating = layer->opacityIsAnimating(); - if (layer->parent() && layer->parent()->preserves3D()) { - drawOpacity *= layer->parent()->drawOpacity(); - drawOpacityIsAnimating |= layer->parent()->drawOpacityIsAnimating(); - } - - IntSize bounds = layer->bounds(); - FloatPoint anchorPoint = layer->anchorPoint(); - FloatPoint position = layer->position() - layer->scrollDelta(); - - // Offset between anchor point and the center of the quad. - float centerOffsetX = (0.5 - anchorPoint.x()) * bounds.width(); - float centerOffsetY = (0.5 - anchorPoint.y()) * bounds.height(); - - WebTransformationMatrix layerLocalTransform; - // LT = S[pageScaleDelta] - layerLocalTransform.scale(layer->pageScaleDelta()); - // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor] - layerLocalTransform.translate3d(position.x() + anchorPoint.x() * bounds.width(), position.y() + anchorPoint.y() * bounds.height(), layer->anchorPointZ()); - // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor] * M[layer] - layerLocalTransform.multiply(layer->transform()); - // LT = S[pageScaleDelta] * Tr[origin] * Tr[origin2anchor] * M[layer] * Tr[anchor2center] - layerLocalTransform.translate3d(centerOffsetX, centerOffsetY, -layer->anchorPointZ()); - - WebTransformationMatrix combinedTransform = parentMatrix; - combinedTransform.multiply(layerLocalTransform); - - if (layer->fixedToContainerLayer()) { - // Special case: this layer is a composited fixed-position layer; we need to - // explicitly compensate for all ancestors' nonzero scrollDeltas to keep this layer - // fixed correctly. - combinedTransform = currentScrollCompensationMatrix * combinedTransform; - } - - // The drawTransform that gets computed below is effectively the layer's drawTransform, unless - // the layer itself creates a renderSurface. In that case, the renderSurface re-parents the transforms. - WebTransformationMatrix drawTransform = combinedTransform; - // M[draw] = M[parent] * LT * Tr[anchor2center] * Tr[center2origin] - drawTransform.translate(-layer->bounds().width() / 2.0, -layer->bounds().height() / 2.0); - if (!layer->contentBounds().isEmpty() && !layer->bounds().isEmpty()) { - // M[draw] = M[parent] * LT * Tr[anchor2origin] * S[layer2content] - drawTransform.scaleNonUniform(layer->bounds().width() / static_cast<double>(layer->contentBounds().width()), - layer->bounds().height() / static_cast<double>(layer->contentBounds().height())); - } - - // layerScreenSpaceTransform represents the transform between root layer's "screen space" and local content space. - WebTransformationMatrix layerScreenSpaceTransform = fullHierarchyMatrix; - if (!layer->preserves3D()) - CCMathUtil::flattenTransformTo2d(layerScreenSpaceTransform); - layerScreenSpaceTransform.multiply(drawTransform); - layer->setScreenSpaceTransform(layerScreenSpaceTransform); - - bool animatingTransformToTarget = layer->transformIsAnimating(); - bool animatingTransformToScreen = animatingTransformToTarget; - if (layer->parent()) { - animatingTransformToTarget |= layer->parent()->drawTransformIsAnimating(); - animatingTransformToScreen |= layer->parent()->screenSpaceTransformIsAnimating(); - } - - FloatRect contentRect(FloatPoint(), layer->contentBounds()); - - // fullHierarchyMatrix is the matrix that transforms objects between screen space (except projection matrix) and the most recent RenderSurface's space. - // nextHierarchyMatrix will only change if this layer uses a new RenderSurface, otherwise remains the same. - WebTransformationMatrix nextHierarchyMatrix = fullHierarchyMatrix; - WebTransformationMatrix sublayerMatrix; - - if (subtreeShouldRenderToSeparateSurface(layer, isScaleOrTranslation(combinedTransform))) { - // Check back-face visibility before continuing with this surface and its subtree - if (!layer->doubleSided() && transformToParentIsKnown(layer) && isSurfaceBackFaceVisible(layer, combinedTransform)) - return; - - if (!layer->renderSurface()) - layer->createRenderSurface(); - - RenderSurfaceType* renderSurface = layer->renderSurface(); - renderSurface->clearLayerList(); - - // The origin of the new surface is the upper left corner of the layer. - renderSurface->setDrawTransform(drawTransform); - WebTransformationMatrix layerDrawTransform; - layerDrawTransform.scale(deviceScaleFactor); - if (!layer->contentBounds().isEmpty() && !layer->bounds().isEmpty()) { - layerDrawTransform.scaleNonUniform(layer->bounds().width() / static_cast<double>(layer->contentBounds().width()), - layer->bounds().height() / static_cast<double>(layer->contentBounds().height())); - } - layer->setDrawTransform(layerDrawTransform); - - // The sublayer matrix transforms centered layer rects into target - // surface content space. - sublayerMatrix.makeIdentity(); - sublayerMatrix.scale(deviceScaleFactor); - sublayerMatrix.translate(0.5 * bounds.width(), 0.5 * bounds.height()); - - // The opacity value is moved from the layer to its surface, so that the entire subtree properly inherits opacity. - renderSurface->setDrawOpacity(drawOpacity); - renderSurface->setDrawOpacityIsAnimating(drawOpacityIsAnimating); - layer->setDrawOpacity(1); - layer->setDrawOpacityIsAnimating(false); - - renderSurface->setTargetSurfaceTransformsAreAnimating(animatingTransformToTarget); - renderSurface->setScreenSpaceTransformsAreAnimating(animatingTransformToScreen); - animatingTransformToTarget = false; - layer->setDrawTransformIsAnimating(animatingTransformToTarget); - layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen); - - // Update the aggregate hierarchy matrix to include the transform of the - // newly created RenderSurface. - nextHierarchyMatrix.multiply(renderSurface->drawTransform()); - - // The new renderSurface here will correctly clip the entire subtree. So, we do - // not need to continue propagating the clipping state further down the tree. This - // way, we can avoid transforming clipRects from ancestor target surface space to - // current target surface space that could cause more w < 0 headaches. - subtreeShouldBeClipped = false; - - if (layer->maskLayer()) - layer->maskLayer()->setRenderTarget(layer); - - if (layer->replicaLayer() && layer->replicaLayer()->maskLayer()) - layer->replicaLayer()->maskLayer()->setRenderTarget(layer); - - if (layer->filters().hasFilterThatMovesPixels()) - nearestAncestorThatMovesPixels = renderSurface; - - renderSurface->setNearestAncestorThatMovesPixels(nearestAncestorThatMovesPixels); - - renderSurfaceLayerList.append(layer); - } else { - layer->setDrawTransform(drawTransform); - layer->setDrawTransformIsAnimating(animatingTransformToTarget); - layer->setScreenSpaceTransformIsAnimating(animatingTransformToScreen); - sublayerMatrix = combinedTransform; - - layer->setDrawOpacity(drawOpacity); - layer->setDrawOpacityIsAnimating(drawOpacityIsAnimating); - - if (layer != rootLayer) { - ASSERT(layer->parent()); - layer->clearRenderSurface(); - - // Layers without renderSurfaces directly inherit the ancestor's clip status. - subtreeShouldBeClipped = ancestorClipsSubtree; - if (ancestorClipsSubtree) - clipRectForSubtree = clipRectFromAncestor; - - // Layers that are not their own renderTarget will render into the target of their nearest ancestor. - layer->setRenderTarget(layer->parent()->renderTarget()); - } else { - // FIXME: This root layer special case code should eventually go away. https://bugs.webkit.org/show_bug.cgi?id=92290 - ASSERT(!layer->parent()); - ASSERT(layer->renderSurface()); - ASSERT(ancestorClipsSubtree); - layer->renderSurface()->setClipRect(clipRectFromAncestor); - subtreeShouldBeClipped = false; - } - } - - IntRect rectInTargetSpace = enclosingIntRect(CCMathUtil::mapClippedRect(layer->drawTransform(), contentRect)); - - if (layerClipsSubtree(layer)) { - subtreeShouldBeClipped = true; - if (ancestorClipsSubtree && !layer->renderSurface()) { - clipRectForSubtree = clipRectFromAncestor; - clipRectForSubtree.intersect(rectInTargetSpace); - } else - clipRectForSubtree = rectInTargetSpace; - } - - // Flatten to 2D if the layer doesn't preserve 3D. - if (!layer->preserves3D()) - CCMathUtil::flattenTransformTo2d(sublayerMatrix); - - // Apply the sublayer transform at the center of the layer. - sublayerMatrix.multiply(layer->sublayerTransform()); - - // The coordinate system given to children is located at the layer's origin, not the center. - sublayerMatrix.translate3d(-bounds.width() * 0.5, -bounds.height() * 0.5, 0); - - LayerList& descendants = (layer->renderSurface() ? layer->renderSurface()->layerList() : layerList); - - // Any layers that are appended after this point are in the layer's subtree and should be included in the sorting process. - unsigned sortingStartIndex = descendants.size(); - - if (!layerShouldBeSkipped(layer)) - descendants.append(layer); - - WebTransformationMatrix nextScrollCompensationMatrix = computeScrollCompensationMatrixForChildren(layer, parentMatrix, currentScrollCompensationMatrix);; - - IntRect accumulatedDrawableContentRectOfChildren; - for (size_t i = 0; i < layer->children().size(); ++i) { - LayerType* child = layer->children()[i].get(); - IntRect drawableContentRectOfChildSubtree; - calculateDrawTransformsInternal<LayerType, LayerList, RenderSurfaceType, LayerSorter>(child, rootLayer, sublayerMatrix, nextHierarchyMatrix, nextScrollCompensationMatrix, - clipRectForSubtree, subtreeShouldBeClipped, nearestAncestorThatMovesPixels, - renderSurfaceLayerList, descendants, layerSorter, maxTextureSize, deviceScaleFactor, drawableContentRectOfChildSubtree); - if (!drawableContentRectOfChildSubtree.isEmpty()) { - accumulatedDrawableContentRectOfChildren.unite(drawableContentRectOfChildSubtree); - if (child->renderSurface()) - descendants.append(child); - } - } - - // Compute the total drawableContentRect for this subtree (the rect is in targetSurface space) - IntRect localDrawableContentRectOfSubtree = accumulatedDrawableContentRectOfChildren; - if (layer->drawsContent()) - localDrawableContentRectOfSubtree.unite(rectInTargetSpace); - if (subtreeShouldBeClipped) - localDrawableContentRectOfSubtree.intersect(clipRectForSubtree); - - // Compute the layer's drawable content rect (the rect is in targetSurface space) - IntRect drawableContentRectOfLayer = rectInTargetSpace; - if (subtreeShouldBeClipped) - drawableContentRectOfLayer.intersect(clipRectForSubtree); - layer->setDrawableContentRect(drawableContentRectOfLayer); - - // Compute the remaining properties for the render surface, if the layer has one. - if (layer->renderSurface() && layer != rootLayer) { - RenderSurfaceType* renderSurface = layer->renderSurface(); - IntRect clippedContentRect = localDrawableContentRectOfSubtree; - - // The render surface clipRect is expressed in the space where this surface draws, i.e. the same space as clipRectFromAncestor. - if (ancestorClipsSubtree) - renderSurface->setClipRect(clipRectFromAncestor); - else - renderSurface->setClipRect(IntRect()); - - // Don't clip if the layer is reflected as the reflection shouldn't be - // clipped. If the layer is animating, then the surface's transform to - // its target is not known on the main thread, and we should not use it - // to clip. - if (!layer->replicaLayer() && transformToParentIsKnown(layer)) { - // Note, it is correct to use ancestorClipsSubtree here, because we are looking at this layer's renderSurface, not the layer itself. - if (ancestorClipsSubtree && !clippedContentRect.isEmpty()) { - IntRect surfaceClipRect = CCLayerTreeHostCommon::calculateVisibleRect(renderSurface->clipRect(), clippedContentRect, renderSurface->drawTransform()); - clippedContentRect.intersect(surfaceClipRect); - } - } - - // The RenderSurface backing texture cannot exceed the maximum supported - // texture size. - clippedContentRect.setWidth(std::min(clippedContentRect.width(), maxTextureSize)); - clippedContentRect.setHeight(std::min(clippedContentRect.height(), maxTextureSize)); - - if (clippedContentRect.isEmpty()) - renderSurface->clearLayerList(); - - renderSurface->setContentRect(clippedContentRect); - renderSurface->setScreenSpaceTransform(layer->screenSpaceTransform()); - - if (layer->replicaLayer()) { - WebTransformationMatrix surfaceOriginToReplicaOriginTransform; - surfaceOriginToReplicaOriginTransform.scale(deviceScaleFactor); - surfaceOriginToReplicaOriginTransform.translate(layer->replicaLayer()->position().x() + layer->replicaLayer()->anchorPoint().x() * bounds.width(), - layer->replicaLayer()->position().y() + layer->replicaLayer()->anchorPoint().y() * bounds.height()); - surfaceOriginToReplicaOriginTransform.multiply(layer->replicaLayer()->transform()); - surfaceOriginToReplicaOriginTransform.translate(-layer->replicaLayer()->anchorPoint().x() * bounds.width(), -layer->replicaLayer()->anchorPoint().y() * bounds.height()); - surfaceOriginToReplicaOriginTransform.scale(1 / deviceScaleFactor); - - // Compute the replica's "originTransform" that maps from the replica's origin space to the target surface origin space. - WebTransformationMatrix replicaOriginTransform = layer->renderSurface()->drawTransform() * surfaceOriginToReplicaOriginTransform; - renderSurface->setReplicaDrawTransform(replicaOriginTransform); - - // Compute the replica's "screenSpaceTransform" that maps from the replica's origin space to the screen's origin space. - WebTransformationMatrix replicaScreenSpaceTransform = layer->renderSurface()->screenSpaceTransform() * surfaceOriginToReplicaOriginTransform; - renderSurface->setReplicaScreenSpaceTransform(replicaScreenSpaceTransform); - } - - // If a render surface has no layer list, then it and none of its children needed to get drawn. - if (!layer->renderSurface()->layerList().size()) { - // FIXME: Originally we asserted that this layer was already at the end of the - // list, and only needed to remove that layer. For now, we remove the - // entire subtree of surfaces to fix a crash bug. The root cause is - // https://bugs.webkit.org/show_bug.cgi?id=74147 and we should be able - // to put the original assert after fixing that. - while (renderSurfaceLayerList.last() != layer) { - renderSurfaceLayerList.last()->clearRenderSurface(); - renderSurfaceLayerList.removeLast(); - } - ASSERT(renderSurfaceLayerList.last() == layer); - renderSurfaceLayerList.removeLast(); - layer->clearRenderSurface(); - return; - } - } - - // If neither this layer nor any of its children were added, early out. - if (sortingStartIndex == descendants.size()) - return; - - // If preserves-3d then sort all the descendants in 3D so that they can be - // drawn from back to front. If the preserves-3d property is also set on the parent then - // skip the sorting as the parent will sort all the descendants anyway. - if (descendants.size() && layer->preserves3D() && (!layer->parent() || !layer->parent()->preserves3D())) - sortLayers(&descendants.at(sortingStartIndex), descendants.end(), layerSorter); - - if (layer->renderSurface()) - drawableContentRectOfSubtree = enclosingIntRect(layer->renderSurface()->drawableContentRect()); - else - drawableContentRectOfSubtree = localDrawableContentRectOfSubtree; - - return; -} - -// FIXME: Instead of using the following function to set visibility rects on a second -// tree pass, revise calculateVisibleContentRect() so that this can be done in a single -// pass inside calculateDrawTransformsInternal<>(). -template<typename LayerType, typename LayerList, typename RenderSurfaceType> -static void calculateVisibleRectsInternal(const LayerList& renderSurfaceLayerList) -{ - // Use BackToFront since it's cheap and this isn't order-dependent. - typedef CCLayerIterator<LayerType, LayerList, RenderSurfaceType, CCLayerIteratorActions::BackToFront> CCLayerIteratorType; - - CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList); - for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) { - if (it.representsTargetRenderSurface()) { - LayerType* maskLayer = it->maskLayer(); - if (maskLayer) - maskLayer->setVisibleContentRect(IntRect(IntPoint(), it->contentBounds())); - LayerType* replicaMaskLayer = it->replicaLayer() ? it->replicaLayer()->maskLayer() : 0; - if (replicaMaskLayer) - replicaMaskLayer->setVisibleContentRect(IntRect(IntPoint(), it->contentBounds())); - } else if (it.representsItself()) { - IntRect visibleContentRect = calculateVisibleContentRect(*it); - it->setVisibleContentRect(visibleContentRect); - } - } -} - -void CCLayerTreeHostCommon::calculateDrawTransforms(LayerChromium* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, int maxTextureSize, Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList) -{ - IntRect totalDrawableContentRect; - WebTransformationMatrix identityMatrix; - WebTransformationMatrix deviceScaleTransform; - deviceScaleTransform.scale(deviceScaleFactor); - - setupRootLayerAndSurfaceForRecursion<LayerChromium, Vector<RefPtr<LayerChromium> > >(rootLayer, renderSurfaceLayerList, deviceViewportSize); - - WebCore::calculateDrawTransformsInternal<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium, void>(rootLayer, rootLayer, deviceScaleTransform, identityMatrix, identityMatrix, - rootLayer->renderSurface()->contentRect(), true, 0, renderSurfaceLayerList, - rootLayer->renderSurface()->layerList(), 0, maxTextureSize, deviceScaleFactor, totalDrawableContentRect); -} - -void CCLayerTreeHostCommon::calculateDrawTransforms(CCLayerImpl* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, CCLayerSorter* layerSorter, int maxTextureSize, Vector<CCLayerImpl*>& renderSurfaceLayerList) -{ - IntRect totalDrawableContentRect; - WebTransformationMatrix identityMatrix; - WebTransformationMatrix deviceScaleTransform; - deviceScaleTransform.scale(deviceScaleFactor); - - setupRootLayerAndSurfaceForRecursion<CCLayerImpl, Vector<CCLayerImpl*> >(rootLayer, renderSurfaceLayerList, deviceViewportSize); - - WebCore::calculateDrawTransformsInternal<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, CCLayerSorter>(rootLayer, rootLayer, deviceScaleTransform, identityMatrix, identityMatrix, - rootLayer->renderSurface()->contentRect(), true, 0, renderSurfaceLayerList, - rootLayer->renderSurface()->layerList(), layerSorter, maxTextureSize, deviceScaleFactor, totalDrawableContentRect); -} - -void CCLayerTreeHostCommon::calculateVisibleRects(Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList) -{ - calculateVisibleRectsInternal<LayerChromium, Vector<RefPtr<LayerChromium> >, RenderSurfaceChromium>(renderSurfaceLayerList); -} - -void CCLayerTreeHostCommon::calculateVisibleRects(Vector<CCLayerImpl*>& renderSurfaceLayerList) -{ - calculateVisibleRectsInternal<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface>(renderSurfaceLayerList); -} - -static bool pointHitsRect(const IntPoint& viewportPoint, const WebTransformationMatrix& localSpaceToScreenSpaceTransform, FloatRect localSpaceRect) -{ - // If the transform is not invertible, then assume that this point doesn't hit this rect. - if (!localSpaceToScreenSpaceTransform.isInvertible()) - return false; - - // Transform the hit test point from screen space to the local space of the given rect. - bool clipped = false; - FloatPoint hitTestPointInLocalSpace = CCMathUtil::projectPoint(localSpaceToScreenSpaceTransform.inverse(), FloatPoint(viewportPoint), clipped); - - // If projectPoint could not project to a valid value, then we assume that this point doesn't hit this rect. - if (clipped) - return false; - - return localSpaceRect.contains(hitTestPointInLocalSpace); -} - -static bool pointIsClippedBySurfaceOrClipRect(const IntPoint& viewportPoint, CCLayerImpl* layer) -{ - CCLayerImpl* currentLayer = layer; - - // Walk up the layer tree and hit-test any renderSurfaces and any layer clipRects that are active. - while (currentLayer) { - if (currentLayer->renderSurface() && !pointHitsRect(viewportPoint, currentLayer->renderSurface()->screenSpaceTransform(), currentLayer->renderSurface()->contentRect())) - return true; - - // Note that drawableContentRects are actually in targetSurface space, so the transform we - // have to provide is the target surface's screenSpaceTransform. - CCLayerImpl* renderTarget = currentLayer->renderTarget(); - if (layerClipsSubtree(currentLayer) && !pointHitsRect(viewportPoint, renderTarget->renderSurface()->screenSpaceTransform(), currentLayer->drawableContentRect())) - return true; - - currentLayer = currentLayer->parent(); - } - - // If we have finished walking all ancestors without having already exited, then the point is not clipped by any ancestors. - return false; -} - -CCLayerImpl* CCLayerTreeHostCommon::findLayerThatIsHitByPoint(const IntPoint& viewportPoint, Vector<CCLayerImpl*>& renderSurfaceLayerList) -{ - CCLayerImpl* foundLayer = 0; - - typedef CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, CCLayerIteratorActions::FrontToBack> CCLayerIteratorType; - CCLayerIteratorType end = CCLayerIteratorType::end(&renderSurfaceLayerList); - - for (CCLayerIteratorType it = CCLayerIteratorType::begin(&renderSurfaceLayerList); it != end; ++it) { - // We don't want to consider renderSurfaces for hit testing. - if (!it.representsItself()) - continue; - - CCLayerImpl* currentLayer = (*it); - - FloatRect contentRect(FloatPoint::zero(), currentLayer->contentBounds()); - if (!pointHitsRect(viewportPoint, currentLayer->screenSpaceTransform(), contentRect)) - continue; - - // At this point, we think the point does hit the layer, but we need to walk up - // the parents to ensure that the layer was not clipped in such a way that the - // hit point actually should not hit the layer. - if (pointIsClippedBySurfaceOrClipRect(viewportPoint, currentLayer)) - continue; - - foundLayer = currentLayer; - break; - } - - // This can potentially return 0, which means the viewportPoint did not successfully hit test any layers, not even the root layer. - return foundLayer; -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostCommon.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostCommon.h deleted file mode 100644 index 4e96904a6..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostCommon.h +++ /dev/null @@ -1,105 +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 CCLayerTreeHostCommon_h -#define CCLayerTreeHostCommon_h - -#include "IntRect.h" -#include "IntSize.h" -#include <public/WebTransformationMatrix.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { - -class CCLayerImpl; -class CCLayerSorter; -class LayerChromium; - -class CCLayerTreeHostCommon { -public: - static IntRect calculateVisibleRect(const IntRect& targetSurfaceRect, const IntRect& layerBoundRect, const WebKit::WebTransformationMatrix&); - - static void calculateDrawTransforms(LayerChromium* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, int maxTextureSize, Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList); - static void calculateDrawTransforms(CCLayerImpl* rootLayer, const IntSize& deviceViewportSize, float deviceScaleFactor, CCLayerSorter*, int maxTextureSize, Vector<CCLayerImpl*>& renderSurfaceLayerList); - - static void calculateVisibleRects(Vector<CCLayerImpl*>& renderSurfaceLayerList); - static void calculateVisibleRects(Vector<RefPtr<LayerChromium> >& renderSurfaceLayerList); - - // Performs hit testing for a given renderSurfaceLayerList. - static CCLayerImpl* findLayerThatIsHitByPoint(const IntPoint& viewportPoint, Vector<CCLayerImpl*>& renderSurfaceLayerList); - - template<typename LayerType> static bool renderSurfaceContributesToTarget(LayerType*, int targetSurfaceLayerID); - - // Returns a layer with the given id if one exists in the subtree starting - // from the given root layer (including mask and replica layers). - template<typename LayerType> static LayerType* findLayerInSubtree(LayerType* rootLayer, int layerId); - - struct ScrollUpdateInfo { - int layerId; - IntSize scrollDelta; - }; -}; - -struct CCScrollAndScaleSet { - Vector<CCLayerTreeHostCommon::ScrollUpdateInfo> scrolls; - float pageScaleDelta; -}; - -template<typename LayerType> -bool CCLayerTreeHostCommon::renderSurfaceContributesToTarget(LayerType* layer, int targetSurfaceLayerID) -{ - // A layer will either contribute its own content, or its render surface's content, to - // the target surface. The layer contributes its surface's content when both the - // following are true: - // (1) The layer actually has a renderSurface, and - // (2) The layer's renderSurface is not the same as the targetSurface. - // - // Otherwise, the layer just contributes itself to the target surface. - - return layer->renderSurface() && layer->id() != targetSurfaceLayerID; -} - -template<typename LayerType> -LayerType* CCLayerTreeHostCommon::findLayerInSubtree(LayerType* rootLayer, int layerId) -{ - if (rootLayer->id() == layerId) - return rootLayer; - - if (rootLayer->maskLayer() && rootLayer->maskLayer()->id() == layerId) - return rootLayer->maskLayer(); - - if (rootLayer->replicaLayer() && rootLayer->replicaLayer()->id() == layerId) - return rootLayer->replicaLayer(); - - for (size_t i = 0; i < rootLayer->children().size(); ++i) { - if (LayerType* found = findLayerInSubtree(rootLayer->children()[i].get(), layerId)) - return found; - } - return 0; -} - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostImpl.cpp deleted file mode 100644 index cc92804c2..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostImpl.cpp +++ /dev/null @@ -1,1299 +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 "CCLayerTreeHostImpl.h" - -#include "CCAppendQuadsData.h" -#include "CCDamageTracker.h" -#include "CCDebugRectHistory.h" -#include "CCDelayBasedTimeSource.h" -#include "CCFontAtlas.h" -#include "CCFrameRateCounter.h" -#include "CCHeadsUpDisplayLayerImpl.h" -#include "CCLayerIterator.h" -#include "CCLayerTreeHost.h" -#include "CCLayerTreeHostCommon.h" -#include "CCMathUtil.h" -#include "CCOverdrawMetrics.h" -#include "CCPageScaleAnimation.h" -#include "CCPrioritizedTextureManager.h" -#include "CCRenderPassDrawQuad.h" -#include "CCRendererGL.h" -#include "CCRenderingStats.h" -#include "CCScrollbarAnimationController.h" -#include "CCScrollbarLayerImpl.h" -#include "CCSettings.h" -#include "CCSingleThreadProxy.h" -#include "TextStream.h" -#include "TraceEvent.h" -#include <wtf/CurrentTime.h> - -using WebKit::WebTransformationMatrix; - -namespace { - -void didVisibilityChange(WebCore::CCLayerTreeHostImpl* id, bool visible) -{ - if (visible) { - TRACE_EVENT_ASYNC_BEGIN1("webkit", "CCLayerTreeHostImpl::setVisible", id, "CCLayerTreeHostImpl", id); - return; - } - - TRACE_EVENT_ASYNC_END0("webkit", "CCLayerTreeHostImpl::setVisible", id); -} - -} // namespace - -namespace WebCore { - -class CCLayerTreeHostImplTimeSourceAdapter : public CCTimeSourceClient { - WTF_MAKE_NONCOPYABLE(CCLayerTreeHostImplTimeSourceAdapter); -public: - static PassOwnPtr<CCLayerTreeHostImplTimeSourceAdapter> create(CCLayerTreeHostImpl* layerTreeHostImpl, PassRefPtr<CCDelayBasedTimeSource> timeSource) - { - return adoptPtr(new CCLayerTreeHostImplTimeSourceAdapter(layerTreeHostImpl, timeSource)); - } - virtual ~CCLayerTreeHostImplTimeSourceAdapter() - { - m_timeSource->setClient(0); - m_timeSource->setActive(false); - } - - virtual void onTimerTick() OVERRIDE - { - // FIXME: We require that animate be called on the impl thread. This - // avoids asserts in single threaded mode. Ideally background ticking - // would be handled by the proxy/scheduler and this could be removed. - DebugScopedSetImplThread impl; - - m_layerTreeHostImpl->animate(monotonicallyIncreasingTime(), currentTime()); - } - - void setActive(bool active) - { - if (active != m_timeSource->active()) - m_timeSource->setActive(active); - } - -private: - CCLayerTreeHostImplTimeSourceAdapter(CCLayerTreeHostImpl* layerTreeHostImpl, PassRefPtr<CCDelayBasedTimeSource> timeSource) - : m_layerTreeHostImpl(layerTreeHostImpl) - , m_timeSource(timeSource) - { - m_timeSource->setClient(this); - } - - CCLayerTreeHostImpl* m_layerTreeHostImpl; - RefPtr<CCDelayBasedTimeSource> m_timeSource; -}; - -PassOwnPtr<CCLayerTreeHostImpl> CCLayerTreeHostImpl::create(const CCLayerTreeSettings& settings, CCLayerTreeHostImplClient* client) -{ - return adoptPtr(new CCLayerTreeHostImpl(settings, client)); -} - -CCLayerTreeHostImpl::CCLayerTreeHostImpl(const CCLayerTreeSettings& settings, CCLayerTreeHostImplClient* client) - : m_client(client) - , m_sourceFrameNumber(-1) - , m_rootScrollLayerImpl(0) - , m_currentlyScrollingLayerImpl(0) - , m_hudLayerImpl(0) - , m_scrollingLayerIdFromPreviousTree(-1) - , m_scrollDeltaIsInScreenSpace(false) - , m_settings(settings) - , m_deviceScaleFactor(1) - , m_visible(true) - , m_contentsTexturesPurged(false) - , m_memoryAllocationLimitBytes(CCPrioritizedTextureManager::defaultMemoryAllocationLimit()) - , m_pageScale(1) - , m_pageScaleDelta(1) - , m_sentPageScaleDelta(1) - , m_minPageScale(0) - , m_maxPageScale(0) - , m_backgroundColor(0) - , m_hasTransparentBackground(false) - , m_needsAnimateLayers(false) - , m_pinchGestureActive(false) - , m_fpsCounter(CCFrameRateCounter::create()) - , m_debugRectHistory(CCDebugRectHistory::create()) -{ - ASSERT(CCProxy::isImplThread()); - didVisibilityChange(this, m_visible); -} - -CCLayerTreeHostImpl::~CCLayerTreeHostImpl() -{ - ASSERT(CCProxy::isImplThread()); - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::~CCLayerTreeHostImpl()"); - - if (m_rootLayerImpl) - clearRenderSurfaces(); -} - -void CCLayerTreeHostImpl::beginCommit() -{ -} - -void CCLayerTreeHostImpl::commitComplete() -{ - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::commitComplete"); - // Recompute max scroll position; must be after layer content bounds are - // updated. - updateMaxScrollPosition(); -} - -bool CCLayerTreeHostImpl::canDraw() -{ - // Note: If you are changing this function or any other function that might - // affect the result of canDraw, make sure to call m_client->onCanDrawStateChanged - // in the proper places and update the notifyIfCanDrawChanged test. - - if (!m_rootLayerImpl) { - TRACE_EVENT_INSTANT0("cc", "CCLayerTreeHostImpl::canDraw no root layer"); - return false; - } - if (deviceViewportSize().isEmpty()) { - TRACE_EVENT_INSTANT0("cc", "CCLayerTreeHostImpl::canDraw empty viewport"); - return false; - } - if (!m_renderer) { - TRACE_EVENT_INSTANT0("cc", "CCLayerTreeHostImpl::canDraw no renderer"); - return false; - } - if (m_contentsTexturesPurged) { - TRACE_EVENT_INSTANT0("cc", "CCLayerTreeHostImpl::canDraw contents textures purged"); - return false; - } - return true; -} - -CCGraphicsContext* CCLayerTreeHostImpl::context() const -{ - return m_context.get(); -} - -void CCLayerTreeHostImpl::animate(double monotonicTime, double wallClockTime) -{ - animatePageScale(monotonicTime); - animateLayers(monotonicTime, wallClockTime); - animateScrollbars(monotonicTime); -} - -void CCLayerTreeHostImpl::startPageScaleAnimation(const IntSize& targetPosition, bool anchorPoint, float pageScale, double startTime, double duration) -{ - if (!m_rootScrollLayerImpl) - return; - - IntSize scrollTotal = flooredIntSize(m_rootScrollLayerImpl->scrollPosition() + m_rootScrollLayerImpl->scrollDelta()); - scrollTotal.scale(m_pageScaleDelta); - float scaleTotal = m_pageScale * m_pageScaleDelta; - IntSize scaledContentSize = contentSize(); - scaledContentSize.scale(m_pageScaleDelta); - - m_pageScaleAnimation = CCPageScaleAnimation::create(scrollTotal, scaleTotal, m_deviceViewportSize, scaledContentSize, startTime); - - if (anchorPoint) { - IntSize windowAnchor(targetPosition); - windowAnchor.scale(scaleTotal / pageScale); - windowAnchor -= scrollTotal; - m_pageScaleAnimation->zoomWithAnchor(windowAnchor, pageScale, duration); - } else - m_pageScaleAnimation->zoomTo(targetPosition, pageScale, duration); - - m_client->setNeedsRedrawOnImplThread(); - m_client->setNeedsCommitOnImplThread(); -} - -void CCLayerTreeHostImpl::scheduleAnimation() -{ - m_client->setNeedsRedrawOnImplThread(); -} - -void CCLayerTreeHostImpl::trackDamageForAllSurfaces(CCLayerImpl* rootDrawLayer, const CCLayerList& renderSurfaceLayerList) -{ - // For now, we use damage tracking to compute a global scissor. To do this, we must - // compute all damage tracking before drawing anything, so that we know the root - // damage rect. The root damage rect is then used to scissor each surface. - - for (int surfaceIndex = renderSurfaceLayerList.size() - 1; surfaceIndex >= 0 ; --surfaceIndex) { - CCLayerImpl* renderSurfaceLayer = renderSurfaceLayerList[surfaceIndex]; - CCRenderSurface* renderSurface = renderSurfaceLayer->renderSurface(); - ASSERT(renderSurface); - renderSurface->damageTracker()->updateDamageTrackingState(renderSurface->layerList(), renderSurfaceLayer->id(), renderSurface->surfacePropertyChangedOnlyFromDescendant(), renderSurface->contentRect(), renderSurfaceLayer->maskLayer(), renderSurfaceLayer->filters()); - } -} - -void CCLayerTreeHostImpl::calculateRenderSurfaceLayerList(CCLayerList& renderSurfaceLayerList) -{ - ASSERT(renderSurfaceLayerList.isEmpty()); - ASSERT(m_rootLayerImpl); - ASSERT(m_renderer); // For maxTextureSize. - - { - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::calcDrawEtc"); - CCLayerTreeHostCommon::calculateDrawTransforms(m_rootLayerImpl.get(), deviceViewportSize(), m_deviceScaleFactor, &m_layerSorter, rendererCapabilities().maxTextureSize, renderSurfaceLayerList); - CCLayerTreeHostCommon::calculateVisibleRects(renderSurfaceLayerList); - - trackDamageForAllSurfaces(m_rootLayerImpl.get(), renderSurfaceLayerList); - } -} - -void CCLayerTreeHostImpl::FrameData::appendRenderPass(PassOwnPtr<CCRenderPass> renderPass) -{ - CCRenderPass* pass = renderPass.get(); - renderPasses.append(pass); - renderPassesById.set(pass->id(), renderPass); -} - -bool CCLayerTreeHostImpl::calculateRenderPasses(FrameData& frame) -{ - ASSERT(frame.renderPasses.isEmpty()); - - calculateRenderSurfaceLayerList(*frame.renderSurfaceLayerList); - - TRACE_EVENT1("cc", "CCLayerTreeHostImpl::calculateRenderPasses", "renderSurfaceLayerList.size()", static_cast<long long unsigned>(frame.renderSurfaceLayerList->size())); - - // Create the render passes in dependency order. - for (int surfaceIndex = frame.renderSurfaceLayerList->size() - 1; surfaceIndex >= 0 ; --surfaceIndex) { - CCLayerImpl* renderSurfaceLayer = (*frame.renderSurfaceLayerList)[surfaceIndex]; - renderSurfaceLayer->renderSurface()->appendRenderPasses(frame); - } - - bool recordMetricsForFrame = true; // FIXME: In the future, disable this when about:tracing is off. - CCOcclusionTrackerImpl occlusionTracker(m_rootLayerImpl->renderSurface()->contentRect(), recordMetricsForFrame); - occlusionTracker.setMinimumTrackingSize(m_settings.minimumOcclusionTrackingSize); - - if (settings().showOccludingRects) - occlusionTracker.setOccludingScreenSpaceRectsContainer(&frame.occludingScreenSpaceRects); - - // Add quads to the Render passes in FrontToBack order to allow for testing occlusion and performing culling during the tree walk. - typedef CCLayerIterator<CCLayerImpl, Vector<CCLayerImpl*>, CCRenderSurface, CCLayerIteratorActions::FrontToBack> CCLayerIteratorType; - - // Typically when we are missing a texture and use a checkerboard quad, we still draw the frame. However when the layer being - // checkerboarded is moving due to an impl-animation, we drop the frame to avoid flashing due to the texture suddenly appearing - // in the future. - bool drawFrame = true; - - CCLayerIteratorType end = CCLayerIteratorType::end(frame.renderSurfaceLayerList); - for (CCLayerIteratorType it = CCLayerIteratorType::begin(frame.renderSurfaceLayerList); it != end; ++it) { - CCRenderPass::Id targetRenderPassId = it.targetRenderSurfaceLayer()->renderSurface()->renderPassId(); - CCRenderPass* targetRenderPass = frame.renderPassesById.get(targetRenderPassId); - - occlusionTracker.enterLayer(it); - - CCAppendQuadsData appendQuadsData; - - if (it.representsContributingRenderSurface()) { - CCRenderPass::Id contributingRenderPassId = it->renderSurface()->renderPassId(); - CCRenderPass* contributingRenderPass = frame.renderPassesById.get(contributingRenderPassId); - targetRenderPass->appendQuadsForRenderSurfaceLayer(*it, contributingRenderPass, &occlusionTracker, appendQuadsData); - } else if (it.representsItself() && !it->visibleContentRect().isEmpty()) { - bool hasOcclusionFromOutsideTargetSurface; - if (occlusionTracker.occluded(*it, it->visibleContentRect(), &hasOcclusionFromOutsideTargetSurface)) - appendQuadsData.hadOcclusionFromOutsideTargetSurface |= hasOcclusionFromOutsideTargetSurface; - else { - it->willDraw(m_resourceProvider.get()); - frame.willDrawLayers.append(*it); - targetRenderPass->appendQuadsForLayer(*it, &occlusionTracker, appendQuadsData); - } - } - - if (appendQuadsData.hadOcclusionFromOutsideTargetSurface) - targetRenderPass->setHasOcclusionFromOutsideTargetSurface(true); - - if (appendQuadsData.hadMissingTiles) { - bool layerHasAnimatingTransform = it->screenSpaceTransformIsAnimating() || it->drawTransformIsAnimating(); - if (layerHasAnimatingTransform) - drawFrame = false; - } - - occlusionTracker.leaveLayer(it); - } - -#if !ASSERT_DISABLED - for (size_t i = 0; i < frame.renderPasses.size(); ++i) { - for (size_t j = 0; j < frame.renderPasses[i]->quadList().size(); ++j) - ASSERT(frame.renderPasses[i]->quadList()[j]->sharedQuadStateId() >= 0); - ASSERT(frame.renderPassesById.contains(frame.renderPasses[i]->id())); - } -#endif - - if (!m_hasTransparentBackground) { - frame.renderPasses.last()->setHasTransparentBackground(false); - frame.renderPasses.last()->appendQuadsToFillScreen(m_rootLayerImpl.get(), m_backgroundColor, occlusionTracker); - } - - if (drawFrame) - occlusionTracker.overdrawMetrics().recordMetrics(this); - - removeRenderPasses(CullRenderPassesWithNoQuads(), frame); - m_renderer->decideRenderPassAllocationsForFrame(frame.renderPasses); - removeRenderPasses(CullRenderPassesWithCachedTextures(*m_renderer), frame); - - return drawFrame; -} - -void CCLayerTreeHostImpl::animateLayersRecursive(CCLayerImpl* current, double monotonicTime, double wallClockTime, CCAnimationEventsVector* events, bool& didAnimate, bool& needsAnimateLayers) -{ - bool subtreeNeedsAnimateLayers = false; - - CCLayerAnimationController* currentController = current->layerAnimationController(); - - bool hadActiveAnimation = currentController->hasActiveAnimation(); - currentController->animate(monotonicTime, events); - bool startedAnimation = events->size() > 0; - - // We animated if we either ticked a running animation, or started a new animation. - if (hadActiveAnimation || startedAnimation) - didAnimate = true; - - // If the current controller still has an active animation, we must continue animating layers. - if (currentController->hasActiveAnimation()) - subtreeNeedsAnimateLayers = true; - - for (size_t i = 0; i < current->children().size(); ++i) { - bool childNeedsAnimateLayers = false; - animateLayersRecursive(current->children()[i].get(), monotonicTime, wallClockTime, events, didAnimate, childNeedsAnimateLayers); - if (childNeedsAnimateLayers) - subtreeNeedsAnimateLayers = true; - } - - needsAnimateLayers = subtreeNeedsAnimateLayers; -} - -void CCLayerTreeHostImpl::setBackgroundTickingEnabled(bool enabled) -{ - // Lazily create the timeSource adapter so that we can vary the interval for testing. - if (!m_timeSourceClientAdapter) - m_timeSourceClientAdapter = CCLayerTreeHostImplTimeSourceAdapter::create(this, CCDelayBasedTimeSource::create(lowFrequencyAnimationInterval(), CCProxy::currentThread())); - - m_timeSourceClientAdapter->setActive(enabled); -} - -IntSize CCLayerTreeHostImpl::contentSize() const -{ - // TODO(aelias): Hardcoding the first child here is weird. Think of - // a cleaner way to get the contentBounds on the Impl side. - if (!m_rootScrollLayerImpl || m_rootScrollLayerImpl->children().isEmpty()) - return IntSize(); - return m_rootScrollLayerImpl->children()[0]->contentBounds(); -} - -static inline CCRenderPass* findRenderPassById(CCRenderPass::Id renderPassId, const CCLayerTreeHostImpl::FrameData& frame) -{ - CCRenderPassIdHashMap::const_iterator it = frame.renderPassesById.find(renderPassId); - ASSERT(it != frame.renderPassesById.end()); - return it->second.get(); -} - -static void removeRenderPassesRecursive(CCRenderPass::Id removeRenderPassId, CCLayerTreeHostImpl::FrameData& frame) -{ - CCRenderPass* removeRenderPass = findRenderPassById(removeRenderPassId, frame); - size_t removeIndex = frame.renderPasses.find(removeRenderPass); - - // The pass was already removed by another quad - probably the original, and we are the replica. - if (removeIndex == notFound) - return; - - const CCRenderPass* removedPass = frame.renderPasses[removeIndex]; - frame.renderPasses.remove(removeIndex); - - // Now follow up for all RenderPass quads and remove their RenderPasses recursively. - const CCQuadList& quadList = removedPass->quadList(); - CCQuadList::constBackToFrontIterator quadListIterator = quadList.backToFrontBegin(); - for (; quadListIterator != quadList.backToFrontEnd(); ++quadListIterator) { - CCDrawQuad* currentQuad = (*quadListIterator).get(); - if (currentQuad->material() != CCDrawQuad::RenderPass) - continue; - - CCRenderPass::Id nextRemoveRenderPassId = CCRenderPassDrawQuad::materialCast(currentQuad)->renderPassId(); - removeRenderPassesRecursive(nextRemoveRenderPassId, frame); - } -} - -bool CCLayerTreeHostImpl::CullRenderPassesWithCachedTextures::shouldRemoveRenderPass(const CCRenderPassDrawQuad& quad, const FrameData&) const -{ - return quad.contentsChangedSinceLastFrame().isEmpty() && m_renderer.haveCachedResourcesForRenderPassId(quad.renderPassId()); -} - -bool CCLayerTreeHostImpl::CullRenderPassesWithNoQuads::shouldRemoveRenderPass(const CCRenderPassDrawQuad& quad, const FrameData& frame) const -{ - const CCRenderPass* renderPass = findRenderPassById(quad.renderPassId(), frame); - size_t passIndex = frame.renderPasses.find(renderPass); - - bool renderPassAlreadyRemoved = passIndex == notFound; - if (renderPassAlreadyRemoved) - return false; - - // If any quad or RenderPass draws into this RenderPass, then keep it. - const CCQuadList& quadList = frame.renderPasses[passIndex]->quadList(); - for (CCQuadList::constBackToFrontIterator quadListIterator = quadList.backToFrontBegin(); quadListIterator != quadList.backToFrontEnd(); ++quadListIterator) { - CCDrawQuad* currentQuad = quadListIterator->get(); - - if (currentQuad->material() != CCDrawQuad::RenderPass) - return false; - - const CCRenderPass* contributingPass = findRenderPassById(CCRenderPassDrawQuad::materialCast(currentQuad)->renderPassId(), frame); - if (frame.renderPasses.contains(contributingPass)) - return false; - } - return true; -} - -// Defined for linking tests. -template void CCLayerTreeHostImpl::removeRenderPasses<CCLayerTreeHostImpl::CullRenderPassesWithCachedTextures>(CullRenderPassesWithCachedTextures, FrameData&); -template void CCLayerTreeHostImpl::removeRenderPasses<CCLayerTreeHostImpl::CullRenderPassesWithNoQuads>(CullRenderPassesWithNoQuads, FrameData&); - -// static -template<typename RenderPassCuller> -void CCLayerTreeHostImpl::removeRenderPasses(RenderPassCuller culler, FrameData& frame) -{ - for (size_t it = culler.renderPassListBegin(frame.renderPasses); it != culler.renderPassListEnd(frame.renderPasses); it = culler.renderPassListNext(it)) { - const CCRenderPass* currentPass = frame.renderPasses[it]; - const CCQuadList& quadList = currentPass->quadList(); - CCQuadList::constBackToFrontIterator quadListIterator = quadList.backToFrontBegin(); - - for (; quadListIterator != quadList.backToFrontEnd(); ++quadListIterator) { - CCDrawQuad* currentQuad = quadListIterator->get(); - - if (currentQuad->material() != CCDrawQuad::RenderPass) - continue; - - CCRenderPassDrawQuad* renderPassQuad = static_cast<CCRenderPassDrawQuad*>(currentQuad); - if (!culler.shouldRemoveRenderPass(*renderPassQuad, frame)) - continue; - - // We are changing the vector in the middle of iteration. Because we - // delete render passes that draw into the current pass, we are - // guaranteed that any data from the iterator to the end will not - // change. So, capture the iterator position from the end of the - // list, and restore it after the change. - int positionFromEnd = frame.renderPasses.size() - it; - removeRenderPassesRecursive(renderPassQuad->renderPassId(), frame); - it = frame.renderPasses.size() - positionFromEnd; - ASSERT(it >= 0); - } - } -} - -bool CCLayerTreeHostImpl::prepareToDraw(FrameData& frame) -{ - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::prepareToDraw"); - ASSERT(canDraw()); - - frame.renderSurfaceLayerList = &m_renderSurfaceLayerList; - frame.renderPasses.clear(); - frame.renderPassesById.clear(); - frame.renderSurfaceLayerList->clear(); - frame.willDrawLayers.clear(); - - if (!calculateRenderPasses(frame)) - return false; - - // If we return true, then we expect drawLayers() to be called before this function is called again. - return true; -} - -void CCLayerTreeHostImpl::releaseContentsTextures() -{ - if (m_contentsTexturesPurged) - return; - m_client->releaseContentsTexturesOnImplThread(); - setContentsTexturesPurged(); - m_client->setNeedsCommitOnImplThread(); - m_client->onCanDrawStateChanged(canDraw()); -} - -void CCLayerTreeHostImpl::setMemoryAllocationLimitBytes(size_t bytes) -{ - if (m_memoryAllocationLimitBytes == bytes) - return; - m_memoryAllocationLimitBytes = bytes; - - ASSERT(bytes); - m_client->setNeedsCommitOnImplThread(); -} - -void CCLayerTreeHostImpl::onVSyncParametersChanged(double monotonicTimebase, double intervalInSeconds) -{ - m_client->onVSyncParametersChanged(monotonicTimebase, intervalInSeconds); -} - -void CCLayerTreeHostImpl::drawLayers(const FrameData& frame) -{ - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::drawLayers"); - ASSERT(canDraw()); - ASSERT(!frame.renderPasses.isEmpty()); - - // FIXME: use the frame begin time from the overall compositor scheduler. - // This value is currently inaccessible because it is up in Chromium's - // RenderWidget. - m_fpsCounter->markBeginningOfFrame(currentTime()); - - if (m_settings.showDebugRects()) - m_debugRectHistory->saveDebugRectsForCurrentFrame(m_rootLayerImpl.get(), *frame.renderSurfaceLayerList, frame.occludingScreenSpaceRects, settings()); - - // Because the contents of the HUD depend on everything else in the frame, the contents - // of its texture are updated as the last thing before the frame is drawn. - if (m_hudLayerImpl) - m_hudLayerImpl->updateHudTexture(m_resourceProvider.get()); - - m_renderer->drawFrame(frame.renderPasses, frame.renderPassesById); - - // Once a RenderPass has been drawn, its damage should be cleared in - // case the RenderPass will be reused next frame. - for (unsigned int i = 0; i < frame.renderPasses.size(); i++) - frame.renderPasses[i]->setDamageRect(FloatRect()); - - // The next frame should start by assuming nothing has changed, and changes are noted as they occur. - for (unsigned int i = 0; i < frame.renderSurfaceLayerList->size(); i++) - (*frame.renderSurfaceLayerList)[i]->renderSurface()->damageTracker()->didDrawDamagedArea(); - m_rootLayerImpl->resetAllChangeTrackingForSubtree(); -} - -void CCLayerTreeHostImpl::didDrawAllLayers(const FrameData& frame) -{ - for (size_t i = 0; i < frame.willDrawLayers.size(); ++i) - frame.willDrawLayers[i]->didDraw(m_resourceProvider.get()); -} - -void CCLayerTreeHostImpl::finishAllRendering() -{ - if (m_renderer) - m_renderer->finish(); -} - -bool CCLayerTreeHostImpl::isContextLost() -{ - return m_renderer && m_renderer->isContextLost(); -} - -const RendererCapabilities& CCLayerTreeHostImpl::rendererCapabilities() const -{ - return m_renderer->capabilities(); -} - -bool CCLayerTreeHostImpl::swapBuffers() -{ - ASSERT(m_renderer); - - m_fpsCounter->markEndOfFrame(); - return m_renderer->swapBuffers(); -} - -void CCLayerTreeHostImpl::didLoseContext() -{ - m_client->didLoseContextOnImplThread(); -} - -void CCLayerTreeHostImpl::onSwapBuffersComplete() -{ - m_client->onSwapBuffersCompleteOnImplThread(); -} - -void CCLayerTreeHostImpl::readback(void* pixels, const IntRect& rect) -{ - ASSERT(m_renderer); - m_renderer->getFramebufferPixels(pixels, rect); -} - -static CCLayerImpl* findRootScrollLayer(CCLayerImpl* layer) -{ - if (!layer) - return 0; - - if (layer->scrollable()) - return layer; - - for (size_t i = 0; i < layer->children().size(); ++i) { - CCLayerImpl* found = findRootScrollLayer(layer->children()[i].get()); - if (found) - return found; - } - - return 0; -} - -// Content layers can be either directly scrollable or contained in an outer -// scrolling layer which applies the scroll transform. Given a content layer, -// this function returns the associated scroll layer if any. -static CCLayerImpl* findScrollLayerForContentLayer(CCLayerImpl* layerImpl) -{ - if (!layerImpl) - return 0; - - if (layerImpl->scrollable()) - return layerImpl; - - if (layerImpl->drawsContent() && layerImpl->parent() && layerImpl->parent()->scrollable()) - return layerImpl->parent(); - - return 0; -} - -void CCLayerTreeHostImpl::setRootLayer(PassOwnPtr<CCLayerImpl> layer) -{ - m_rootLayerImpl = layer; - m_rootScrollLayerImpl = findRootScrollLayer(m_rootLayerImpl.get()); - m_currentlyScrollingLayerImpl = 0; - - if (m_rootLayerImpl && m_scrollingLayerIdFromPreviousTree != -1) - m_currentlyScrollingLayerImpl = CCLayerTreeHostCommon::findLayerInSubtree(m_rootLayerImpl.get(), m_scrollingLayerIdFromPreviousTree); - - m_scrollingLayerIdFromPreviousTree = -1; - - m_client->onCanDrawStateChanged(canDraw()); -} - -PassOwnPtr<CCLayerImpl> CCLayerTreeHostImpl::detachLayerTree() -{ - // Clear all data structures that have direct references to the layer tree. - m_scrollingLayerIdFromPreviousTree = m_currentlyScrollingLayerImpl ? m_currentlyScrollingLayerImpl->id() : -1; - m_currentlyScrollingLayerImpl = 0; - m_renderSurfaceLayerList.clear(); - - return m_rootLayerImpl.release(); -} - -void CCLayerTreeHostImpl::setVisible(bool visible) -{ - ASSERT(CCProxy::isImplThread()); - - if (m_visible == visible) - return; - m_visible = visible; - didVisibilityChange(this, m_visible); - - if (!m_renderer) - return; - - m_renderer->setVisible(visible); - - setBackgroundTickingEnabled(!m_visible && m_needsAnimateLayers); -} - -bool CCLayerTreeHostImpl::initializeRenderer(PassOwnPtr<CCGraphicsContext> context, TextureUploaderOption textureUploader) -{ - if (!context->bindToClient(this)) - return false; - - WebKit::WebGraphicsContext3D* context3d = context->context3D(); - - if (!context3d) { - // FIXME: Implement this path for software compositing. - return false; - } - - OwnPtr<CCGraphicsContext> contextRef(context); - OwnPtr<CCResourceProvider> resourceProvider = CCResourceProvider::create(contextRef.get()); - OwnPtr<CCRendererGL> renderer; - if (resourceProvider.get()) - renderer = CCRendererGL::create(this, resourceProvider.get(), textureUploader); - - // Since we now have a new context/renderer, we cannot continue to use the old - // resources (i.e. renderSurfaces and texture IDs). - if (m_rootLayerImpl) { - clearRenderSurfaces(); - sendDidLoseContextRecursive(m_rootLayerImpl.get()); - } - - m_renderer = renderer.release(); - m_resourceProvider = resourceProvider.release(); - if (m_renderer) - m_context = contextRef.release(); - - if (!m_visible && m_renderer) - m_renderer->setVisible(m_visible); - - m_client->onCanDrawStateChanged(canDraw()); - - return m_renderer; -} - -void CCLayerTreeHostImpl::setContentsTexturesPurged() -{ - m_contentsTexturesPurged = true; - m_client->onCanDrawStateChanged(canDraw()); -} - -void CCLayerTreeHostImpl::resetContentsTexturesPurged() -{ - m_contentsTexturesPurged = false; - m_client->onCanDrawStateChanged(canDraw()); -} - -void CCLayerTreeHostImpl::setViewportSize(const IntSize& layoutViewportSize, const IntSize& deviceViewportSize) -{ - if (layoutViewportSize == m_layoutViewportSize && deviceViewportSize == m_deviceViewportSize) - return; - - m_layoutViewportSize = layoutViewportSize; - m_deviceViewportSize = deviceViewportSize; - - updateMaxScrollPosition(); - - if (m_renderer) - m_renderer->viewportChanged(); - - m_client->onCanDrawStateChanged(canDraw()); -} - -static void adjustScrollsForPageScaleChange(CCLayerImpl* layerImpl, float pageScaleChange) -{ - if (!layerImpl) - return; - - if (layerImpl->scrollable()) { - // We need to convert impl-side scroll deltas to pageScale space. - FloatSize scrollDelta = layerImpl->scrollDelta(); - scrollDelta.scale(pageScaleChange); - layerImpl->setScrollDelta(scrollDelta); - } - - for (size_t i = 0; i < layerImpl->children().size(); ++i) - adjustScrollsForPageScaleChange(layerImpl->children()[i].get(), pageScaleChange); -} - -void CCLayerTreeHostImpl::setDeviceScaleFactor(float deviceScaleFactor) -{ - if (deviceScaleFactor == m_deviceScaleFactor) - return; - m_deviceScaleFactor = deviceScaleFactor; - - updateMaxScrollPosition(); -} - - -void CCLayerTreeHostImpl::setPageScaleFactorAndLimits(float pageScale, float minPageScale, float maxPageScale) -{ - if (!pageScale) - return; - - if (m_sentPageScaleDelta == 1 && pageScale == m_pageScale && minPageScale == m_minPageScale && maxPageScale == m_maxPageScale) - return; - - m_minPageScale = minPageScale; - m_maxPageScale = maxPageScale; - - float pageScaleChange = pageScale / m_pageScale; - m_pageScale = pageScale; - - if (pageScaleChange != 1) - adjustScrollsForPageScaleChange(m_rootScrollLayerImpl, pageScaleChange); - - // Clamp delta to limits and refresh display matrix. - setPageScaleDelta(m_pageScaleDelta / m_sentPageScaleDelta); - m_sentPageScaleDelta = 1; - if (m_rootScrollLayerImpl) - m_rootScrollLayerImpl->setPageScaleDelta(m_pageScaleDelta); -} - -void CCLayerTreeHostImpl::setPageScaleDelta(float delta) -{ - // Clamp to the current min/max limits. - float finalMagnifyScale = m_pageScale * delta; - if (m_minPageScale && finalMagnifyScale < m_minPageScale) - delta = m_minPageScale / m_pageScale; - else if (m_maxPageScale && finalMagnifyScale > m_maxPageScale) - delta = m_maxPageScale / m_pageScale; - - if (delta == m_pageScaleDelta) - return; - - m_pageScaleDelta = delta; - - updateMaxScrollPosition(); - if (m_rootScrollLayerImpl) - m_rootScrollLayerImpl->setPageScaleDelta(m_pageScaleDelta); -} - -void CCLayerTreeHostImpl::updateMaxScrollPosition() -{ - if (!m_rootScrollLayerImpl || !m_rootScrollLayerImpl->children().size()) - return; - - FloatSize viewBounds = m_deviceViewportSize; - if (CCLayerImpl* clipLayer = m_rootScrollLayerImpl->parent()) { - // Compensate for non-overlay scrollbars. - if (clipLayer->masksToBounds()) { - viewBounds = clipLayer->bounds(); - viewBounds.scale(m_deviceScaleFactor); - } - } - viewBounds.scale(1 / m_pageScaleDelta); - - // maxScroll is computed in physical pixels, but scroll positions are in layout pixels. - IntSize maxScroll = contentSize() - expandedIntSize(viewBounds); - maxScroll.scale(1 / m_deviceScaleFactor); - // The viewport may be larger than the contents in some cases, such as - // having a vertical scrollbar but no horizontal overflow. - maxScroll.clampNegativeToZero(); - - m_rootScrollLayerImpl->setMaxScrollPosition(maxScroll); -} - -void CCLayerTreeHostImpl::setNeedsRedraw() -{ - m_client->setNeedsRedrawOnImplThread(); -} - -bool CCLayerTreeHostImpl::ensureRenderSurfaceLayerList() -{ - if (!m_rootLayerImpl) - return false; - if (!m_renderer) - return false; - - // We need both a non-empty render surface layer list and a root render - // surface to be able to iterate over the visible layers. - if (m_renderSurfaceLayerList.size() && m_rootLayerImpl->renderSurface()) - return true; - - // If we are called after setRootLayer() but before prepareToDraw(), we need - // to recalculate the visible layers. This prevents being unable to scroll - // during part of a commit. - m_renderSurfaceLayerList.clear(); - calculateRenderSurfaceLayerList(m_renderSurfaceLayerList); - - return m_renderSurfaceLayerList.size(); -} - -CCInputHandlerClient::ScrollStatus CCLayerTreeHostImpl::scrollBegin(const IntPoint& viewportPoint, CCInputHandlerClient::ScrollInputType type) -{ - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::scrollBegin"); - - ASSERT(!m_currentlyScrollingLayerImpl); - clearCurrentlyScrollingLayer(); - - if (!ensureRenderSurfaceLayerList()) - return ScrollIgnored; - - IntPoint deviceViewportPoint = viewportPoint; - deviceViewportPoint.scale(m_deviceScaleFactor, m_deviceScaleFactor); - - // First find out which layer was hit from the saved list of visible layers - // in the most recent frame. - CCLayerImpl* layerImpl = CCLayerTreeHostCommon::findLayerThatIsHitByPoint(viewportPoint, m_renderSurfaceLayerList); - - // Walk up the hierarchy and look for a scrollable layer. - CCLayerImpl* potentiallyScrollingLayerImpl = 0; - for (; layerImpl; layerImpl = layerImpl->parent()) { - // The content layer can also block attempts to scroll outside the main thread. - if (layerImpl->tryScroll(deviceViewportPoint, type) == ScrollOnMainThread) - return ScrollOnMainThread; - - CCLayerImpl* scrollLayerImpl = findScrollLayerForContentLayer(layerImpl); - if (!scrollLayerImpl) - continue; - - ScrollStatus status = scrollLayerImpl->tryScroll(viewportPoint, type); - - // If any layer wants to divert the scroll event to the main thread, abort. - if (status == ScrollOnMainThread) - return ScrollOnMainThread; - - if (status == ScrollStarted && !potentiallyScrollingLayerImpl) - potentiallyScrollingLayerImpl = scrollLayerImpl; - } - - if (potentiallyScrollingLayerImpl) { - m_currentlyScrollingLayerImpl = potentiallyScrollingLayerImpl; - // Gesture events need to be transformed from screen coordinates to local layer coordinates - // so that the scrolling contents exactly follow the user's finger. In contrast, wheel - // events are already in local layer coordinates so we can just apply them directly. - m_scrollDeltaIsInScreenSpace = (type == Gesture); - return ScrollStarted; - } - return ScrollIgnored; -} - -static FloatSize scrollLayerWithScreenSpaceDelta(CCLayerImpl& layerImpl, const FloatPoint& screenSpacePoint, const FloatSize& screenSpaceDelta) -{ - // Layers with non-invertible screen space transforms should not have passed the scroll hit - // test in the first place. - ASSERT(layerImpl.screenSpaceTransform().isInvertible()); - WebTransformationMatrix inverseScreenSpaceTransform = layerImpl.screenSpaceTransform().inverse(); - - // First project the scroll start and end points to local layer space to find the scroll delta - // in layer coordinates. - bool startClipped, endClipped; - FloatPoint screenSpaceEndPoint = screenSpacePoint + screenSpaceDelta; - FloatPoint localStartPoint = CCMathUtil::projectPoint(inverseScreenSpaceTransform, screenSpacePoint, startClipped); - FloatPoint localEndPoint = CCMathUtil::projectPoint(inverseScreenSpaceTransform, screenSpaceEndPoint, endClipped); - - // In general scroll point coordinates should not get clipped. - ASSERT(!startClipped); - ASSERT(!endClipped); - if (startClipped || endClipped) - return FloatSize(); - - // Apply the scroll delta. - FloatSize previousDelta(layerImpl.scrollDelta()); - layerImpl.scrollBy(localEndPoint - localStartPoint); - - // Calculate the applied scroll delta in screen space coordinates. - FloatPoint actualLocalEndPoint = localStartPoint + layerImpl.scrollDelta() - previousDelta; - FloatPoint actualScreenSpaceEndPoint = CCMathUtil::mapPoint(layerImpl.screenSpaceTransform(), actualLocalEndPoint, endClipped); - ASSERT(!endClipped); - if (endClipped) - return FloatSize(); - return actualScreenSpaceEndPoint - screenSpacePoint; -} - -static FloatSize scrollLayerWithLocalDelta(CCLayerImpl& layerImpl, const FloatSize& localDelta) -{ - FloatSize previousDelta(layerImpl.scrollDelta()); - layerImpl.scrollBy(localDelta); - return layerImpl.scrollDelta() - previousDelta; -} - -void CCLayerTreeHostImpl::scrollBy(const IntPoint& viewportPoint, const IntSize& scrollDelta) -{ - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::scrollBy"); - if (!m_currentlyScrollingLayerImpl) - return; - - FloatSize pendingDelta(scrollDelta); - - pendingDelta.scale(m_deviceScaleFactor); - - for (CCLayerImpl* layerImpl = m_currentlyScrollingLayerImpl; layerImpl; layerImpl = layerImpl->parent()) { - if (!layerImpl->scrollable()) - continue; - - FloatSize appliedDelta; - if (m_scrollDeltaIsInScreenSpace) - appliedDelta = scrollLayerWithScreenSpaceDelta(*layerImpl, viewportPoint, pendingDelta); - else - appliedDelta = scrollLayerWithLocalDelta(*layerImpl, pendingDelta); - - // If the layer wasn't able to move, try the next one in the hierarchy. - float moveThresholdSquared = 0.1f * 0.1f; - if (appliedDelta.diagonalLengthSquared() < moveThresholdSquared) - continue; - - // If the applied delta is within 45 degrees of the input delta, bail out to make it easier - // to scroll just one layer in one direction without affecting any of its parents. - float angleThreshold = 45; - if (CCMathUtil::smallestAngleBetweenVectors(appliedDelta, pendingDelta) < angleThreshold) { - pendingDelta = FloatSize(); - break; - } - - // Allow further movement only on an axis perpendicular to the direction in which the layer - // moved. - FloatSize perpendicularAxis(-appliedDelta.height(), appliedDelta.width()); - pendingDelta = CCMathUtil::projectVector(pendingDelta, perpendicularAxis); - - if (flooredIntSize(pendingDelta).isZero()) - break; - } - - if (!scrollDelta.isZero() && flooredIntSize(pendingDelta).isEmpty()) { - m_client->setNeedsCommitOnImplThread(); - m_client->setNeedsRedrawOnImplThread(); - } -} - -void CCLayerTreeHostImpl::clearCurrentlyScrollingLayer() -{ - m_currentlyScrollingLayerImpl = 0; - m_scrollingLayerIdFromPreviousTree = -1; -} - -void CCLayerTreeHostImpl::scrollEnd() -{ - clearCurrentlyScrollingLayer(); -} - -void CCLayerTreeHostImpl::pinchGestureBegin() -{ - m_pinchGestureActive = true; - m_previousPinchAnchor = IntPoint(); - - if (m_rootScrollLayerImpl && m_rootScrollLayerImpl->scrollbarAnimationController()) - m_rootScrollLayerImpl->scrollbarAnimationController()->didPinchGestureBegin(); -} - -void CCLayerTreeHostImpl::pinchGestureUpdate(float magnifyDelta, - const IntPoint& anchor) -{ - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::pinchGestureUpdate"); - - if (!m_rootScrollLayerImpl) - return; - - if (m_previousPinchAnchor == IntPoint::zero()) - m_previousPinchAnchor = anchor; - - // Keep the center-of-pinch anchor specified by (x, y) in a stable - // position over the course of the magnify. - FloatPoint previousScaleAnchor(m_previousPinchAnchor.x() / m_pageScaleDelta, m_previousPinchAnchor.y() / m_pageScaleDelta); - setPageScaleDelta(m_pageScaleDelta * magnifyDelta); - FloatPoint newScaleAnchor(anchor.x() / m_pageScaleDelta, anchor.y() / m_pageScaleDelta); - FloatSize move = previousScaleAnchor - newScaleAnchor; - - m_previousPinchAnchor = anchor; - - m_rootScrollLayerImpl->scrollBy(roundedIntSize(move)); - - if (m_rootScrollLayerImpl->scrollbarAnimationController()) - m_rootScrollLayerImpl->scrollbarAnimationController()->didPinchGestureUpdate(); - - m_client->setNeedsCommitOnImplThread(); - m_client->setNeedsRedrawOnImplThread(); -} - -void CCLayerTreeHostImpl::pinchGestureEnd() -{ - m_pinchGestureActive = false; - - if (m_rootScrollLayerImpl && m_rootScrollLayerImpl->scrollbarAnimationController()) - m_rootScrollLayerImpl->scrollbarAnimationController()->didPinchGestureEnd(); - - m_client->setNeedsCommitOnImplThread(); -} - -void CCLayerTreeHostImpl::computeDoubleTapZoomDeltas(CCScrollAndScaleSet* scrollInfo) -{ - float pageScale = m_pageScaleAnimation->finalPageScale(); - IntSize scrollOffset = m_pageScaleAnimation->finalScrollOffset(); - scrollOffset.scale(m_pageScale / pageScale); - makeScrollAndScaleSet(scrollInfo, scrollOffset, pageScale); -} - -void CCLayerTreeHostImpl::computePinchZoomDeltas(CCScrollAndScaleSet* scrollInfo) -{ - if (!m_rootScrollLayerImpl) - return; - - // Only send fake scroll/zoom deltas if we're pinch zooming out by a - // significant amount. This also ensures only one fake delta set will be - // sent. - const float pinchZoomOutSensitivity = 0.95f; - if (m_pageScaleDelta > pinchZoomOutSensitivity) - return; - - // Compute where the scroll offset/page scale would be if fully pinch-zoomed - // out from the anchor point. - IntSize scrollBegin = flooredIntSize(m_rootScrollLayerImpl->scrollPosition() + m_rootScrollLayerImpl->scrollDelta()); - scrollBegin.scale(m_pageScaleDelta); - float scaleBegin = m_pageScale * m_pageScaleDelta; - float pageScaleDeltaToSend = m_minPageScale / m_pageScale; - FloatSize scaledContentsSize = contentSize(); - scaledContentsSize.scale(pageScaleDeltaToSend); - - FloatSize anchor = toSize(m_previousPinchAnchor); - FloatSize scrollEnd = scrollBegin + anchor; - scrollEnd.scale(m_minPageScale / scaleBegin); - scrollEnd -= anchor; - scrollEnd = scrollEnd.shrunkTo(roundedIntSize(scaledContentsSize - m_deviceViewportSize)).expandedTo(FloatSize(0, 0)); - scrollEnd.scale(1 / pageScaleDeltaToSend); - scrollEnd.scale(m_deviceScaleFactor); - - makeScrollAndScaleSet(scrollInfo, roundedIntSize(scrollEnd), m_minPageScale); -} - -void CCLayerTreeHostImpl::makeScrollAndScaleSet(CCScrollAndScaleSet* scrollInfo, const IntSize& scrollOffset, float pageScale) -{ - if (!m_rootScrollLayerImpl) - return; - - CCLayerTreeHostCommon::ScrollUpdateInfo scroll; - scroll.layerId = m_rootScrollLayerImpl->id(); - scroll.scrollDelta = scrollOffset - toSize(m_rootScrollLayerImpl->scrollPosition()); - scrollInfo->scrolls.append(scroll); - m_rootScrollLayerImpl->setSentScrollDelta(scroll.scrollDelta); - m_sentPageScaleDelta = scrollInfo->pageScaleDelta = pageScale / m_pageScale; -} - -static void collectScrollDeltas(CCScrollAndScaleSet* scrollInfo, CCLayerImpl* layerImpl) -{ - if (!layerImpl) - return; - - if (!layerImpl->scrollDelta().isZero()) { - IntSize scrollDelta = flooredIntSize(layerImpl->scrollDelta()); - CCLayerTreeHostCommon::ScrollUpdateInfo scroll; - scroll.layerId = layerImpl->id(); - scroll.scrollDelta = scrollDelta; - scrollInfo->scrolls.append(scroll); - layerImpl->setSentScrollDelta(scrollDelta); - } - - for (size_t i = 0; i < layerImpl->children().size(); ++i) - collectScrollDeltas(scrollInfo, layerImpl->children()[i].get()); -} - -PassOwnPtr<CCScrollAndScaleSet> CCLayerTreeHostImpl::processScrollDeltas() -{ - OwnPtr<CCScrollAndScaleSet> scrollInfo = adoptPtr(new CCScrollAndScaleSet()); - - if (m_pinchGestureActive || m_pageScaleAnimation) { - m_sentPageScaleDelta = scrollInfo->pageScaleDelta = 1; - if (m_pinchGestureActive) - computePinchZoomDeltas(scrollInfo.get()); - else if (m_pageScaleAnimation.get()) - computeDoubleTapZoomDeltas(scrollInfo.get()); - return scrollInfo.release(); - } - - collectScrollDeltas(scrollInfo.get(), m_rootLayerImpl.get()); - m_sentPageScaleDelta = scrollInfo->pageScaleDelta = m_pageScaleDelta; - - return scrollInfo.release(); -} - -void CCLayerTreeHostImpl::setFullRootLayerDamage() -{ - if (m_rootLayerImpl) { - CCRenderSurface* renderSurface = m_rootLayerImpl->renderSurface(); - if (renderSurface) - renderSurface->damageTracker()->forceFullDamageNextUpdate(); - } -} - -void CCLayerTreeHostImpl::animatePageScale(double monotonicTime) -{ - if (!m_pageScaleAnimation || !m_rootScrollLayerImpl) - return; - - IntSize scrollTotal = flooredIntSize(m_rootScrollLayerImpl->scrollPosition() + m_rootScrollLayerImpl->scrollDelta()); - - setPageScaleDelta(m_pageScaleAnimation->pageScaleAtTime(monotonicTime) / m_pageScale); - IntSize nextScroll = m_pageScaleAnimation->scrollOffsetAtTime(monotonicTime); - nextScroll.scale(1 / m_pageScaleDelta); - m_rootScrollLayerImpl->scrollBy(nextScroll - scrollTotal); - m_client->setNeedsRedrawOnImplThread(); - - if (m_pageScaleAnimation->isAnimationCompleteAtTime(monotonicTime)) { - m_pageScaleAnimation.clear(); - m_client->setNeedsCommitOnImplThread(); - } -} - -void CCLayerTreeHostImpl::animateLayers(double monotonicTime, double wallClockTime) -{ - if (!CCSettings::acceleratedAnimationEnabled() || !m_needsAnimateLayers || !m_rootLayerImpl) - return; - - TRACE_EVENT0("cc", "CCLayerTreeHostImpl::animateLayers"); - - OwnPtr<CCAnimationEventsVector> events(adoptPtr(new CCAnimationEventsVector)); - - bool didAnimate = false; - animateLayersRecursive(m_rootLayerImpl.get(), monotonicTime, wallClockTime, events.get(), didAnimate, m_needsAnimateLayers); - - if (!events->isEmpty()) - m_client->postAnimationEventsToMainThreadOnImplThread(events.release(), wallClockTime); - - if (didAnimate) - m_client->setNeedsRedrawOnImplThread(); - - setBackgroundTickingEnabled(!m_visible && m_needsAnimateLayers); -} - -double CCLayerTreeHostImpl::lowFrequencyAnimationInterval() const -{ - return 1; -} - -void CCLayerTreeHostImpl::sendDidLoseContextRecursive(CCLayerImpl* current) -{ - ASSERT(current); - current->didLoseContext(); - if (current->maskLayer()) - sendDidLoseContextRecursive(current->maskLayer()); - if (current->replicaLayer()) - sendDidLoseContextRecursive(current->replicaLayer()); - for (size_t i = 0; i < current->children().size(); ++i) - sendDidLoseContextRecursive(current->children()[i].get()); -} - -static void clearRenderSurfacesOnCCLayerImplRecursive(CCLayerImpl* current) -{ - ASSERT(current); - for (size_t i = 0; i < current->children().size(); ++i) - clearRenderSurfacesOnCCLayerImplRecursive(current->children()[i].get()); - current->clearRenderSurface(); -} - -void CCLayerTreeHostImpl::clearRenderSurfaces() -{ - clearRenderSurfacesOnCCLayerImplRecursive(m_rootLayerImpl.get()); - m_renderSurfaceLayerList.clear(); -} - -String CCLayerTreeHostImpl::layerTreeAsText() const -{ - TextStream ts; - if (m_rootLayerImpl) { - ts << m_rootLayerImpl->layerTreeAsText(); - ts << "RenderSurfaces:\n"; - dumpRenderSurfaces(ts, 1, m_rootLayerImpl.get()); - } - return ts.release(); -} - -void CCLayerTreeHostImpl::dumpRenderSurfaces(TextStream& ts, int indent, const CCLayerImpl* layer) const -{ - if (layer->renderSurface()) - layer->renderSurface()->dumpSurface(ts, indent); - - for (size_t i = 0; i < layer->children().size(); ++i) - dumpRenderSurfaces(ts, indent, layer->children()[i].get()); -} - -int CCLayerTreeHostImpl::sourceAnimationFrameNumber() const -{ - return fpsCounter()->currentFrameNumber(); -} - -void CCLayerTreeHostImpl::renderingStats(CCRenderingStats& stats) const -{ - stats.numFramesSentToScreen = fpsCounter()->currentFrameNumber(); - stats.droppedFrameCount = fpsCounter()->droppedFrameCount(); -} - -void CCLayerTreeHostImpl::animateScrollbars(double monotonicTime) -{ - animateScrollbarsRecursive(m_rootLayerImpl.get(), monotonicTime); -} - -void CCLayerTreeHostImpl::animateScrollbarsRecursive(CCLayerImpl* layer, double monotonicTime) -{ - if (!layer) - return; - - CCScrollbarAnimationController* scrollbarController = layer->scrollbarAnimationController(); - if (scrollbarController && scrollbarController->animate(monotonicTime)) - m_client->setNeedsRedrawOnImplThread(); - - for (size_t i = 0; i < layer->children().size(); ++i) - animateScrollbarsRecursive(layer->children()[i].get(), monotonicTime); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostImpl.h deleted file mode 100644 index f557ddd8c..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCLayerTreeHostImpl.h +++ /dev/null @@ -1,316 +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 CCLayerTreeHostImpl_h -#define CCLayerTreeHostImpl_h - -#include "CCAnimationEvents.h" -#include "CCInputHandler.h" -#include "CCLayerSorter.h" -#include "CCRenderPass.h" -#include "CCRenderPassSink.h" -#include "CCRenderer.h" -#include "SkColor.h" -#include <public/WebCompositorOutputSurfaceClient.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/RefPtr.h> - -namespace WebCore { - -class CCCompletionEvent; -class CCDebugRectHistory; -class CCFrameRateCounter; -class CCHeadsUpDisplayLayerImpl; -class CCLayerImpl; -class CCLayerTreeHostImplTimeSourceAdapter; -class CCPageScaleAnimation; -class CCRenderPassDrawQuad; -class CCResourceProvider; -struct RendererCapabilities; -struct CCRenderingStats; - -// CCLayerTreeHost->CCProxy callback interface. -class CCLayerTreeHostImplClient { -public: - virtual void didLoseContextOnImplThread() = 0; - virtual void onSwapBuffersCompleteOnImplThread() = 0; - virtual void onVSyncParametersChanged(double monotonicTimebase, double intervalInSeconds) = 0; - virtual void onCanDrawStateChanged(bool canDraw) = 0; - virtual void setNeedsRedrawOnImplThread() = 0; - virtual void setNeedsCommitOnImplThread() = 0; - virtual void postAnimationEventsToMainThreadOnImplThread(PassOwnPtr<CCAnimationEventsVector>, double wallClockTime) = 0; - virtual void releaseContentsTexturesOnImplThread() = 0; -}; - -// CCLayerTreeHostImpl owns the CCLayerImpl tree as well as associated rendering state -class CCLayerTreeHostImpl : public CCInputHandlerClient, - public CCRendererClient, - public WebKit::WebCompositorOutputSurfaceClient { - WTF_MAKE_NONCOPYABLE(CCLayerTreeHostImpl); - typedef Vector<CCLayerImpl*> CCLayerList; - -public: - static PassOwnPtr<CCLayerTreeHostImpl> create(const CCLayerTreeSettings&, CCLayerTreeHostImplClient*); - virtual ~CCLayerTreeHostImpl(); - - // CCInputHandlerClient implementation - virtual CCInputHandlerClient::ScrollStatus scrollBegin(const IntPoint&, CCInputHandlerClient::ScrollInputType) OVERRIDE; - virtual void scrollBy(const IntPoint&, const IntSize&) OVERRIDE; - virtual void scrollEnd() OVERRIDE; - virtual void pinchGestureBegin() OVERRIDE; - virtual void pinchGestureUpdate(float, const IntPoint&) OVERRIDE; - virtual void pinchGestureEnd() OVERRIDE; - virtual void startPageScaleAnimation(const IntSize& targetPosition, bool anchorPoint, float pageScale, double startTime, double duration) OVERRIDE; - virtual void scheduleAnimation() OVERRIDE; - - struct FrameData : public CCRenderPassSink { - Vector<IntRect> occludingScreenSpaceRects; - CCRenderPassList renderPasses; - CCRenderPassIdHashMap renderPassesById; - CCLayerList* renderSurfaceLayerList; - CCLayerList willDrawLayers; - - // CCRenderPassSink implementation. - virtual void appendRenderPass(PassOwnPtr<CCRenderPass>) OVERRIDE; - }; - - // Virtual for testing. - virtual void beginCommit(); - virtual void commitComplete(); - virtual void animate(double monotonicTime, double wallClockTime); - - // Returns false if problems occured preparing the frame, and we should try - // to avoid displaying the frame. If prepareToDraw is called, - // didDrawAllLayers must also be called, regardless of whether drawLayers is - // called between the two. - virtual bool prepareToDraw(FrameData&); - virtual void drawLayers(const FrameData&); - // Must be called if and only if prepareToDraw was called. - void didDrawAllLayers(const FrameData&); - - // CCRendererClient implementation - virtual const IntSize& deviceViewportSize() const OVERRIDE { return m_deviceViewportSize; } - virtual const CCLayerTreeSettings& settings() const OVERRIDE { return m_settings; } - virtual void didLoseContext() OVERRIDE; - virtual void onSwapBuffersComplete() OVERRIDE; - virtual void setFullRootLayerDamage() OVERRIDE; - virtual void releaseContentsTextures() OVERRIDE; - virtual void setMemoryAllocationLimitBytes(size_t) OVERRIDE; - - // WebCompositorOutputSurfaceClient implementation. - virtual void onVSyncParametersChanged(double monotonicTimebase, double intervalInSeconds) OVERRIDE; - - // Implementation - bool canDraw(); - CCGraphicsContext* context() const; - - String layerTreeAsText() const; - - void finishAllRendering(); - int sourceAnimationFrameNumber() const; - - bool initializeRenderer(PassOwnPtr<CCGraphicsContext>, TextureUploaderOption); - bool isContextLost(); - CCRenderer* renderer() { return m_renderer.get(); } - const RendererCapabilities& rendererCapabilities() const; - - bool swapBuffers(); - - void readback(void* pixels, const IntRect&); - - void setRootLayer(PassOwnPtr<CCLayerImpl>); - CCLayerImpl* rootLayer() { return m_rootLayerImpl.get(); } - - void setHudLayer(CCHeadsUpDisplayLayerImpl* layerImpl) { m_hudLayerImpl = layerImpl; } - CCHeadsUpDisplayLayerImpl* hudLayer() { return m_hudLayerImpl; } - - // Release ownership of the current layer tree and replace it with an empty - // tree. Returns the root layer of the detached tree. - PassOwnPtr<CCLayerImpl> detachLayerTree(); - - CCLayerImpl* rootScrollLayer() const { return m_rootScrollLayerImpl; } - - bool visible() const { return m_visible; } - void setVisible(bool); - - int sourceFrameNumber() const { return m_sourceFrameNumber; } - void setSourceFrameNumber(int frameNumber) { m_sourceFrameNumber = frameNumber; } - - bool contentsTexturesPurged() const { return m_contentsTexturesPurged; } - void setContentsTexturesPurged(); - void resetContentsTexturesPurged(); - size_t memoryAllocationLimitBytes() const { return m_memoryAllocationLimitBytes; } - - void setViewportSize(const IntSize& layoutViewportSize, const IntSize& deviceViewportSize); - const IntSize& layoutViewportSize() const { return m_layoutViewportSize; } - - float deviceScaleFactor() const { return m_deviceScaleFactor; } - void setDeviceScaleFactor(float); - - float pageScale() const { return m_pageScale; } - void setPageScaleFactorAndLimits(float pageScale, float minPageScale, float maxPageScale); - - PassOwnPtr<CCScrollAndScaleSet> processScrollDeltas(); - - void startPageScaleAnimation(const IntSize& tragetPosition, bool useAnchor, float scale, double durationSec); - - SkColor backgroundColor() const { return m_backgroundColor; } - void setBackgroundColor(SkColor color) { m_backgroundColor = color; } - - bool hasTransparentBackground() const { return m_hasTransparentBackground; } - void setHasTransparentBackground(bool transparent) { m_hasTransparentBackground = transparent; } - - bool needsAnimateLayers() const { return m_needsAnimateLayers; } - void setNeedsAnimateLayers() { m_needsAnimateLayers = true; } - - void setNeedsRedraw(); - - void renderingStats(CCRenderingStats&) const; - - CCFrameRateCounter* fpsCounter() const { return m_fpsCounter.get(); } - CCDebugRectHistory* debugRectHistory() const { return m_debugRectHistory.get(); } - CCResourceProvider* resourceProvider() const { return m_resourceProvider.get(); } - - class CullRenderPassesWithCachedTextures { - public: - bool shouldRemoveRenderPass(const CCRenderPassDrawQuad&, const FrameData&) const; - - // Iterates from the root first, in order to remove the surfaces closest - // to the root with cached textures, and all surfaces that draw into - // them. - size_t renderPassListBegin(const CCRenderPassList& list) const { return list.size() - 1; } - size_t renderPassListEnd(const CCRenderPassList&) const { return 0 - 1; } - size_t renderPassListNext(size_t it) const { return it - 1; } - - CullRenderPassesWithCachedTextures(CCRenderer& renderer) : m_renderer(renderer) { } - private: - CCRenderer& m_renderer; - }; - - class CullRenderPassesWithNoQuads { - public: - bool shouldRemoveRenderPass(const CCRenderPassDrawQuad&, const FrameData&) const; - - // Iterates in draw order, so that when a surface is removed, and its - // target becomes empty, then its target can be removed also. - size_t renderPassListBegin(const CCRenderPassList&) const { return 0; } - size_t renderPassListEnd(const CCRenderPassList& list) const { return list.size(); } - size_t renderPassListNext(size_t it) const { return it + 1; } - }; - - template<typename RenderPassCuller> - static void removeRenderPasses(RenderPassCuller, FrameData&); - -protected: - CCLayerTreeHostImpl(const CCLayerTreeSettings&, CCLayerTreeHostImplClient*); - - void animatePageScale(double monotonicTime); - void animateScrollbars(double monotonicTime); - - // Exposed for testing. - void calculateRenderSurfaceLayerList(CCLayerList&); - - // Virtual for testing. - virtual void animateLayers(double monotonicTime, double wallClockTime); - - // Virtual for testing. Measured in seconds. - virtual double lowFrequencyAnimationInterval() const; - - CCLayerTreeHostImplClient* m_client; - int m_sourceFrameNumber; - -private: - void computeDoubleTapZoomDeltas(CCScrollAndScaleSet* scrollInfo); - void computePinchZoomDeltas(CCScrollAndScaleSet* scrollInfo); - void makeScrollAndScaleSet(CCScrollAndScaleSet* scrollInfo, const IntSize& scrollOffset, float pageScale); - - void setPageScaleDelta(float); - void updateMaxScrollPosition(); - void trackDamageForAllSurfaces(CCLayerImpl* rootDrawLayer, const CCLayerList& renderSurfaceLayerList); - - // Returns false if the frame should not be displayed. This function should - // only be called from prepareToDraw, as didDrawAllLayers must be called - // if this helper function is called. - bool calculateRenderPasses(FrameData&); - void animateLayersRecursive(CCLayerImpl*, double monotonicTime, double wallClockTime, CCAnimationEventsVector*, bool& didAnimate, bool& needsAnimateLayers); - void setBackgroundTickingEnabled(bool); - IntSize contentSize() const; - - void sendDidLoseContextRecursive(CCLayerImpl*); - void clearRenderSurfaces(); - bool ensureRenderSurfaceLayerList(); - void clearCurrentlyScrollingLayer(); - - void animateScrollbarsRecursive(CCLayerImpl*, double monotonicTime); - - void dumpRenderSurfaces(TextStream&, int indent, const CCLayerImpl*) const; - - OwnPtr<CCGraphicsContext> m_context; - OwnPtr<CCResourceProvider> m_resourceProvider; - OwnPtr<CCRenderer> m_renderer; - OwnPtr<CCLayerImpl> m_rootLayerImpl; - CCLayerImpl* m_rootScrollLayerImpl; - CCLayerImpl* m_currentlyScrollingLayerImpl; - CCHeadsUpDisplayLayerImpl* m_hudLayerImpl; - int m_scrollingLayerIdFromPreviousTree; - bool m_scrollDeltaIsInScreenSpace; - CCLayerTreeSettings m_settings; - IntSize m_layoutViewportSize; - IntSize m_deviceViewportSize; - float m_deviceScaleFactor; - bool m_visible; - bool m_contentsTexturesPurged; - size_t m_memoryAllocationLimitBytes; - - float m_pageScale; - float m_pageScaleDelta; - float m_sentPageScaleDelta; - float m_minPageScale, m_maxPageScale; - - SkColor m_backgroundColor; - bool m_hasTransparentBackground; - - // If this is true, it is necessary to traverse the layer tree ticking the animators. - bool m_needsAnimateLayers; - bool m_pinchGestureActive; - IntPoint m_previousPinchAnchor; - - OwnPtr<CCPageScaleAnimation> m_pageScaleAnimation; - - // This is used for ticking animations slowly when hidden. - OwnPtr<CCLayerTreeHostImplTimeSourceAdapter> m_timeSourceClientAdapter; - - CCLayerSorter m_layerSorter; - - // List of visible layers for the most recently prepared frame. Used for - // rendering and input event hit testing. - CCLayerList m_renderSurfaceLayerList; - - OwnPtr<CCFrameRateCounter> m_fpsCounter; - OwnPtr<CCDebugRectHistory> m_debugRectHistory; -}; - -}; - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCMathUtil.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCMathUtil.cpp deleted file mode 100644 index cad0a5d63..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCMathUtil.cpp +++ /dev/null @@ -1,399 +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 "CCMathUtil.h" - -#include "FloatPoint.h" -#include "FloatQuad.h" -#include "IntRect.h" -#include <public/WebTransformationMatrix.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -static HomogeneousCoordinate projectHomogeneousPoint(const WebTransformationMatrix& transform, const FloatPoint& p) -{ - // In this case, the layer we are trying to project onto is perpendicular to ray - // (point p and z-axis direction) that we are trying to project. This happens when the - // layer is rotated so that it is infinitesimally thin, or when it is co-planar with - // the camera origin -- i.e. when the layer is invisible anyway. - if (!transform.m33()) - return HomogeneousCoordinate(0, 0, 0, 1); - - double x = p.x(); - double y = p.y(); - double z = -(transform.m13() * x + transform.m23() * y + transform.m43()) / transform.m33(); - // implicit definition of w = 1; - - double outX = x * transform.m11() + y * transform.m21() + z * transform.m31() + transform.m41(); - double outY = x * transform.m12() + y * transform.m22() + z * transform.m32() + transform.m42(); - double outZ = x * transform.m13() + y * transform.m23() + z * transform.m33() + transform.m43(); - double outW = x * transform.m14() + y * transform.m24() + z * transform.m34() + transform.m44(); - - return HomogeneousCoordinate(outX, outY, outZ, outW); -} - -static HomogeneousCoordinate mapHomogeneousPoint(const WebTransformationMatrix& transform, const FloatPoint3D& p) -{ - double x = p.x(); - double y = p.y(); - double z = p.z(); - // implicit definition of w = 1; - - double outX = x * transform.m11() + y * transform.m21() + z * transform.m31() + transform.m41(); - double outY = x * transform.m12() + y * transform.m22() + z * transform.m32() + transform.m42(); - double outZ = x * transform.m13() + y * transform.m23() + z * transform.m33() + transform.m43(); - double outW = x * transform.m14() + y * transform.m24() + z * transform.m34() + transform.m44(); - - return HomogeneousCoordinate(outX, outY, outZ, outW); -} - -static HomogeneousCoordinate computeClippedPointForEdge(const HomogeneousCoordinate& h1, const HomogeneousCoordinate& h2) -{ - // Points h1 and h2 form a line in 4d, and any point on that line can be represented - // as an interpolation between h1 and h2: - // p = (1-t) h1 + (t) h2 - // - // We want to compute point p such that p.w == epsilon, where epsilon is a small - // non-zero number. (but the smaller the number is, the higher the risk of overflow) - // To do this, we solve for t in the following equation: - // p.w = epsilon = (1-t) * h1.w + (t) * h2.w - // - // Once paramter t is known, the rest of p can be computed via p = (1-t) h1 + (t) h2. - - // Technically this is a special case of the following assertion, but its a good idea to keep it an explicit sanity check here. - ASSERT(h2.w != h1.w); - // Exactly one of h1 or h2 (but not both) must be on the negative side of the w plane when this is called. - ASSERT(h1.shouldBeClipped() ^ h2.shouldBeClipped()); - - double w = 0.00001; // or any positive non-zero small epsilon - - double t = (w - h1.w) / (h2.w - h1.w); - - double x = (1-t) * h1.x + t * h2.x; - double y = (1-t) * h1.y + t * h2.y; - double z = (1-t) * h1.z + t * h2.z; - - return HomogeneousCoordinate(x, y, z, w); -} - -static inline void expandBoundsToIncludePoint(float& xmin, float& xmax, float& ymin, float& ymax, const FloatPoint& p) -{ - xmin = std::min(p.x(), xmin); - xmax = std::max(p.x(), xmax); - ymin = std::min(p.y(), ymin); - ymax = std::max(p.y(), ymax); -} - -static inline void addVertexToClippedQuad(const FloatPoint& newVertex, FloatPoint clippedQuad[8], int& numVerticesInClippedQuad) -{ - clippedQuad[numVerticesInClippedQuad] = newVertex; - numVerticesInClippedQuad++; -} - -IntRect CCMathUtil::mapClippedRect(const WebTransformationMatrix& transform, const IntRect& srcRect) -{ - return enclosingIntRect(mapClippedRect(transform, FloatRect(srcRect))); -} - -FloatRect CCMathUtil::mapClippedRect(const WebTransformationMatrix& transform, const FloatRect& srcRect) -{ - if (transform.isIdentityOrTranslation()) { - FloatRect mappedRect(srcRect); - mappedRect.move(static_cast<float>(transform.m41()), static_cast<float>(transform.m42())); - return mappedRect; - } - - // Apply the transform, but retain the result in homogeneous coordinates. - FloatQuad q = FloatQuad(FloatRect(srcRect)); - HomogeneousCoordinate h1 = mapHomogeneousPoint(transform, q.p1()); - HomogeneousCoordinate h2 = mapHomogeneousPoint(transform, q.p2()); - HomogeneousCoordinate h3 = mapHomogeneousPoint(transform, q.p3()); - HomogeneousCoordinate h4 = mapHomogeneousPoint(transform, q.p4()); - - return computeEnclosingClippedRect(h1, h2, h3, h4); -} - -FloatRect CCMathUtil::projectClippedRect(const WebTransformationMatrix& transform, const FloatRect& srcRect) -{ - // Perform the projection, but retain the result in homogeneous coordinates. - FloatQuad q = FloatQuad(FloatRect(srcRect)); - HomogeneousCoordinate h1 = projectHomogeneousPoint(transform, q.p1()); - HomogeneousCoordinate h2 = projectHomogeneousPoint(transform, q.p2()); - HomogeneousCoordinate h3 = projectHomogeneousPoint(transform, q.p3()); - HomogeneousCoordinate h4 = projectHomogeneousPoint(transform, q.p4()); - - return computeEnclosingClippedRect(h1, h2, h3, h4); -} - -void CCMathUtil::mapClippedQuad(const WebTransformationMatrix& transform, const FloatQuad& srcQuad, FloatPoint clippedQuad[8], int& numVerticesInClippedQuad) -{ - HomogeneousCoordinate h1 = mapHomogeneousPoint(transform, srcQuad.p1()); - HomogeneousCoordinate h2 = mapHomogeneousPoint(transform, srcQuad.p2()); - HomogeneousCoordinate h3 = mapHomogeneousPoint(transform, srcQuad.p3()); - HomogeneousCoordinate h4 = mapHomogeneousPoint(transform, srcQuad.p4()); - - // The order of adding the vertices to the array is chosen so that clockwise / counter-clockwise orientation is retained. - - numVerticesInClippedQuad = 0; - - if (!h1.shouldBeClipped()) - addVertexToClippedQuad(h1.cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - if (h1.shouldBeClipped() ^ h2.shouldBeClipped()) - addVertexToClippedQuad(computeClippedPointForEdge(h1, h2).cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - if (!h2.shouldBeClipped()) - addVertexToClippedQuad(h2.cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - if (h2.shouldBeClipped() ^ h3.shouldBeClipped()) - addVertexToClippedQuad(computeClippedPointForEdge(h2, h3).cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - if (!h3.shouldBeClipped()) - addVertexToClippedQuad(h3.cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - if (h3.shouldBeClipped() ^ h4.shouldBeClipped()) - addVertexToClippedQuad(computeClippedPointForEdge(h3, h4).cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - if (!h4.shouldBeClipped()) - addVertexToClippedQuad(h4.cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - if (h4.shouldBeClipped() ^ h1.shouldBeClipped()) - addVertexToClippedQuad(computeClippedPointForEdge(h4, h1).cartesianPoint2d(), clippedQuad, numVerticesInClippedQuad); - - ASSERT(numVerticesInClippedQuad <= 8); -} - -FloatRect CCMathUtil::computeEnclosingRectOfVertices(FloatPoint vertices[], int numVertices) -{ - if (numVertices < 2) - return FloatRect(); - - float xmin = std::numeric_limits<float>::max(); - float xmax = -std::numeric_limits<float>::max(); - float ymin = std::numeric_limits<float>::max(); - float ymax = -std::numeric_limits<float>::max(); - - for (int i = 0; i < numVertices; ++i) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, vertices[i]); - - return FloatRect(FloatPoint(xmin, ymin), FloatSize(xmax - xmin, ymax - ymin)); -} - -FloatRect CCMathUtil::computeEnclosingClippedRect(const HomogeneousCoordinate& h1, const HomogeneousCoordinate& h2, const HomogeneousCoordinate& h3, const HomogeneousCoordinate& h4) -{ - // This function performs clipping as necessary and computes the enclosing 2d - // FloatRect of the vertices. Doing these two steps simultaneously allows us to avoid - // the overhead of storing an unknown number of clipped vertices. - - // If no vertices on the quad are clipped, then we can simply return the enclosing rect directly. - bool somethingClipped = h1.shouldBeClipped() || h2.shouldBeClipped() || h3.shouldBeClipped() || h4.shouldBeClipped(); - if (!somethingClipped) { - FloatQuad mappedQuad = FloatQuad(h1.cartesianPoint2d(), h2.cartesianPoint2d(), h3.cartesianPoint2d(), h4.cartesianPoint2d()); - return mappedQuad.boundingBox(); - } - - bool everythingClipped = h1.shouldBeClipped() && h2.shouldBeClipped() && h3.shouldBeClipped() && h4.shouldBeClipped(); - if (everythingClipped) - return FloatRect(); - - - float xmin = std::numeric_limits<float>::max(); - float xmax = -std::numeric_limits<float>::max(); - float ymin = std::numeric_limits<float>::max(); - float ymax = -std::numeric_limits<float>::max(); - - if (!h1.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, h1.cartesianPoint2d()); - - if (h1.shouldBeClipped() ^ h2.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, computeClippedPointForEdge(h1, h2).cartesianPoint2d()); - - if (!h2.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, h2.cartesianPoint2d()); - - if (h2.shouldBeClipped() ^ h3.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, computeClippedPointForEdge(h2, h3).cartesianPoint2d()); - - if (!h3.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, h3.cartesianPoint2d()); - - if (h3.shouldBeClipped() ^ h4.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, computeClippedPointForEdge(h3, h4).cartesianPoint2d()); - - if (!h4.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, h4.cartesianPoint2d()); - - if (h4.shouldBeClipped() ^ h1.shouldBeClipped()) - expandBoundsToIncludePoint(xmin, xmax, ymin, ymax, computeClippedPointForEdge(h4, h1).cartesianPoint2d()); - - return FloatRect(FloatPoint(xmin, ymin), FloatSize(xmax - xmin, ymax - ymin)); -} - -FloatQuad CCMathUtil::mapQuad(const WebTransformationMatrix& transform, const FloatQuad& q, bool& clipped) -{ - if (transform.isIdentityOrTranslation()) { - FloatQuad mappedQuad(q); - mappedQuad.move(static_cast<float>(transform.m41()), static_cast<float>(transform.m42())); - clipped = false; - return mappedQuad; - } - - HomogeneousCoordinate h1 = mapHomogeneousPoint(transform, q.p1()); - HomogeneousCoordinate h2 = mapHomogeneousPoint(transform, q.p2()); - HomogeneousCoordinate h3 = mapHomogeneousPoint(transform, q.p3()); - HomogeneousCoordinate h4 = mapHomogeneousPoint(transform, q.p4()); - - clipped = h1.shouldBeClipped() || h2.shouldBeClipped() || h3.shouldBeClipped() || h4.shouldBeClipped(); - - // Result will be invalid if clipped == true. But, compute it anyway just in case, to emulate existing behavior. - return FloatQuad(h1.cartesianPoint2d(), h2.cartesianPoint2d(), h3.cartesianPoint2d(), h4.cartesianPoint2d()); -} - -FloatPoint CCMathUtil::mapPoint(const WebTransformationMatrix& transform, const FloatPoint& p, bool& clipped) -{ - HomogeneousCoordinate h = mapHomogeneousPoint(transform, p); - - if (h.w > 0) { - clipped = false; - return h.cartesianPoint2d(); - } - - // The cartesian coordinates will be invalid after dividing by w. - clipped = true; - - // Avoid dividing by w if w == 0. - if (!h.w) - return FloatPoint(); - - // This return value will be invalid because clipped == true, but (1) users of this - // code should be ignoring the return value when clipped == true anyway, and (2) this - // behavior is more consistent with existing behavior of WebKit transforms if the user - // really does not ignore the return value. - return h.cartesianPoint2d(); -} - -FloatPoint3D CCMathUtil::mapPoint(const WebTransformationMatrix& transform, const FloatPoint3D& p, bool& clipped) -{ - HomogeneousCoordinate h = mapHomogeneousPoint(transform, p); - - if (h.w > 0) { - clipped = false; - return h.cartesianPoint3d(); - } - - // The cartesian coordinates will be invalid after dividing by w. - clipped = true; - - // Avoid dividing by w if w == 0. - if (!h.w) - return FloatPoint3D(); - - // This return value will be invalid because clipped == true, but (1) users of this - // code should be ignoring the return value when clipped == true anyway, and (2) this - // behavior is more consistent with existing behavior of WebKit transforms if the user - // really does not ignore the return value. - return h.cartesianPoint3d(); -} - -FloatQuad CCMathUtil::projectQuad(const WebTransformationMatrix& transform, const FloatQuad& q, bool& clipped) -{ - FloatQuad projectedQuad; - bool clippedPoint; - projectedQuad.setP1(projectPoint(transform, q.p1(), clippedPoint)); - clipped = clippedPoint; - projectedQuad.setP2(projectPoint(transform, q.p2(), clippedPoint)); - clipped |= clippedPoint; - projectedQuad.setP3(projectPoint(transform, q.p3(), clippedPoint)); - clipped |= clippedPoint; - projectedQuad.setP4(projectPoint(transform, q.p4(), clippedPoint)); - clipped |= clippedPoint; - - return projectedQuad; -} - -FloatPoint CCMathUtil::projectPoint(const WebTransformationMatrix& transform, const FloatPoint& p, bool& clipped) -{ - HomogeneousCoordinate h = projectHomogeneousPoint(transform, p); - - if (h.w > 0) { - // The cartesian coordinates will be valid in this case. - clipped = false; - return h.cartesianPoint2d(); - } - - // The cartesian coordinates will be invalid after dividing by w. - clipped = true; - - // Avoid dividing by w if w == 0. - if (!h.w) - return FloatPoint(); - - // This return value will be invalid because clipped == true, but (1) users of this - // code should be ignoring the return value when clipped == true anyway, and (2) this - // behavior is more consistent with existing behavior of WebKit transforms if the user - // really does not ignore the return value. - return h.cartesianPoint2d(); -} - -void CCMathUtil::flattenTransformTo2d(WebTransformationMatrix& transform) -{ - // Set both the 3rd row and 3rd column to (0, 0, 1, 0). - // - // One useful interpretation of doing this operation: - // - For x and y values, the new transform behaves effectively like an orthographic - // projection was added to the matrix sequence. - // - For z values, the new transform overrides any effect that the transform had on - // z, and instead it preserves the z value for any points that are transformed. - // - Because of linearity of transforms, this flattened transform also preserves the - // effect that any subsequent (post-multiplied) transforms would have on z values. - // - transform.setM13(0); - transform.setM23(0); - transform.setM31(0); - transform.setM32(0); - transform.setM33(1); - transform.setM34(0); - transform.setM43(0); -} - -float CCMathUtil::smallestAngleBetweenVectors(const FloatSize& v1, const FloatSize& v2) -{ - float dotProduct = (v1.width() * v2.width() + v1.height() * v2.height()) / (v1.diagonalLength() * v2.diagonalLength()); - // Clamp to compensate for rounding errors. - dotProduct = std::max(-1.f, std::min(1.f, dotProduct)); - return rad2deg(acosf(dotProduct)); -} - -FloatSize CCMathUtil::projectVector(const FloatSize& source, const FloatSize& destination) -{ - float sourceDotDestination = source.width() * destination.width() + source.height() * destination.height(); - float projectedLength = sourceDotDestination / destination.diagonalLengthSquared(); - return FloatSize(projectedLength * destination.width(), projectedLength * destination.height()); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCMathUtil.h b/Source/WebCore/platform/graphics/chromium/cc/CCMathUtil.h deleted file mode 100644 index 0f9e7a0e3..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCMathUtil.h +++ /dev/null @@ -1,129 +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 CCMathUtil_h -#define CCMathUtil_h - -#include "FloatPoint.h" -#include "FloatPoint3D.h" - -namespace WebKit { -class WebTransformationMatrix; -} - -namespace WebCore { - -class IntRect; -class FloatRect; -class FloatQuad; - -struct HomogeneousCoordinate { - HomogeneousCoordinate(double newX, double newY, double newZ, double newW) - : x(newX) - , y(newY) - , z(newZ) - , w(newW) - { - } - - bool shouldBeClipped() const - { - return w <= 0; - } - - FloatPoint cartesianPoint2d() const - { - if (w == 1) - return FloatPoint(x, y); - - // For now, because this code is used privately only by CCMathUtil, it should never be called when w == 0, and we do not yet need to handle that case. - ASSERT(w); - double invW = 1.0 / w; - return FloatPoint(x * invW, y * invW); - } - - FloatPoint3D cartesianPoint3d() const - { - if (w == 1) - return FloatPoint3D(x, y, z); - - // For now, because this code is used privately only by CCMathUtil, it should never be called when w == 0, and we do not yet need to handle that case. - ASSERT(w); - double invW = 1.0 / w; - return FloatPoint3D(x * invW, y * invW, z * invW); - } - - double x; - double y; - double z; - double w; -}; - -// This class contains math helper functionality that does not belong in WebCore. -// It is possible that this functionality should be migrated to WebCore eventually. -class CCMathUtil { -public: - - // Background: WebTransformationMatrix code in WebCore does not do the right thing in - // mapRect / mapQuad / projectQuad when there is a perspective projection that causes - // one of the transformed vertices to go to w < 0. In those cases, it is necessary to - // perform clipping in homogeneous coordinates, after applying the transform, before - // dividing-by-w to convert to cartesian coordinates. - // - // These functions return the axis-aligned rect that encloses the correctly clipped, - // transformed polygon. - static IntRect mapClippedRect(const WebKit::WebTransformationMatrix&, const IntRect&); - static FloatRect mapClippedRect(const WebKit::WebTransformationMatrix&, const FloatRect&); - static FloatRect projectClippedRect(const WebKit::WebTransformationMatrix&, const FloatRect&); - - // Returns an array of vertices that represent the clipped polygon. After returning, indexes from - // 0 to numVerticesInClippedQuad are valid in the clippedQuad array. Note that - // numVerticesInClippedQuad may be zero, which means the entire quad was clipped, and - // none of the vertices in the array are valid. - static void mapClippedQuad(const WebKit::WebTransformationMatrix&, const FloatQuad& srcQuad, FloatPoint clippedQuad[8], int& numVerticesInClippedQuad); - - static FloatRect computeEnclosingRectOfVertices(FloatPoint vertices[], int numVertices); - static FloatRect computeEnclosingClippedRect(const HomogeneousCoordinate& h1, const HomogeneousCoordinate& h2, const HomogeneousCoordinate& h3, const HomogeneousCoordinate& h4); - - // NOTE: These functions do not do correct clipping against w = 0 plane, but they - // correctly detect the clipped condition via the boolean clipped. - static FloatQuad mapQuad(const WebKit::WebTransformationMatrix&, const FloatQuad&, bool& clipped); - static FloatPoint mapPoint(const WebKit::WebTransformationMatrix&, const FloatPoint&, bool& clipped); - static FloatPoint3D mapPoint(const WebKit::WebTransformationMatrix&, const FloatPoint3D&, bool& clipped); - static FloatQuad projectQuad(const WebKit::WebTransformationMatrix&, const FloatQuad&, bool& clipped); - static FloatPoint projectPoint(const WebKit::WebTransformationMatrix&, const FloatPoint&, bool& clipped); - - static void flattenTransformTo2d(WebKit::WebTransformationMatrix&); - - // Returns the smallest angle between the given two vectors in degrees. Neither vector is - // assumed to be normalized. - static float smallestAngleBetweenVectors(const FloatSize&, const FloatSize&); - - // Projects the |source| vector onto |destination|. Neither vector is assumed to be normalized. - static FloatSize projectVector(const FloatSize& source, const FloatSize& destination); -}; - -} // namespace WebCore - -#endif // #define CCMathUtil_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCOcclusionTracker.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCOcclusionTracker.cpp deleted file mode 100644 index a0f0e247b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCOcclusionTracker.cpp +++ /dev/null @@ -1,503 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCOcclusionTracker.h" - -#include "CCLayerImpl.h" -#include "CCMathUtil.h" -#include "CCOverdrawMetrics.h" -#include "LayerChromium.h" -#include <algorithm> - -using namespace std; -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -template<typename LayerType, typename RenderSurfaceType> -CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::CCOcclusionTrackerBase(IntRect rootTargetRect, bool recordMetricsForFrame) - : m_rootTargetRect(rootTargetRect) - , m_overdrawMetrics(CCOverdrawMetrics::create(recordMetricsForFrame)) - , m_occludingScreenSpaceRects(0) -{ -} - -template<typename LayerType, typename RenderSurfaceType> -void CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::enterLayer(const CCLayerIteratorPosition<LayerType>& layerIterator) -{ - LayerType* renderTarget = layerIterator.targetRenderSurfaceLayer; - - if (layerIterator.representsItself) - enterRenderTarget(renderTarget); - else if (layerIterator.representsTargetRenderSurface) - finishedRenderTarget(renderTarget); -} - -template<typename LayerType, typename RenderSurfaceType> -void CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::leaveLayer(const CCLayerIteratorPosition<LayerType>& layerIterator) -{ - LayerType* renderTarget = layerIterator.targetRenderSurfaceLayer; - - if (layerIterator.representsItself) - markOccludedBehindLayer(layerIterator.currentLayer); - else if (layerIterator.representsContributingRenderSurface) - leaveToRenderTarget(renderTarget); -} - -template<typename LayerType, typename RenderSurfaceType> -void CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::enterRenderTarget(const LayerType* newTarget) -{ - if (!m_stack.isEmpty() && m_stack.last().target == newTarget) - return; - - const LayerType* oldTarget = m_stack.isEmpty() ? 0 : m_stack.last().target; - const RenderSurfaceType* oldAncestorThatMovesPixels = !oldTarget ? 0 : oldTarget->renderSurface()->nearestAncestorThatMovesPixels(); - const RenderSurfaceType* newAncestorThatMovesPixels = newTarget->renderSurface()->nearestAncestorThatMovesPixels(); - - m_stack.append(StackObject(newTarget)); - - // We copy the screen occlusion into the new RenderSurface subtree, but we never copy in the - // target occlusion, since we are looking at a new RenderSurface target. - - // If we are entering a subtree that is going to move pixels around, then the occlusion we've computed - // so far won't apply to the pixels we're drawing here in the same way. We discard the occlusion thus - // far to be safe, and ensure we don't cull any pixels that are moved such that they become visible. - bool enteringSubtreeThatMovesPixels = newAncestorThatMovesPixels && newAncestorThatMovesPixels != oldAncestorThatMovesPixels; - - bool copyScreenOcclusionForward = m_stack.size() > 1 && !enteringSubtreeThatMovesPixels; - if (copyScreenOcclusionForward) { - int lastIndex = m_stack.size() - 1; - m_stack[lastIndex].occlusionInScreen = m_stack[lastIndex - 1].occlusionInScreen; - } -} - -static inline bool layerOpacityKnown(const LayerChromium* layer) { return !layer->drawOpacityIsAnimating(); } -static inline bool layerOpacityKnown(const CCLayerImpl*) { return true; } -static inline bool layerTransformsToTargetKnown(const LayerChromium* layer) { return !layer->drawTransformIsAnimating(); } -static inline bool layerTransformsToTargetKnown(const CCLayerImpl*) { return true; } -static inline bool layerTransformsToScreenKnown(const LayerChromium* layer) { return !layer->screenSpaceTransformIsAnimating(); } -static inline bool layerTransformsToScreenKnown(const CCLayerImpl*) { return true; } - -static inline bool surfaceOpacityKnown(const RenderSurfaceChromium* surface) { return !surface->drawOpacityIsAnimating(); } -static inline bool surfaceOpacityKnown(const CCRenderSurface*) { return true; } -static inline bool surfaceTransformsToTargetKnown(const RenderSurfaceChromium* surface) { return !surface->targetSurfaceTransformsAreAnimating(); } -static inline bool surfaceTransformsToTargetKnown(const CCRenderSurface*) { return true; } -static inline bool surfaceTransformsToScreenKnown(const RenderSurfaceChromium* surface) { return !surface->screenSpaceTransformsAreAnimating(); } -static inline bool surfaceTransformsToScreenKnown(const CCRenderSurface*) { return true; } - -static inline bool layerIsInUnsorted3dRenderingContext(const LayerChromium* layer) { return layer->parent() && layer->parent()->preserves3D(); } -static inline bool layerIsInUnsorted3dRenderingContext(const CCLayerImpl*) { return false; } - -template<typename LayerType, typename RenderSurfaceType> -void CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::finishedRenderTarget(const LayerType* finishedTarget) -{ - // Make sure we know about the target surface. - enterRenderTarget(finishedTarget); - - RenderSurfaceType* surface = finishedTarget->renderSurface(); - - // If the occlusion within the surface can not be applied to things outside of the surface's subtree, then clear the occlusion here so it won't be used. - if (finishedTarget->maskLayer() || !surfaceOpacityKnown(surface) || surface->drawOpacity() < 1 || finishedTarget->filters().hasFilterThatAffectsOpacity()) { - m_stack.last().occlusionInScreen = Region(); - m_stack.last().occlusionInTarget = Region(); - } else { - if (!surfaceTransformsToTargetKnown(surface)) - m_stack.last().occlusionInTarget = Region(); - if (!surfaceTransformsToScreenKnown(surface)) - m_stack.last().occlusionInScreen = Region(); - } -} - -template<typename RenderSurfaceType> -static inline Region transformSurfaceOpaqueRegion(const RenderSurfaceType* surface, const Region& region, const WebTransformationMatrix& transform) -{ - // Verify that rects within the |surface| will remain rects in its target surface after applying |transform|. If this is true, then - // apply |transform| to each rect within |region| in order to transform the entire Region. - - bool clipped; - FloatQuad transformedBoundsQuad = CCMathUtil::mapQuad(transform, FloatQuad(region.bounds()), clipped); - // FIXME: Find a rect interior to each transformed quad. - if (clipped || !transformedBoundsQuad.isRectilinear()) - return Region(); - - Region transformedRegion; - - Vector<IntRect> rects = region.rects(); - for (size_t i = 0; i < rects.size(); ++i) { - // We've already checked for clipping in the mapQuad call above, these calls should not clip anything further. - IntRect transformedRect = enclosedIntRect(CCMathUtil::mapClippedRect(transform, FloatRect(rects[i]))); - if (!surface->clipRect().isEmpty()) - transformedRect.intersect(surface->clipRect()); - transformedRegion.unite(transformedRect); - } - return transformedRegion; -} - -static inline void reduceOcclusion(const IntRect& affectedArea, const IntRect& expandedPixel, Region& occlusion) -{ - if (affectedArea.isEmpty()) - return; - - Region affectedOcclusion = intersect(occlusion, affectedArea); - Vector<IntRect> affectedOcclusionRects = affectedOcclusion.rects(); - - occlusion.subtract(affectedArea); - for (size_t j = 0; j < affectedOcclusionRects.size(); ++j) { - IntRect& occlusionRect = affectedOcclusionRects[j]; - - // Shrink the rect by expanding the non-opaque pixels outside the rect. - - // The expandedPixel is the IntRect for a single pixel after being - // expanded by filters on the layer. The original pixel would be - // IntRect(0, 0, 1, 1), and the expanded pixel is the rect, relative - // to this original rect, that the original pixel can influence after - // being filtered. - // To convert the expandedPixel IntRect back to filter outsets: - // x = -leftOutset - // width = leftOutset + rightOutset - // maxX = x + width = -leftOutset + leftOutset + rightOutset = rightOutset - - // The leftOutset of the filters moves pixels on the right side of - // the occlusionRect into it, shrinking its right edge. - int shrinkLeft = occlusionRect.x() == affectedArea.x() ? 0 : expandedPixel.maxX(); - int shrinkTop = occlusionRect.y() == affectedArea.y() ? 0 : expandedPixel.maxY(); - int shrinkRight = occlusionRect.maxX() == affectedArea.maxX() ? 0 : -expandedPixel.x(); - int shrinkBottom = occlusionRect.maxY() == affectedArea.maxY() ? 0 : -expandedPixel.y(); - - occlusionRect.move(shrinkLeft, shrinkTop); - occlusionRect.contract(shrinkLeft + shrinkRight, shrinkTop + shrinkBottom); - - occlusion.unite(occlusionRect); - } -} - -template<typename LayerType> -static void reduceOcclusionBelowSurface(LayerType* contributingLayer, const IntRect& surfaceRect, const WebTransformationMatrix& surfaceTransform, LayerType* renderTarget, Region& occlusionInTarget, Region& occlusionInScreen) -{ - if (surfaceRect.isEmpty()) - return; - - IntRect boundsInTarget = enclosingIntRect(CCMathUtil::mapClippedRect(surfaceTransform, FloatRect(surfaceRect))); - if (!contributingLayer->renderSurface()->clipRect().isEmpty()) - boundsInTarget.intersect(contributingLayer->renderSurface()->clipRect()); - - int outsetTop, outsetRight, outsetBottom, outsetLeft; - contributingLayer->backgroundFilters().getOutsets(outsetTop, outsetRight, outsetBottom, outsetLeft); - - // The filter can move pixels from outside of the clip, so allow affectedArea to expand outside the clip. - boundsInTarget.move(-outsetLeft, -outsetTop); - boundsInTarget.expand(outsetLeft + outsetRight, outsetTop + outsetBottom); - - IntRect boundsInScreen = enclosingIntRect(CCMathUtil::mapClippedRect(renderTarget->renderSurface()->screenSpaceTransform(), FloatRect(boundsInTarget))); - - IntRect filterOutsetsInTarget(-outsetLeft, -outsetTop, outsetLeft + outsetRight, outsetTop + outsetBottom); - IntRect filterOutsetsInScreen = enclosingIntRect(CCMathUtil::mapClippedRect(renderTarget->renderSurface()->screenSpaceTransform(), FloatRect(filterOutsetsInTarget))); - - reduceOcclusion(boundsInTarget, filterOutsetsInTarget, occlusionInTarget); - reduceOcclusion(boundsInScreen, filterOutsetsInScreen, occlusionInScreen); -} - -template<typename LayerType, typename RenderSurfaceType> -void CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::leaveToRenderTarget(const LayerType* newTarget) -{ - int lastIndex = m_stack.size() - 1; - bool surfaceWillBeAtTopAfterPop = m_stack.size() > 1 && m_stack[lastIndex - 1].target == newTarget; - - // We merge the screen occlusion from the current RenderSurface subtree out to its parent target RenderSurface. - // The target occlusion can be merged out as well but needs to be transformed to the new target. - - const LayerType* oldTarget = m_stack[lastIndex].target; - const RenderSurfaceType* oldSurface = oldTarget->renderSurface(); - Region oldTargetOcclusionInNewTarget = transformSurfaceOpaqueRegion<RenderSurfaceType>(oldSurface, m_stack[lastIndex].occlusionInTarget, oldSurface->drawTransform()); - if (oldTarget->hasReplica() && !oldTarget->replicaHasMask()) - oldTargetOcclusionInNewTarget.unite(transformSurfaceOpaqueRegion<RenderSurfaceType>(oldSurface, m_stack[lastIndex].occlusionInTarget, oldSurface->replicaDrawTransform())); - - IntRect unoccludedSurfaceRect; - IntRect unoccludedReplicaRect; - if (oldTarget->backgroundFilters().hasFilterThatMovesPixels()) { - unoccludedSurfaceRect = unoccludedContributingSurfaceContentRect(oldTarget, false, oldSurface->contentRect()); - if (oldTarget->hasReplica()) - unoccludedReplicaRect = unoccludedContributingSurfaceContentRect(oldTarget, true, oldSurface->contentRect()); - } - - if (surfaceWillBeAtTopAfterPop) { - // Merge the top of the stack down. - m_stack[lastIndex - 1].occlusionInScreen.unite(m_stack[lastIndex].occlusionInScreen); - m_stack[lastIndex - 1].occlusionInTarget.unite(oldTargetOcclusionInNewTarget); - m_stack.removeLast(); - } else { - // Replace the top of the stack with the new pushed surface. Copy the occluded screen region to the top. - m_stack.last().target = newTarget; - m_stack.last().occlusionInTarget = oldTargetOcclusionInNewTarget; - } - - if (oldTarget->backgroundFilters().hasFilterThatMovesPixels()) { - reduceOcclusionBelowSurface(oldTarget, unoccludedSurfaceRect, oldSurface->drawTransform(), newTarget, m_stack.last().occlusionInTarget, m_stack.last().occlusionInScreen); - if (oldTarget->hasReplica()) - reduceOcclusionBelowSurface(oldTarget, unoccludedReplicaRect, oldSurface->replicaDrawTransform(), newTarget, m_stack.last().occlusionInTarget, m_stack.last().occlusionInScreen); - } -} - -// FIXME: Remove usePaintTracking when paint tracking is on for paint culling. -template<typename LayerType> -static inline void addOcclusionBehindLayer(Region& region, const LayerType* layer, const WebTransformationMatrix& transform, const Region& opaqueContents, const IntRect& clipRectInTarget, const IntSize& minimumTrackingSize, Vector<IntRect>* occludingScreenSpaceRects) -{ - ASSERT(layer->visibleContentRect().contains(opaqueContents.bounds())); - - bool clipped; - FloatQuad visibleTransformedQuad = CCMathUtil::mapQuad(transform, FloatQuad(layer->visibleContentRect()), clipped); - // FIXME: Find a rect interior to each transformed quad. - if (clipped || !visibleTransformedQuad.isRectilinear()) - return; - - Vector<IntRect> contentRects = opaqueContents.rects(); - for (size_t i = 0; i < contentRects.size(); ++i) { - // We've already checked for clipping in the mapQuad call above, these calls should not clip anything further. - IntRect transformedRect = enclosedIntRect(CCMathUtil::mapClippedRect(transform, FloatRect(contentRects[i]))); - transformedRect.intersect(clipRectInTarget); - if (transformedRect.width() >= minimumTrackingSize.width() || transformedRect.height() >= minimumTrackingSize.height()) { - if (occludingScreenSpaceRects) - occludingScreenSpaceRects->append(transformedRect); - region.unite(transformedRect); - } - } -} - -template<typename LayerType, typename RenderSurfaceType> -void CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::markOccludedBehindLayer(const LayerType* layer) -{ - ASSERT(!m_stack.isEmpty()); - ASSERT(layer->renderTarget() == m_stack.last().target); - if (m_stack.isEmpty()) - return; - - if (!layerOpacityKnown(layer) || layer->drawOpacity() < 1) - return; - - if (layerIsInUnsorted3dRenderingContext(layer)) - return; - - Region opaqueContents = layer->visibleContentOpaqueRegion(); - if (opaqueContents.isEmpty()) - return; - - IntRect clipRectInTarget = layerClipRectInTarget(layer); - if (layerTransformsToTargetKnown(layer)) - addOcclusionBehindLayer<LayerType>(m_stack.last().occlusionInTarget, layer, layer->drawTransform(), opaqueContents, clipRectInTarget, m_minimumTrackingSize, 0); - - // We must clip the occlusion within the layer's clipRectInTarget within screen space as well. If the clip rect can't be moved to screen space and - // remain rectilinear, then we don't add any occlusion in screen space. - - if (layerTransformsToScreenKnown(layer)) { - WebTransformationMatrix targetToScreenTransform = m_stack.last().target->renderSurface()->screenSpaceTransform(); - bool clipped; - FloatQuad clipQuadInScreen = CCMathUtil::mapQuad(targetToScreenTransform, FloatQuad(FloatRect(clipRectInTarget)), clipped); - // FIXME: Find a rect interior to the transformed clip quad. - if (clipped || !clipQuadInScreen.isRectilinear()) - return; - IntRect clipRectInScreen = intersection(m_rootTargetRect, enclosedIntRect(clipQuadInScreen.boundingBox())); - addOcclusionBehindLayer<LayerType>(m_stack.last().occlusionInScreen, layer, layer->screenSpaceTransform(), opaqueContents, clipRectInScreen, m_minimumTrackingSize, m_occludingScreenSpaceRects); - } -} - -static inline bool testContentRectOccluded(const IntRect& contentRect, const WebTransformationMatrix& contentSpaceTransform, const IntRect& clipRectInTarget, const Region& occlusion) -{ - FloatRect transformedRect = CCMathUtil::mapClippedRect(contentSpaceTransform, FloatRect(contentRect)); - // Take the enclosingIntRect, as we want to include partial pixels in the test. - IntRect targetRect = intersection(enclosingIntRect(transformedRect), clipRectInTarget); - return targetRect.isEmpty() || occlusion.contains(targetRect); -} - -template<typename LayerType, typename RenderSurfaceType> -bool CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::occluded(const LayerType* layer, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const -{ - if (hasOcclusionFromOutsideTargetSurface) - *hasOcclusionFromOutsideTargetSurface = false; - - ASSERT(!m_stack.isEmpty()); - if (m_stack.isEmpty()) - return false; - if (contentRect.isEmpty()) - return true; - - ASSERT(layer->renderTarget() == m_stack.last().target); - - if (layerTransformsToTargetKnown(layer) && testContentRectOccluded(contentRect, layer->drawTransform(), layerClipRectInTarget(layer), m_stack.last().occlusionInTarget)) - return true; - - if (layerTransformsToScreenKnown(layer) && testContentRectOccluded(contentRect, layer->screenSpaceTransform(), m_rootTargetRect, m_stack.last().occlusionInScreen)) { - if (hasOcclusionFromOutsideTargetSurface) - *hasOcclusionFromOutsideTargetSurface = true; - return true; - } - - return false; -} - -// Determines what portion of rect, if any, is unoccluded (not occluded by region). If -// the resulting unoccluded region is not rectangular, we return a rect containing it. -static inline IntRect rectSubtractRegion(const IntRect& rect, const Region& region) -{ - Region rectRegion(rect); - rectRegion.subtract(region); - return rectRegion.bounds(); -} - -static inline IntRect computeUnoccludedContentRect(const IntRect& contentRect, const WebTransformationMatrix& contentSpaceTransform, const IntRect& clipRectInTarget, const Region& occlusion) -{ - if (!contentSpaceTransform.isInvertible()) - return contentRect; - - // Take the enclosingIntRect at each step, as we want to contain any unoccluded partial pixels in the resulting IntRect. - FloatRect transformedRect = CCMathUtil::mapClippedRect(contentSpaceTransform, FloatRect(contentRect)); - IntRect shrunkRect = rectSubtractRegion(intersection(enclosingIntRect(transformedRect), clipRectInTarget), occlusion); - IntRect unoccludedRect = enclosingIntRect(CCMathUtil::projectClippedRect(contentSpaceTransform.inverse(), FloatRect(shrunkRect))); - // The rect back in content space is a bounding box and may extend outside of the original contentRect, so clamp it to the contentRectBounds. - return intersection(unoccludedRect, contentRect); -} - -template<typename LayerType, typename RenderSurfaceType> -IntRect CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::unoccludedContentRect(const LayerType* layer, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const -{ - ASSERT(!m_stack.isEmpty()); - if (m_stack.isEmpty()) - return contentRect; - if (contentRect.isEmpty()) - return contentRect; - - ASSERT(layer->renderTarget() == m_stack.last().target); - - // We want to return a rect that contains all the visible parts of |contentRect| in both screen space and in the target surface. - // So we find the visible parts of |contentRect| in each space, and take the intersection. - - IntRect unoccludedInScreen = contentRect; - if (layerTransformsToScreenKnown(layer)) - unoccludedInScreen = computeUnoccludedContentRect(contentRect, layer->screenSpaceTransform(), m_rootTargetRect, m_stack.last().occlusionInScreen); - - IntRect unoccludedInTarget = contentRect; - if (layerTransformsToTargetKnown(layer)) - unoccludedInTarget = computeUnoccludedContentRect(contentRect, layer->drawTransform(), layerClipRectInTarget(layer), m_stack.last().occlusionInTarget); - - if (hasOcclusionFromOutsideTargetSurface) - *hasOcclusionFromOutsideTargetSurface = (intersection(unoccludedInScreen, unoccludedInTarget) != unoccludedInTarget); - - return intersection(unoccludedInScreen, unoccludedInTarget); -} - -template<typename LayerType, typename RenderSurfaceType> -IntRect CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::unoccludedContributingSurfaceContentRect(const LayerType* layer, bool forReplica, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const -{ - ASSERT(!m_stack.isEmpty()); - // The layer is a contributing renderTarget so it should have a surface. - ASSERT(layer->renderSurface()); - // The layer is a contributing renderTarget so its target should be itself. - ASSERT(layer->renderTarget() == layer); - // The layer should not be the root, else what is is contributing to? - ASSERT(layer->parent()); - // This should be called while the layer is still considered the current target in the occlusion tracker. - ASSERT(layer == m_stack.last().target); - - if (contentRect.isEmpty()) - return contentRect; - - RenderSurfaceType* surface = layer->renderSurface(); - - IntRect surfaceClipRect = surface->clipRect(); - if (surfaceClipRect.isEmpty()) { - LayerType* contributingSurfaceRenderTarget = layer->parent()->renderTarget(); - surfaceClipRect = intersection(contributingSurfaceRenderTarget->renderSurface()->contentRect(), enclosingIntRect(surface->drawableContentRect())); - } - - // A contributing surface doesn't get occluded by things inside its own surface, so only things outside the surface can occlude it. That occlusion is - // found just below the top of the stack (if it exists). - bool hasOcclusion = m_stack.size() > 1; - - const WebTransformationMatrix& transformToScreen = forReplica ? surface->replicaScreenSpaceTransform() : surface->screenSpaceTransform(); - const WebTransformationMatrix& transformToTarget = forReplica ? surface->replicaDrawTransform() : surface->drawTransform(); - - IntRect unoccludedInScreen = contentRect; - if (surfaceTransformsToScreenKnown(surface)) { - if (hasOcclusion) { - const StackObject& secondLast = m_stack[m_stack.size() - 2]; - unoccludedInScreen = computeUnoccludedContentRect(contentRect, transformToScreen, m_rootTargetRect, secondLast.occlusionInScreen); - } else - unoccludedInScreen = computeUnoccludedContentRect(contentRect, transformToScreen, m_rootTargetRect, Region()); - } - - IntRect unoccludedInTarget = contentRect; - if (surfaceTransformsToTargetKnown(surface)) { - if (hasOcclusion) { - const StackObject& secondLast = m_stack[m_stack.size() - 2]; - unoccludedInTarget = computeUnoccludedContentRect(contentRect, transformToTarget, surfaceClipRect, secondLast.occlusionInTarget); - } else - unoccludedInTarget = computeUnoccludedContentRect(contentRect, transformToTarget, surfaceClipRect, Region()); - } - - if (hasOcclusionFromOutsideTargetSurface) - *hasOcclusionFromOutsideTargetSurface = (intersection(unoccludedInScreen, unoccludedInTarget) != unoccludedInTarget); - - return intersection(unoccludedInScreen, unoccludedInTarget); -} - -template<typename LayerType, typename RenderSurfaceType> -IntRect CCOcclusionTrackerBase<LayerType, RenderSurfaceType>::layerClipRectInTarget(const LayerType* layer) const -{ - // FIXME: we could remove this helper function, but unit tests currently override this - // function, and they need to be verified/adjusted before this can be removed. - return layer->drawableContentRect(); -} - -// Declare the possible functions here for the linker. -template CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::CCOcclusionTrackerBase(IntRect rootTargetRect, bool recordMetricsForFrame); -template void CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::enterLayer(const CCLayerIteratorPosition<LayerChromium>&); -template void CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::leaveLayer(const CCLayerIteratorPosition<LayerChromium>&); -template void CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::enterRenderTarget(const LayerChromium* newTarget); -template void CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::finishedRenderTarget(const LayerChromium* finishedTarget); -template void CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::leaveToRenderTarget(const LayerChromium* newTarget); -template void CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::markOccludedBehindLayer(const LayerChromium*); -template bool CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::occluded(const LayerChromium*, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const; -template IntRect CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::unoccludedContentRect(const LayerChromium*, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const; -template IntRect CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::unoccludedContributingSurfaceContentRect(const LayerChromium*, bool forReplica, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const; -template IntRect CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium>::layerClipRectInTarget(const LayerChromium*) const; - -template CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::CCOcclusionTrackerBase(IntRect rootTargetRect, bool recordMetricsForFrame); -template void CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::enterLayer(const CCLayerIteratorPosition<CCLayerImpl>&); -template void CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::leaveLayer(const CCLayerIteratorPosition<CCLayerImpl>&); -template void CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::enterRenderTarget(const CCLayerImpl* newTarget); -template void CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::finishedRenderTarget(const CCLayerImpl* finishedTarget); -template void CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::leaveToRenderTarget(const CCLayerImpl* newTarget); -template void CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::markOccludedBehindLayer(const CCLayerImpl*); -template bool CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::occluded(const CCLayerImpl*, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const; -template IntRect CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::unoccludedContentRect(const CCLayerImpl*, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const; -template IntRect CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::unoccludedContributingSurfaceContentRect(const CCLayerImpl*, bool forReplica, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface) const; -template IntRect CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>::layerClipRectInTarget(const CCLayerImpl*) const; - - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCOcclusionTracker.h b/Source/WebCore/platform/graphics/chromium/cc/CCOcclusionTracker.h deleted file mode 100644 index 7877319f0..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCOcclusionTracker.h +++ /dev/null @@ -1,124 +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 CCOcclusionTracker_h -#define CCOcclusionTracker_h - -#include "CCLayerIterator.h" -#include "FloatQuad.h" -#include "Region.h" - -namespace WebCore { -class CCOverdrawMetrics; -class CCLayerImpl; -class CCRenderSurface; -class LayerChromium; -class RenderSurfaceChromium; - -// This class is used to track occlusion of layers while traversing them in a front-to-back order. As each layer is visited, one of the -// methods in this class is called to notify it about the current target surface. -// Then, occlusion in the content space of the current layer may be queried, via methods such as occluded() and unoccludedContentRect(). -// If the current layer owns a RenderSurface, then occlusion on that RenderSurface may also be queried via surfaceOccluded() and surfaceUnoccludedContentRect(). -// Finally, once finished with the layer, occlusion behind the layer should be marked by calling markOccludedBehindLayer(). -template<typename LayerType, typename RenderSurfaceType> -class CCOcclusionTrackerBase { - WTF_MAKE_NONCOPYABLE(CCOcclusionTrackerBase); -public: - CCOcclusionTrackerBase(IntRect rootTargetRect, bool recordMetricsForFrame); - - // Called at the beginning of each step in the CCLayerIterator's front-to-back traversal. - void enterLayer(const CCLayerIteratorPosition<LayerType>&); - // Called at the end of each step in the CCLayerIterator's front-to-back traversal. - void leaveLayer(const CCLayerIteratorPosition<LayerType>&); - - // Returns true if the given rect in content space for the layer is fully occluded in either screen space or the layer's target surface. - bool occluded(const LayerType*, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface = 0) const; - // Gives an unoccluded sub-rect of |contentRect| in the content space of the layer. Used when considering occlusion for a layer that paints/draws something. - IntRect unoccludedContentRect(const LayerType*, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface = 0) const; - - // Gives an unoccluded sub-rect of |contentRect| in the content space of the renderTarget owned by the layer. - // Used when considering occlusion for a contributing surface that is rendering into another target. - IntRect unoccludedContributingSurfaceContentRect(const LayerType*, bool forReplica, const IntRect& contentRect, bool* hasOcclusionFromOutsideTargetSurface = 0) const; - - // Report operations for recording overdraw metrics. - CCOverdrawMetrics& overdrawMetrics() const { return *m_overdrawMetrics.get(); } - - // Gives the region of the screen that is not occluded by something opaque. - Region computeVisibleRegionInScreen() const { return subtract(Region(m_rootTargetRect), m_stack.last().occlusionInScreen); } - - void setMinimumTrackingSize(const IntSize& size) { m_minimumTrackingSize = size; } - - // The following is used for visualization purposes. - void setOccludingScreenSpaceRectsContainer(Vector<IntRect>* rects) { m_occludingScreenSpaceRects = rects; } - -protected: - struct StackObject { - StackObject() : target(0) { } - StackObject(const LayerType* target) : target(target) { } - const LayerType* target; - Region occlusionInScreen; - Region occlusionInTarget; - }; - - // The stack holds occluded regions for subtrees in the RenderSurface-Layer tree, so that when we leave a subtree we may - // apply a mask to it, but not to the parts outside the subtree. - // - The first time we see a new subtree under a target, we add that target to the top of the stack. This can happen as a layer representing itself, or as a target surface. - // - When we visit a target surface, we apply its mask to its subtree, which is at the top of the stack. - // - When we visit a layer representing itself, we add its occlusion to the current subtree, which is at the top of the stack. - // - When we visit a layer representing a contributing surface, the current target will never be the top of the stack since we just came from the contributing surface. - // We merge the occlusion at the top of the stack with the new current subtree. This new target is pushed onto the stack if not already there. - Vector<StackObject, 1> m_stack; - - // Allow tests to override this. - virtual IntRect layerClipRectInTarget(const LayerType*) const; - -private: - // Called when visiting a layer representing itself. If the target was not already current, then this indicates we have entered a new surface subtree. - void enterRenderTarget(const LayerType* newTarget); - - // Called when visiting a layer representing a target surface. This indicates we have visited all the layers within the surface, and we may - // perform any surface-wide operations. - void finishedRenderTarget(const LayerType* finishedTarget); - - // Called when visiting a layer representing a contributing surface. This indicates that we are leaving our current surface, and - // entering the new one. We then perform any operations required for merging results from the child subtree into its parent. - void leaveToRenderTarget(const LayerType* newTarget); - - // Add the layer's occlusion to the tracked state. - void markOccludedBehindLayer(const LayerType*); - - IntRect m_rootTargetRect; - OwnPtr<CCOverdrawMetrics> m_overdrawMetrics; - IntSize m_minimumTrackingSize; - - // This is used for visualizing the occlusion tracking process. - Vector<IntRect>* m_occludingScreenSpaceRects; -}; - -typedef CCOcclusionTrackerBase<LayerChromium, RenderSurfaceChromium> CCOcclusionTracker; -typedef CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface> CCOcclusionTrackerImpl; - -} -#endif // CCOcclusionTracker_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCOverdrawMetrics.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCOverdrawMetrics.cpp deleted file mode 100644 index dc90c5d4c..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCOverdrawMetrics.cpp +++ /dev/null @@ -1,210 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCOverdrawMetrics.h" - -#include "CCLayerTreeHost.h" -#include "CCLayerTreeHostImpl.h" -#include "CCMathUtil.h" -#include "FloatQuad.h" -#include "IntRect.h" -#include "TraceEvent.h" -#include <public/Platform.h> -#include <public/WebTransformationMatrix.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -CCOverdrawMetrics::CCOverdrawMetrics(bool recordMetricsForFrame) - : m_recordMetricsForFrame(recordMetricsForFrame) - , m_pixelsPainted(0) - , m_pixelsUploadedOpaque(0) - , m_pixelsUploadedTranslucent(0) - , m_tilesCulledForUpload(0) - , m_contentsTextureUseBytes(0) - , m_renderSurfaceTextureUseBytes(0) - , m_pixelsDrawnOpaque(0) - , m_pixelsDrawnTranslucent(0) - , m_pixelsCulledForDrawing(0) -{ -} - -static inline float wedgeProduct(const FloatPoint& p1, const FloatPoint& p2) -{ - return p1.x() * p2.y() - p1.y() * p2.x(); -} - -// Calculates area of an arbitrary convex polygon with up to 8 points. -static inline float polygonArea(const FloatPoint points[8], int numPoints) -{ - if (numPoints < 3) - return 0; - - float area = 0; - for (int i = 0; i < numPoints; ++i) - area += wedgeProduct(points[i], points[(i+1)%numPoints]); - return fabs(0.5f * area); -} - -// Takes a given quad, maps it by the given transformation, and gives the area of the resulting polygon. -static inline float areaOfMappedQuad(const WebTransformationMatrix& transform, const FloatQuad& quad) -{ - FloatPoint clippedQuad[8]; - int numVerticesInClippedQuad = 0; - CCMathUtil::mapClippedQuad(transform, quad, clippedQuad, numVerticesInClippedQuad); - return polygonArea(clippedQuad, numVerticesInClippedQuad); -} - -void CCOverdrawMetrics::didPaint(const IntRect& paintedRect) -{ - if (!m_recordMetricsForFrame) - return; - - m_pixelsPainted += static_cast<float>(paintedRect.width()) * paintedRect.height(); -} - -void CCOverdrawMetrics::didCullTileForUpload() -{ - if (m_recordMetricsForFrame) - ++m_tilesCulledForUpload; -} - -void CCOverdrawMetrics::didUpload(const WebTransformationMatrix& transformToTarget, const IntRect& uploadRect, const IntRect& opaqueRect) -{ - if (!m_recordMetricsForFrame) - return; - - float uploadArea = areaOfMappedQuad(transformToTarget, FloatQuad(uploadRect)); - float uploadOpaqueArea = areaOfMappedQuad(transformToTarget, FloatQuad(intersection(opaqueRect, uploadRect))); - - m_pixelsUploadedOpaque += uploadOpaqueArea; - m_pixelsUploadedTranslucent += uploadArea - uploadOpaqueArea; -} - -void CCOverdrawMetrics::didUseContentsTextureMemoryBytes(size_t contentsTextureUseBytes) -{ - if (!m_recordMetricsForFrame) - return; - - m_contentsTextureUseBytes += contentsTextureUseBytes; -} - -void CCOverdrawMetrics::didUseRenderSurfaceTextureMemoryBytes(size_t renderSurfaceUseBytes) -{ - if (!m_recordMetricsForFrame) - return; - - m_renderSurfaceTextureUseBytes += renderSurfaceUseBytes; -} - -void CCOverdrawMetrics::didCullForDrawing(const WebTransformationMatrix& transformToTarget, const IntRect& beforeCullRect, const IntRect& afterCullRect) -{ - if (!m_recordMetricsForFrame) - return; - - float beforeCullArea = areaOfMappedQuad(transformToTarget, FloatQuad(beforeCullRect)); - float afterCullArea = areaOfMappedQuad(transformToTarget, FloatQuad(afterCullRect)); - - m_pixelsCulledForDrawing += beforeCullArea - afterCullArea; -} - -void CCOverdrawMetrics::didDraw(const WebTransformationMatrix& transformToTarget, const IntRect& afterCullRect, const IntRect& opaqueRect) -{ - if (!m_recordMetricsForFrame) - return; - - float afterCullArea = areaOfMappedQuad(transformToTarget, FloatQuad(afterCullRect)); - float afterCullOpaqueArea = areaOfMappedQuad(transformToTarget, FloatQuad(intersection(opaqueRect, afterCullRect))); - - m_pixelsDrawnOpaque += afterCullOpaqueArea; - m_pixelsDrawnTranslucent += afterCullArea - afterCullOpaqueArea; -} - -void CCOverdrawMetrics::recordMetrics(const CCLayerTreeHost* layerTreeHost) const -{ - if (m_recordMetricsForFrame) - recordMetricsInternal<CCLayerTreeHost>(UpdateAndCommit, layerTreeHost); -} - -void CCOverdrawMetrics::recordMetrics(const CCLayerTreeHostImpl* layerTreeHost) const -{ - if (m_recordMetricsForFrame) - recordMetricsInternal<CCLayerTreeHostImpl>(DrawingToScreen, layerTreeHost); -} - -template<typename LayerTreeHostType> -void CCOverdrawMetrics::recordMetricsInternal(MetricsType metricsType, const LayerTreeHostType* layerTreeHost) const -{ - // This gives approximately 10x the percentage of pixels to fill the viewport once. - float normalization = 1000.f / (layerTreeHost->deviceViewportSize().width() * layerTreeHost->deviceViewportSize().height()); - // This gives approximately 100x the percentage of tiles to fill the viewport once, if all tiles were 256x256. - float tileNormalization = 10000.f / (layerTreeHost->deviceViewportSize().width() / 256.f * layerTreeHost->deviceViewportSize().height() / 256.f); - // This gives approximately 10x the percentage of bytes to fill the viewport once, assuming 4 bytes per pixel. - float byteNormalization = normalization / 4; - - switch (metricsType) { - case DrawingToScreen: - WebKit::Platform::current()->histogramCustomCounts("Renderer4.pixelCountOpaque_Draw", static_cast<int>(normalization * m_pixelsDrawnOpaque), 100, 1000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.pixelCountTranslucent_Draw", static_cast<int>(normalization * m_pixelsDrawnTranslucent), 100, 1000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.pixelCountCulled_Draw", static_cast<int>(normalization * m_pixelsCulledForDrawing), 100, 1000000, 50); - - { - TRACE_COUNTER_ID1("cc", "DrawPixelsCulled", layerTreeHost, m_pixelsCulledForDrawing); - TRACE_EVENT2("cc", "CCOverdrawMetrics", "PixelsDrawnOpaque", m_pixelsDrawnOpaque, "PixelsDrawnTranslucent", m_pixelsDrawnTranslucent); - } - break; - case UpdateAndCommit: - WebKit::Platform::current()->histogramCustomCounts("Renderer4.pixelCountPainted", static_cast<int>(normalization * m_pixelsPainted), 100, 1000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.pixelCountOpaque_Upload", static_cast<int>(normalization * m_pixelsUploadedOpaque), 100, 1000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.pixelCountTranslucent_Upload", static_cast<int>(normalization * m_pixelsUploadedTranslucent), 100, 1000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.tileCountCulled_Upload", static_cast<int>(tileNormalization * m_tilesCulledForUpload), 100, 10000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.renderSurfaceTextureBytes_ViewportScaled", static_cast<int>(byteNormalization * m_renderSurfaceTextureUseBytes), 10, 1000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.renderSurfaceTextureBytes_Unscaled", static_cast<int>(m_renderSurfaceTextureUseBytes / 1000), 1000, 100000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.contentsTextureBytes_ViewportScaled", static_cast<int>(byteNormalization * m_contentsTextureUseBytes), 10, 1000000, 50); - WebKit::Platform::current()->histogramCustomCounts("Renderer4.contentsTextureBytes_Unscaled", static_cast<int>(m_contentsTextureUseBytes / 1000), 1000, 100000000, 50); - - { - TRACE_COUNTER_ID1("cc", "UploadTilesCulled", layerTreeHost, m_tilesCulledForUpload); - TRACE_EVENT2("cc", "CCOverdrawMetrics", "PixelsUploadedOpaque", m_pixelsUploadedOpaque, "PixelsUploadedTranslucent", m_pixelsUploadedTranslucent); - } - { - // This must be in a different scope than the TRACE_EVENT2 above. - TRACE_EVENT1("cc", "CCOverdrawPaintMetrics", "PixelsPainted", m_pixelsPainted); - } - { - // This must be in a different scope than the TRACE_EVENTs above. - TRACE_EVENT2("cc", "CCOverdrawPaintMetrics", "ContentsTextureBytes", m_contentsTextureUseBytes, "RenderSurfaceTextureBytes", m_renderSurfaceTextureUseBytes); - } - break; - } -} - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCOverdrawMetrics.h b/Source/WebCore/platform/graphics/chromium/cc/CCOverdrawMetrics.h deleted file mode 100644 index f0dab0e93..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCOverdrawMetrics.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCOverdrawMetrics_h -#define CCOverdrawMetrics_h - -#include <wtf/PassOwnPtr.h> - -namespace WebKit { -class WebTransformationMatrix; -} - -namespace WebCore { -class IntRect; -class CCLayerTreeHost; -class CCLayerTreeHostImpl; - -// FIXME: compute overdraw metrics only occasionally, not every frame. -class CCOverdrawMetrics { -public: - static PassOwnPtr<CCOverdrawMetrics> create(bool recordMetricsForFrame) { return adoptPtr(new CCOverdrawMetrics(recordMetricsForFrame)); } - - // These methods are used for saving metrics during update/commit. - - // Record pixels painted by WebKit into the texture updater, but does not mean the pixels were rasterized in main memory. - void didPaint(const IntRect& paintedRect); - // Records that an invalid tile was culled and did not need to be painted/uploaded, and did not contribute to other tiles needing to be painted. - void didCullTileForUpload(); - // Records pixels that were uploaded to texture memory. - void didUpload(const WebKit::WebTransformationMatrix& transformToTarget, const IntRect& uploadRect, const IntRect& opaqueRect); - // Record contents texture(s) behind present using the given number of bytes. - void didUseContentsTextureMemoryBytes(size_t contentsTextureUseBytes); - // Record RenderSurface texture(s) being present using the given number of bytes. - void didUseRenderSurfaceTextureMemoryBytes(size_t renderSurfaceUseBytes); - - // These methods are used for saving metrics during draw. - - // Record pixels that were not drawn to screen. - void didCullForDrawing(const WebKit::WebTransformationMatrix& transformToTarget, const IntRect& beforeCullRect, const IntRect& afterCullRect); - // Record pixels that were drawn to screen. - void didDraw(const WebKit::WebTransformationMatrix& transformToTarget, const IntRect& afterCullRect, const IntRect& opaqueRect); - - void recordMetrics(const CCLayerTreeHost*) const; - void recordMetrics(const CCLayerTreeHostImpl*) const; - - // Accessors for tests. - float pixelsDrawnOpaque() const { return m_pixelsDrawnOpaque; } - float pixelsDrawnTranslucent() const { return m_pixelsDrawnTranslucent; } - float pixelsCulledForDrawing() const { return m_pixelsCulledForDrawing; } - float pixelsPainted() const { return m_pixelsPainted; } - float pixelsUploadedOpaque() const { return m_pixelsUploadedOpaque; } - float pixelsUploadedTranslucent() const { return m_pixelsUploadedTranslucent; } - int tilesCulledForUpload() const { return m_tilesCulledForUpload; } - -private: - enum MetricsType { - UpdateAndCommit, - DrawingToScreen - }; - - explicit CCOverdrawMetrics(bool recordMetricsForFrame); - - template<typename LayerTreeHostType> - void recordMetricsInternal(MetricsType, const LayerTreeHostType*) const; - - // When false this class is a giant no-op. - bool m_recordMetricsForFrame; - - // These values are used for saving metrics during update/commit. - - // Count of pixels that were painted due to invalidation. - float m_pixelsPainted; - // Count of pixels uploaded to textures and known to be opaque. - float m_pixelsUploadedOpaque; - // Count of pixels uploaded to textures and not known to be opaque. - float m_pixelsUploadedTranslucent; - // Count of tiles that were invalidated but not uploaded. - int m_tilesCulledForUpload; - // Count the number of bytes in contents textures. - unsigned long long m_contentsTextureUseBytes; - // Count the number of bytes in RenderSurface textures. - unsigned long long m_renderSurfaceTextureUseBytes; - - // These values are used for saving metrics during draw. - - // Count of pixels that are opaque (and thus occlude). Ideally this is no more than wiewport width x height. - float m_pixelsDrawnOpaque; - // Count of pixels that are possibly translucent, and cannot occlude. - float m_pixelsDrawnTranslucent; - // Count of pixels not drawn as they are occluded by somthing opaque. - float m_pixelsCulledForDrawing; -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPageScaleAnimation.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCPageScaleAnimation.cpp deleted file mode 100644 index 508851f9d..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPageScaleAnimation.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2007 Alp Toker <alp@atoker.com> - * 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. - */ - -#include "config.h" - -#include "CCPageScaleAnimation.h" - -#include "FloatRect.h" -#include "FloatSize.h" - -#include <math.h> - -namespace WebCore { - -PassOwnPtr<CCPageScaleAnimation> CCPageScaleAnimation::create(const IntSize& scrollStart, float pageScaleStart, const IntSize& windowSize, const IntSize& contentSize, double startTime) -{ - return adoptPtr(new CCPageScaleAnimation(scrollStart, pageScaleStart, windowSize, contentSize, startTime)); -} - - -CCPageScaleAnimation::CCPageScaleAnimation(const IntSize& scrollStart, float pageScaleStart, const IntSize& windowSize, const IntSize& contentSize, double startTime) - : m_scrollStart(scrollStart) - , m_pageScaleStart(pageScaleStart) - , m_windowSize(windowSize) - , m_contentSize(contentSize) - , m_anchorMode(false) - , m_scrollEnd(scrollStart) - , m_pageScaleEnd(pageScaleStart) - , m_startTime(startTime) - , m_duration(0) -{ -} - -void CCPageScaleAnimation::zoomTo(const IntSize& finalScroll, float finalPageScale, double duration) -{ - if (m_pageScaleStart != finalPageScale) { - // For uniform-looking zooming, infer the anchor (point that remains in - // place throughout the zoom) from the start and end rects. - FloatRect startRect(IntPoint(m_scrollStart), m_windowSize); - FloatRect endRect(IntPoint(finalScroll), m_windowSize); - endRect.scale(m_pageScaleStart / finalPageScale); - - // The anchor is the point which is at the same ratio of the sides of - // both startRect and endRect. For example, a zoom-in double-tap to a - // perfectly centered rect will have anchor ratios (0.5, 0.5), while one - // to a rect touching the bottom-right of the screen will have anchor - // ratios (1.0, 1.0). In other words, it obeys the equations: - // anchorX = start_width * ratioX + start_x - // anchorX = end_width * ratioX + end_x - // anchorY = start_height * ratioY + start_y - // anchorY = end_height * ratioY + end_y - // where both anchor{x,y} and ratio{x,y} begin as unknowns. Solving - // for the ratios, we get the following formulas: - float ratioX = (startRect.x() - endRect.x()) / (endRect.width() - startRect.width()); - float ratioY = (startRect.y() - endRect.y()) / (endRect.height() - startRect.height()); - - IntSize anchor(m_windowSize.width() * ratioX, m_windowSize.height() * ratioY); - zoomWithAnchor(anchor, finalPageScale, duration); - } else { - // If this is a pure translation, then there exists no anchor. Linearly - // interpolate the scroll offset instead. - m_scrollEnd = finalScroll; - m_pageScaleEnd = finalPageScale; - m_duration = duration; - m_anchorMode = false; - } -} - -void CCPageScaleAnimation::zoomWithAnchor(const IntSize& anchor, float finalPageScale, double duration) -{ - m_scrollEnd = m_scrollStart + anchor; - m_scrollEnd.scale(finalPageScale / m_pageScaleStart); - m_scrollEnd -= anchor; - - m_scrollEnd.clampNegativeToZero(); - FloatSize scaledContentSize(m_contentSize); - scaledContentSize.scale(finalPageScale / m_pageScaleStart); - IntSize maxScrollPosition = roundedIntSize(scaledContentSize - m_windowSize); - m_scrollEnd = m_scrollEnd.shrunkTo(maxScrollPosition); - - m_anchor = anchor; - m_pageScaleEnd = finalPageScale; - m_duration = duration; - m_anchorMode = true; -} - -IntSize CCPageScaleAnimation::scrollOffsetAtTime(double time) const -{ - return scrollOffsetAtRatio(progressRatioForTime(time)); -} - -float CCPageScaleAnimation::pageScaleAtTime(double time) const -{ - return pageScaleAtRatio(progressRatioForTime(time)); -} - -bool CCPageScaleAnimation::isAnimationCompleteAtTime(double time) const -{ - return time >= endTime(); -} - -float CCPageScaleAnimation::progressRatioForTime(double time) const -{ - if (isAnimationCompleteAtTime(time)) - return 1; - - return (time - m_startTime) / m_duration; -} - -IntSize CCPageScaleAnimation::scrollOffsetAtRatio(float ratio) const -{ - if (ratio <= 0) - return m_scrollStart; - if (ratio >= 1) - return m_scrollEnd; - - float currentPageScale = pageScaleAtRatio(ratio); - IntSize currentScrollOffset; - if (m_anchorMode) { - // Keep the anchor stable on the screen at the current scale. - IntSize documentAnchor = m_scrollStart + m_anchor; - documentAnchor.scale(currentPageScale / m_pageScaleStart); - currentScrollOffset = documentAnchor - m_anchor; - } else { - // First move both scroll offsets to the current coordinate space. - FloatSize scaledStartScroll(m_scrollStart); - scaledStartScroll.scale(currentPageScale / m_pageScaleStart); - FloatSize scaledEndScroll(m_scrollEnd); - scaledEndScroll.scale(currentPageScale / m_pageScaleEnd); - - // Linearly interpolate between them. - FloatSize delta = scaledEndScroll - scaledStartScroll; - delta.scale(ratio); - currentScrollOffset = roundedIntSize(scaledStartScroll + delta); - } - - return currentScrollOffset; -} - -float CCPageScaleAnimation::pageScaleAtRatio(float ratio) const -{ - if (ratio <= 0) - return m_pageScaleStart; - if (ratio >= 1) - return m_pageScaleEnd; - - // Linearly interpolate the magnitude in log scale. - // Log scale is needed to maintain the appearance of uniform zoom. For - // example, if we zoom from 0.5 to 4.0 in 3 seconds, then we should - // be zooming by 2x every second. - float diff = m_pageScaleEnd / m_pageScaleStart; - float logDiff = log(diff); - logDiff *= ratio; - diff = exp(logDiff); - return m_pageScaleStart * diff; -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPageScaleAnimation.h b/Source/WebCore/platform/graphics/chromium/cc/CCPageScaleAnimation.h deleted file mode 100644 index d9acb4911..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPageScaleAnimation.h +++ /dev/null @@ -1,94 +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 CCPageScaleAnimation_h -#define CCPageScaleAnimation_h - -#include "IntSize.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -// A small helper class that does the math for zoom animations, primarily for -// double-tap zoom. Initialize it with starting and ending scroll/page scale -// positions and an animation length time, then call ...AtTime() at every frame -// to obtain the current interpolated position. -class CCPageScaleAnimation { -public: - // Construct with the starting page scale and scroll offset (which is in - // pageScaleStart space). The window size is the user-viewable area - // in pixels. - static PassOwnPtr<CCPageScaleAnimation> create(const IntSize& scrollStart, float pageScaleStart, const IntSize& windowSize, const IntSize& contentSize, double startTime); - - // The following methods initialize the animation. Call one of them - // immediately after construction to set the final scroll and page scale. - - // Zoom while explicitly specifying the top-left scroll position. The - // scroll offset is in finalPageScale coordinates. - void zoomTo(const IntSize& finalScroll, float finalPageScale, double duration); - - // Zoom based on a specified onscreen anchor, which will remain at the same - // position on the screen throughout the animation. The anchor is in local - // space relative to scrollStart. - void zoomWithAnchor(const IntSize& anchor, float finalPageScale, double duration); - - // Call these functions while the animation is in progress to output the - // current state. - IntSize scrollOffsetAtTime(double time) const; - float pageScaleAtTime(double time) const; - bool isAnimationCompleteAtTime(double time) const; - - // The following methods return state which is invariant throughout the - // course of the animation. - double startTime() const { return m_startTime; } - double duration() const { return m_duration; } - double endTime() const { return m_startTime + m_duration; } - const IntSize& finalScrollOffset() const { return m_scrollEnd; } - float finalPageScale() const { return m_pageScaleEnd; } - -protected: - CCPageScaleAnimation(const IntSize& scrollStart, float pageScaleStart, const IntSize& windowSize, const IntSize& contentSize, double startTime); - -private: - float progressRatioForTime(double time) const; - IntSize scrollOffsetAtRatio(float ratio) const; - float pageScaleAtRatio(float ratio) const; - - IntSize m_scrollStart; - float m_pageScaleStart; - IntSize m_windowSize; - IntSize m_contentSize; - - bool m_anchorMode; - IntSize m_anchor; - IntSize m_scrollEnd; - float m_pageScaleEnd; - - double m_startTime; - double m_duration; -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTexture.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTexture.cpp deleted file mode 100644 index d98aba615..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTexture.cpp +++ /dev/null @@ -1,171 +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 "CCPrioritizedTexture.h" - -#include "CCPrioritizedTextureManager.h" -#include "CCPriorityCalculator.h" -#include "CCProxy.h" -#include <algorithm> - -using namespace std; - -namespace WebCore { - -CCPrioritizedTexture::CCPrioritizedTexture(CCPrioritizedTextureManager* manager, IntSize size, GC3Denum format) - : m_size(size) - , m_format(format) - , m_bytes(0) - , m_priority(CCPriorityCalculator::lowestPriority()) - , m_isAbovePriorityCutoff(false) - , m_isSelfManaged(false) - , m_backing(0) - , m_manager(0) -{ - // m_manager is set in registerTexture() so validity can be checked. - ASSERT(format || size.isEmpty()); - if (format) - m_bytes = CCTexture::memorySizeBytes(size, format); - if (manager) - manager->registerTexture(this); -} - -CCPrioritizedTexture::~CCPrioritizedTexture() -{ - if (m_manager) - m_manager->unregisterTexture(this); -} - -void CCPrioritizedTexture::setTextureManager(CCPrioritizedTextureManager* manager) -{ - if (m_manager == manager) - return; - if (m_manager) - m_manager->unregisterTexture(this); - if (manager) - manager->registerTexture(this); -} - -void CCPrioritizedTexture::setDimensions(IntSize size, GC3Denum format) -{ - if (m_format != format || m_size != size) { - m_isAbovePriorityCutoff = false; - m_format = format; - m_size = size; - m_bytes = CCTexture::memorySizeBytes(size, format); - ASSERT(m_manager || !m_backing); - if (m_manager) - m_manager->returnBackingTexture(this); - } -} - -bool CCPrioritizedTexture::requestLate() -{ - if (!m_manager) - return false; - return m_manager->requestLate(this); -} - -void CCPrioritizedTexture::acquireBackingTexture(CCResourceProvider* resourceProvider) -{ - ASSERT(m_isAbovePriorityCutoff); - if (m_isAbovePriorityCutoff) - m_manager->acquireBackingTextureIfNeeded(this, resourceProvider); -} - -CCResourceProvider::ResourceId CCPrioritizedTexture::resourceId() const -{ - if (m_backing) - return m_backing->id(); - return 0; -} - -void CCPrioritizedTexture::upload(CCResourceProvider* resourceProvider, - const uint8_t* image, const IntRect& imageRect, - const IntRect& sourceRect, const IntSize& destOffset) -{ - ASSERT(m_isAbovePriorityCutoff); - if (m_isAbovePriorityCutoff) - acquireBackingTexture(resourceProvider); - ASSERT(m_backing); - resourceProvider->upload(resourceId(), image, imageRect, sourceRect, destOffset); -} - -void CCPrioritizedTexture::link(Backing* backing) -{ - ASSERT(backing); - ASSERT(!backing->m_owner); - ASSERT(!m_backing); - - m_backing = backing; - m_backing->m_owner = this; -} - -void CCPrioritizedTexture::unlink() -{ - ASSERT(m_backing); - ASSERT(m_backing->m_owner == this); - - m_backing->m_owner = 0; - m_backing = 0; -} - -void CCPrioritizedTexture::setToSelfManagedMemoryPlaceholder(size_t bytes) -{ - setDimensions(IntSize(), GraphicsContext3D::RGBA); - setIsSelfManaged(true); - m_bytes = bytes; -} - -CCPrioritizedTexture::Backing::Backing(unsigned id, IntSize size, GC3Denum format) - : CCTexture(id, size, format) - , m_owner(0) - , m_priorityAtLastPriorityUpdate(CCPriorityCalculator::lowestPriority()) - , m_ownerExistedAtLastPriorityUpdate(false) - , m_wasAbovePriorityCutoffAtLastPriorityUpdate(false) -{ -} - -CCPrioritizedTexture::Backing::~Backing() -{ - ASSERT(!m_owner); -} - -void CCPrioritizedTexture::Backing::updatePriority() -{ - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - if (m_owner) { - m_ownerExistedAtLastPriorityUpdate = true; - m_priorityAtLastPriorityUpdate = m_owner->requestPriority(); - m_wasAbovePriorityCutoffAtLastPriorityUpdate = m_owner->isAbovePriorityCutoff(); - } else { - m_ownerExistedAtLastPriorityUpdate = false; - m_priorityAtLastPriorityUpdate = CCPriorityCalculator::lowestPriority(); - m_wasAbovePriorityCutoffAtLastPriorityUpdate = false; - } -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTexture.h b/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTexture.h deleted file mode 100644 index 526451899..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTexture.h +++ /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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCPrioritizedTexture_h -#define CCPrioritizedTexture_h - -#include "CCPriorityCalculator.h" -#include "CCResourceProvider.h" -#include "CCTexture.h" -#include "GraphicsContext3D.h" -#include "IntRect.h" -#include "IntSize.h" - -namespace WebCore { - -class CCPrioritizedTextureManager; - -class CCPrioritizedTexture { - WTF_MAKE_NONCOPYABLE(CCPrioritizedTexture); -public: - static PassOwnPtr<CCPrioritizedTexture> create(CCPrioritizedTextureManager* manager, IntSize size, GC3Denum format) - { - return adoptPtr(new CCPrioritizedTexture(manager, size, format)); - } - static PassOwnPtr<CCPrioritizedTexture> create(CCPrioritizedTextureManager* manager) - { - return adoptPtr(new CCPrioritizedTexture(manager, IntSize(), 0)); - } - ~CCPrioritizedTexture(); - - // Texture properties. Changing these causes the backing texture to be lost. - // Setting these to the same value is a no-op. - void setTextureManager(CCPrioritizedTextureManager*); - CCPrioritizedTextureManager* textureManager() { return m_manager; } - void setDimensions(IntSize, GC3Denum format); - GC3Denum format() const { return m_format; } - IntSize size() const { return m_size; } - size_t bytes() const { return m_bytes; } - - // Set priority for the requested texture. - void setRequestPriority(int priority) { m_priority = priority; } - int requestPriority() const { return m_priority; } - - // After CCPrioritizedTexture::prioritizeTextures() is called, this returns - // if the the request succeeded and this texture can be acquired for use. - bool canAcquireBackingTexture() const { return m_isAbovePriorityCutoff; } - - // This returns whether we still have a backing texture. This can continue - // to be true even after canAcquireBackingTexture() becomes false. In this - // case the texture can be used but shouldn't be updated since it will get - // taken away "soon". - bool haveBackingTexture() const { return !!backing(); } - - // If canAcquireBackingTexture() is true acquireBackingTexture() will acquire - // a backing texture for use. Call this whenever the texture is actually needed. - void acquireBackingTexture(CCResourceProvider*); - - // FIXME: Request late is really a hack for when we are totally out of memory - // (all textures are visible) but we can still squeeze into the limit - // by not painting occluded textures. In this case the manager - // refuses all visible textures and requestLate() will enable - // canAcquireBackingTexture() on a call-order basis. We might want to - // just remove this in the future (carefully) and just make sure we don't - // regress OOMs situations. - bool requestLate(); - - // Uploads pixels into the backing resource. This functions will aquire the backing if needed. - void upload(CCResourceProvider*, const uint8_t* image, const IntRect& imageRect, const IntRect& sourceRect, const IntSize& destOffset); - - CCResourceProvider::ResourceId resourceId() const; - - // Self-managed textures are accounted for when prioritizing other textures, - // but they are not allocated/recycled/deleted, so this needs to be done - // externally. canAcquireBackingTexture() indicates if the texture would have - // been allowed given its priority. - void setIsSelfManaged(bool isSelfManaged) { m_isSelfManaged = isSelfManaged; } - bool isSelfManaged() { return m_isSelfManaged; } - void setToSelfManagedMemoryPlaceholder(size_t bytes); - -private: - friend class CCPrioritizedTextureManager; - friend class CCPrioritizedTextureTest; - - class Backing : public CCTexture { - WTF_MAKE_NONCOPYABLE(Backing); - public: - Backing(unsigned id, IntSize, GC3Denum format); - ~Backing(); - void updatePriority(); - - CCPrioritizedTexture* owner() { return m_owner; } - bool hadOwnerAtLastPriorityUpdate() const { return m_ownerExistedAtLastPriorityUpdate; } - bool requestPriorityAtLastPriorityUpdate() const { return m_priorityAtLastPriorityUpdate; } - bool wasAbovePriorityCutoffAtLastPriorityUpdate() const { return m_wasAbovePriorityCutoffAtLastPriorityUpdate; } - - private: - friend class CCPrioritizedTexture; - CCPrioritizedTexture* m_owner; - int m_priorityAtLastPriorityUpdate; - bool m_ownerExistedAtLastPriorityUpdate; - bool m_wasAbovePriorityCutoffAtLastPriorityUpdate; - }; - - CCPrioritizedTexture(CCPrioritizedTextureManager*, IntSize, GC3Denum format); - - bool isAbovePriorityCutoff() { return m_isAbovePriorityCutoff; } - void setAbovePriorityCutoff(bool isAbovePriorityCutoff) { m_isAbovePriorityCutoff = isAbovePriorityCutoff; } - void setManagerInternal(CCPrioritizedTextureManager* manager) { m_manager = manager; } - - Backing* backing() const { return m_backing; } - void link(Backing*); - void unlink(); - - IntSize m_size; - GC3Denum m_format; - size_t m_bytes; - - int m_priority; - bool m_isAbovePriorityCutoff; - bool m_isSelfManaged; - - Backing* m_backing; - CCPrioritizedTextureManager* m_manager; -}; - -} // WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTextureManager.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTextureManager.cpp deleted file mode 100644 index ca65ba9e1..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTextureManager.cpp +++ /dev/null @@ -1,431 +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 "CCPrioritizedTextureManager.h" - -#include "CCPrioritizedTexture.h" -#include "CCPriorityCalculator.h" -#include "CCProxy.h" -#include "TraceEvent.h" -#include <algorithm> - -using namespace std; - -namespace WebCore { - -CCPrioritizedTextureManager::CCPrioritizedTextureManager(size_t maxMemoryLimitBytes, int, int pool) - : m_maxMemoryLimitBytes(maxMemoryLimitBytes) - , m_memoryUseBytes(0) - , m_memoryAboveCutoffBytes(0) - , m_memoryAvailableBytes(0) - , m_pool(pool) - , m_needsUpdateBackingsPrioritites(false) -{ -} - -CCPrioritizedTextureManager::~CCPrioritizedTextureManager() -{ - while (m_textures.size() > 0) - unregisterTexture(*m_textures.begin()); - - deleteEvictedBackings(); - - // Each remaining backing is a leaked opengl texture. There should be none. - ASSERT(m_backings.isEmpty()); -} - -void CCPrioritizedTextureManager::prioritizeTextures() -{ - TRACE_EVENT0("cc", "CCPrioritizedTextureManager::prioritizeTextures"); - ASSERT(CCProxy::isMainThread()); - - // Sorting textures in this function could be replaced by a slightly - // modified O(n) quick-select to partition textures rather than - // sort them (if performance of the sort becomes an issue). - - TextureVector& sortedTextures = m_tempTextureVector; - sortedTextures.clear(); - - // Copy all textures into a vector and sort them. - for (TextureSet::iterator it = m_textures.begin(); it != m_textures.end(); ++it) - sortedTextures.append(*it); - std::sort(sortedTextures.begin(), sortedTextures.end(), compareTextures); - - m_memoryAvailableBytes = m_maxMemoryLimitBytes; - m_priorityCutoff = CCPriorityCalculator::lowestPriority(); - size_t memoryBytes = 0; - for (TextureVector::iterator it = sortedTextures.begin(); it != sortedTextures.end(); ++it) { - if ((*it)->requestPriority() == CCPriorityCalculator::lowestPriority()) - break; - - if ((*it)->isSelfManaged()) { - // Account for self-managed memory immediately by reducing the memory - // available (since it never gets acquired). - size_t newMemoryBytes = memoryBytes + (*it)->bytes(); - if (newMemoryBytes > m_memoryAvailableBytes) { - m_priorityCutoff = (*it)->requestPriority(); - m_memoryAvailableBytes = memoryBytes; - break; - } - m_memoryAvailableBytes -= (*it)->bytes(); - } else { - size_t newMemoryBytes = memoryBytes + (*it)->bytes(); - if (newMemoryBytes > m_memoryAvailableBytes) { - m_priorityCutoff = (*it)->requestPriority(); - break; - } - memoryBytes = newMemoryBytes; - } - } - - // Only allow textures if they are higher than the cutoff. All textures - // of the same priority are accepted or rejected together, rather than - // being partially allowed randomly. - m_memoryAboveCutoffBytes = 0; - for (TextureVector::iterator it = sortedTextures.begin(); it != sortedTextures.end(); ++it) { - bool isAbovePriorityCutoff = CCPriorityCalculator::priorityIsHigher((*it)->requestPriority(), m_priorityCutoff); - (*it)->setAbovePriorityCutoff(isAbovePriorityCutoff); - if (isAbovePriorityCutoff && !(*it)->isSelfManaged()) - m_memoryAboveCutoffBytes += (*it)->bytes(); - } - sortedTextures.clear(); - - m_needsUpdateBackingsPrioritites = true; - - ASSERT(m_memoryAboveCutoffBytes <= m_memoryAvailableBytes); - ASSERT(memoryAboveCutoffBytes() <= maxMemoryLimitBytes()); -} - -void CCPrioritizedTextureManager::updateBackingsPriorities() -{ - TRACE_EVENT0("cc", "CCPrioritizedTextureManager::updateBackingsPriorities"); - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - - if (!m_needsUpdateBackingsPrioritites) - return; - -#if !ASSERT_DISABLED - assertInvariants(); -#endif - - // Update backings' priorities and put backings in eviction/recycling order. - BackingVector& sortedBackings = m_tempBackingVector; - sortedBackings.clear(); - for (BackingSet::iterator it = m_backings.begin(); it != m_backings.end(); ++it) { - (*it)->updatePriority(); - sortedBackings.append(*it); - } - std::sort(sortedBackings.begin(), sortedBackings.end(), compareBackings); - - for (BackingVector::iterator it = sortedBackings.begin(); it != sortedBackings.end(); ++it) { - m_backings.remove(*it); - m_backings.add(*it); - } - sortedBackings.clear(); - m_needsUpdateBackingsPrioritites = false; - -#if !ASSERT_DISABLED - assertInvariants(); -#endif -} - -void CCPrioritizedTextureManager::clearPriorities() -{ - ASSERT(CCProxy::isMainThread()); - for (TextureSet::iterator it = m_textures.begin(); it != m_textures.end(); ++it) { - // FIXME: We should remove this and just set all priorities to - // CCPriorityCalculator::lowestPriority() once we have priorities - // for all textures (we can't currently calculate distances for - // off-screen textures). - (*it)->setRequestPriority(CCPriorityCalculator::lingeringPriority((*it)->requestPriority())); - } -} - -bool CCPrioritizedTextureManager::requestLate(CCPrioritizedTexture* texture) -{ - ASSERT(CCProxy::isMainThread()); - - // This is already above cutoff, so don't double count it's memory below. - if (texture->isAbovePriorityCutoff()) - return true; - - if (CCPriorityCalculator::priorityIsLower(texture->requestPriority(), m_priorityCutoff)) - return false; - - size_t newMemoryBytes = m_memoryAboveCutoffBytes + texture->bytes(); - if (newMemoryBytes > m_memoryAvailableBytes) - return false; - - m_memoryAboveCutoffBytes = newMemoryBytes; - texture->setAbovePriorityCutoff(true); - m_needsUpdateBackingsPrioritites = true; - return true; -} - -void CCPrioritizedTextureManager::acquireBackingTextureIfNeeded(CCPrioritizedTexture* texture, CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - ASSERT(!texture->isSelfManaged()); - ASSERT(texture->isAbovePriorityCutoff()); - if (texture->backing() || !texture->isAbovePriorityCutoff()) - return; - - // Make sure that the backings list is up to date and sorted before traversing it. - updateBackingsPriorities(); - - // Find a backing below, by either recycling or allocating. - CCPrioritizedTexture::Backing* backing = 0; - - // First try to recycle - for (BackingSet::iterator it = m_backings.begin(); it != m_backings.end(); ++it) { - if ((*it)->hadOwnerAtLastPriorityUpdate() && (*it)->wasAbovePriorityCutoffAtLastPriorityUpdate()) - break; - if ((*it)->size() == texture->size() && (*it)->format() == texture->format()) { - backing = (*it); - break; - } - } - - // Otherwise reduce memory and just allocate a new backing texures. - if (!backing) { - evictBackingsToReduceMemory(m_memoryAvailableBytes - texture->bytes(), RespectManagerPriorityCutoff, resourceProvider); - backing = createBacking(texture->size(), texture->format(), resourceProvider); - } - - // Move the used backing texture to the end of the eviction list. - if (backing->owner()) - backing->owner()->unlink(); - texture->link(backing); - m_backings.remove(backing); - m_backings.add(backing); - - // Update the backing's priority from its new owner. - backing->updatePriority(); -} - -void CCPrioritizedTextureManager::evictBackingsToReduceMemory(size_t limitBytes, EvictionPriorityPolicy evictionPolicy, CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - if (memoryUseBytes() <= limitBytes) - return; - - // Destroy backings until we are below the limit, - // or until all backings remaining are above the cutoff. - while (memoryUseBytes() > limitBytes && m_backings.size() > 0) { - CCPrioritizedTexture::Backing* backing = *m_backings.begin(); - if (evictionPolicy == RespectManagerPriorityCutoff) - if (backing->hadOwnerAtLastPriorityUpdate() && backing->wasAbovePriorityCutoffAtLastPriorityUpdate()) - break; - evictBackingResource(backing, resourceProvider); - } -} - -void CCPrioritizedTextureManager::reduceMemory(CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - - // Make sure that the backings list is up to date and sorted before traversing it. - updateBackingsPriorities(); - - evictBackingsToReduceMemory(m_memoryAvailableBytes, RespectManagerPriorityCutoff, resourceProvider); - ASSERT(memoryUseBytes() <= maxMemoryLimitBytes()); - - // We currently collect backings from deleted textures for later recycling. - // However, if we do that forever we will always use the max limit even if - // we really need very little memory. This should probably be solved by reducing the - // limit externally, but until then this just does some "clean up" of unused - // backing textures (any more than 10%). - size_t wastedMemory = 0; - for (BackingSet::iterator it = m_backings.begin(); it != m_backings.end(); ++it) { - if ((*it)->owner()) - break; - wastedMemory += (*it)->bytes(); - } - size_t tenPercentOfMemory = m_memoryAvailableBytes / 10; - if (wastedMemory > tenPercentOfMemory) - evictBackingsToReduceMemory(memoryUseBytes() - (wastedMemory - tenPercentOfMemory), RespectManagerPriorityCutoff, resourceProvider); - - deleteEvictedBackings(); -} - -void CCPrioritizedTextureManager::clearAllMemory(CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - ASSERT(resourceProvider); - evictBackingsToReduceMemory(0, DoNotRespectManagerPriorityCutoff, resourceProvider); - deleteEvictedBackings(); -} - -void CCPrioritizedTextureManager::reduceMemoryOnImplThread(size_t limitBytes, CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - ASSERT(resourceProvider); - - evictBackingsToReduceMemory(limitBytes, DoNotRespectManagerPriorityCutoff, resourceProvider); - - // Deleting just some (not all) resources is not supported yet because we do not clear - // only the deleted resources from the texture upload queues (rather, we clear all uploads). - // Make sure that if we evict all resources. - ASSERT(m_backings.isEmpty()); -} - -void CCPrioritizedTextureManager::getEvictedBackings(BackingVector& evictedBackings) -{ - ASSERT(CCProxy::isImplThread()); - evictedBackings.clear(); - evictedBackings.append(m_evictedBackings); -} - -void CCPrioritizedTextureManager::unlinkEvictedBackings(const BackingVector& evictedBackings) -{ - ASSERT(CCProxy::isMainThread()); - for (BackingVector::const_iterator it = evictedBackings.begin(); it != evictedBackings.end(); ++it) { - CCPrioritizedTexture::Backing* backing = (*it); - if (backing->owner()) - backing->owner()->unlink(); - } -} - -bool CCPrioritizedTextureManager::deleteEvictedBackings() -{ - ASSERT(CCProxy::isMainThread() || (CCProxy::isImplThread() && CCProxy::isMainThreadBlocked())); - bool linkedEvictedBackingsExisted = false; - for (BackingVector::const_iterator it = m_evictedBackings.begin(); it != m_evictedBackings.end(); ++it) { - CCPrioritizedTexture::Backing* backing = (*it); - if (backing->owner()) { - linkedEvictedBackingsExisted = true; - backing->owner()->unlink(); - } - delete backing; - } - m_evictedBackings.clear(); - return linkedEvictedBackingsExisted; -} - -void CCPrioritizedTextureManager::registerTexture(CCPrioritizedTexture* texture) -{ - ASSERT(CCProxy::isMainThread()); - ASSERT(texture); - ASSERT(!texture->textureManager()); - ASSERT(!texture->backing()); - ASSERT(m_textures.find(texture) == m_textures.end()); - - texture->setManagerInternal(this); - m_textures.add(texture); - -} - -void CCPrioritizedTextureManager::unregisterTexture(CCPrioritizedTexture* texture) -{ - ASSERT(CCProxy::isMainThread() || (CCProxy::isImplThread() && CCProxy::isMainThreadBlocked())); - ASSERT(texture); - ASSERT(m_textures.find(texture) != m_textures.end()); - - returnBackingTexture(texture); - texture->setManagerInternal(0); - m_textures.remove(texture); - texture->setAbovePriorityCutoff(false); -} - -void CCPrioritizedTextureManager::returnBackingTexture(CCPrioritizedTexture* texture) -{ - ASSERT(CCProxy::isMainThread() || (CCProxy::isImplThread() && CCProxy::isMainThreadBlocked())); - if (texture->backing()) { - texture->unlink(); - m_needsUpdateBackingsPrioritites = true; - } -} - -CCPrioritizedTexture::Backing* CCPrioritizedTextureManager::createBacking(IntSize size, GC3Denum format, CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - ASSERT(resourceProvider); - CCResourceProvider::ResourceId resourceId = resourceProvider->createResource(m_pool, size, format, CCResourceProvider::TextureUsageAny); - CCPrioritizedTexture::Backing* backing = new CCPrioritizedTexture::Backing(resourceId, size, format); - m_memoryUseBytes += backing->bytes(); - // Put backing texture at the front for eviction, since it isn't in use yet. - m_backings.insertBefore(m_backings.begin(), backing); - return backing; -} - -void CCPrioritizedTextureManager::evictBackingResource(CCPrioritizedTexture::Backing* backing, CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - ASSERT(backing); - ASSERT(resourceProvider); - ASSERT(m_backings.find(backing) != m_backings.end()); - - resourceProvider->deleteResource(backing->id()); - backing->setId(0); - m_memoryUseBytes -= backing->bytes(); - m_backings.remove(backing); - m_evictedBackings.append(backing); -} - -#if !ASSERT_DISABLED -void CCPrioritizedTextureManager::assertInvariants() -{ - ASSERT(CCProxy::isImplThread() && CCProxy::isMainThreadBlocked()); - - // If we hit any of these asserts, there is a bug in this class. To see - // where the bug is, call this function at the beginning and end of - // every public function. - - // Backings/textures must be doubly-linked and only to other backings/textures in this manager. - for (BackingSet::iterator it = m_backings.begin(); it != m_backings.end(); ++it) { - if ((*it)->owner()) { - ASSERT(m_textures.find((*it)->owner()) != m_textures.end()); - ASSERT((*it)->owner()->backing() == (*it)); - } - } - for (TextureSet::iterator it = m_textures.begin(); it != m_textures.end(); ++it) { - if ((*it)->backing()) { - ASSERT(m_backings.find((*it)->backing()) != m_backings.end()); - ASSERT((*it)->backing()->owner() == (*it)); - } - } - - // At all times, backings that can be evicted must always come before - // backings that can't be evicted in the backing texture list (otherwise - // reduceMemory will not find all textures available for eviction/recycling). - bool reachedOwned = false; - bool reachedAboveCutoff = false; - for (BackingSet::iterator it = m_backings.begin(); it != m_backings.end(); ++it) { - if ((*it)->hadOwnerAtLastPriorityUpdate()) - reachedOwned = true; - if ((*it)->wasAbovePriorityCutoffAtLastPriorityUpdate()) - reachedAboveCutoff = true; - if (reachedOwned) - ASSERT((*it)->hadOwnerAtLastPriorityUpdate()); - if (reachedAboveCutoff) { - ASSERT((*it)->hadOwnerAtLastPriorityUpdate() && (*it)->wasAbovePriorityCutoffAtLastPriorityUpdate()); - ASSERT(reachedOwned); - } - } -} -#endif - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTextureManager.h b/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTextureManager.h deleted file mode 100644 index bbc0c7d10..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPrioritizedTextureManager.h +++ /dev/null @@ -1,165 +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 CCPrioritizedTextureManager_h -#define CCPrioritizedTextureManager_h - -#include "CCPrioritizedTexture.h" -#include "CCPriorityCalculator.h" -#include "CCTexture.h" -#include "GraphicsContext3D.h" -#include "IntRect.h" -#include "IntSize.h" -#include <wtf/HashSet.h> -#include <wtf/ListHashSet.h> -#include <wtf/Vector.h> - -namespace WebCore { - -class CCPrioritizedTexture; -class CCPriorityCalculator; - -class CCPrioritizedTextureManager { - WTF_MAKE_NONCOPYABLE(CCPrioritizedTextureManager); -public: - static PassOwnPtr<CCPrioritizedTextureManager> create(size_t maxMemoryLimitBytes, int maxTextureSize, int pool) - { - return adoptPtr(new CCPrioritizedTextureManager(maxMemoryLimitBytes, maxTextureSize, pool)); - } - PassOwnPtr<CCPrioritizedTexture> createTexture(IntSize size, GC3Denum format) - { - return adoptPtr(new CCPrioritizedTexture(this, size, format)); - } - ~CCPrioritizedTextureManager(); - - typedef Vector<CCPrioritizedTexture::Backing*> BackingVector; - - // FIXME (http://crbug.com/137094): This 64MB default is a straggler from the - // old texture manager and is just to give us a default memory allocation before - // we get a callback from the GPU memory manager. We should probaby either: - // - wait for the callback before rendering anything instead - // - push this into the GPU memory manager somehow. - static size_t defaultMemoryAllocationLimit() { return 64 * 1024 * 1024; } - - // memoryUseBytes() describes the number of bytes used by existing allocated textures. - // memoryAboveCutoffBytes() describes the number of bytes that would be used if all - // textures that are above the cutoff were allocated. - // memoryUseBytes() <= memoryAboveCutoffBytes() should always be true. - size_t memoryUseBytes() const { return m_memoryUseBytes; } - size_t memoryAboveCutoffBytes() const { return m_memoryAboveCutoffBytes; } - size_t memoryForSelfManagedTextures() const { return m_maxMemoryLimitBytes - m_memoryAvailableBytes; } - - void setMaxMemoryLimitBytes(size_t bytes) { m_maxMemoryLimitBytes = bytes; } - size_t maxMemoryLimitBytes() const { return m_maxMemoryLimitBytes; } - - void prioritizeTextures(); - void clearPriorities(); - - void reduceMemoryOnImplThread(size_t limitBytes, CCResourceProvider*); - void getEvictedBackings(BackingVector& evictedBackings); - void unlinkEvictedBackings(const BackingVector& evictedBackings); - // Deletes all evicted backings, unlinking them from their owning textures if needed. - // Returns true if this function to unlinked any backings from their owning texture while - // destroying them. - bool deleteEvictedBackings(); - - bool requestLate(CCPrioritizedTexture*); - - void reduceMemory(CCResourceProvider*); - void clearAllMemory(CCResourceProvider*); - - void acquireBackingTextureIfNeeded(CCPrioritizedTexture*, CCResourceProvider*); - - void registerTexture(CCPrioritizedTexture*); - void unregisterTexture(CCPrioritizedTexture*); - void returnBackingTexture(CCPrioritizedTexture*); - -private: - friend class CCPrioritizedTextureTest; - - enum EvictionPriorityPolicy { - RespectManagerPriorityCutoff, - DoNotRespectManagerPriorityCutoff, - }; - - // Compare textures. Highest priority first. - static inline bool compareTextures(CCPrioritizedTexture* a, CCPrioritizedTexture* b) - { - if (a->requestPriority() == b->requestPriority()) - return a < b; - return CCPriorityCalculator::priorityIsHigher(a->requestPriority(), b->requestPriority()); - } - // Compare backings. Lowest priority first. - static inline bool compareBackings(CCPrioritizedTexture::Backing* a, CCPrioritizedTexture::Backing* b) - { - int priorityA = a->requestPriorityAtLastPriorityUpdate(); - int priorityB = b->requestPriorityAtLastPriorityUpdate(); - if (priorityA != priorityB) - return CCPriorityCalculator::priorityIsLower(priorityA, priorityB); - bool aboveCutoffA = a->wasAbovePriorityCutoffAtLastPriorityUpdate(); - bool aboveCutoffB = b->wasAbovePriorityCutoffAtLastPriorityUpdate(); - if (!aboveCutoffA && aboveCutoffB) - return true; - if (aboveCutoffA && !aboveCutoffB) - return false; - return a < b; - } - - CCPrioritizedTextureManager(size_t maxMemoryLimitBytes, int maxTextureSize, int pool); - - void updateBackingsPriorities(); - void evictBackingsToReduceMemory(size_t limitBytes, EvictionPriorityPolicy, CCResourceProvider*); - CCPrioritizedTexture::Backing* createBacking(IntSize, GC3Denum format, CCResourceProvider*); - void evictBackingResource(CCPrioritizedTexture::Backing*, CCResourceProvider*); - -#if !ASSERT_DISABLED - void assertInvariants(); -#endif - - size_t m_maxMemoryLimitBytes; - unsigned m_priorityCutoff; - size_t m_memoryUseBytes; - size_t m_memoryAboveCutoffBytes; - size_t m_memoryAvailableBytes; - int m_pool; - - typedef HashSet<CCPrioritizedTexture*> TextureSet; - typedef ListHashSet<CCPrioritizedTexture::Backing*> BackingSet; - typedef Vector<CCPrioritizedTexture*> TextureVector; - - TextureSet m_textures; - BackingSet m_backings; - BackingVector m_evictedBackings; - - TextureVector m_tempTextureVector; - BackingVector m_tempBackingVector; - - // Set by the main thread when it adjust priorities in such a way that - // the m_backings array's view of priorities is now out of date. - bool m_needsUpdateBackingsPrioritites; -}; - -} // WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPriorityCalculator.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCPriorityCalculator.cpp deleted file mode 100644 index 5a8bebaca..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPriorityCalculator.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCPriorityCalculator.h" - -using namespace std; - -namespace WebCore { - -// static -int CCPriorityCalculator::uiPriority(bool drawsToRootSurface) -{ - return drawsToRootSurface ? -1 : 2; -} - -// static -int CCPriorityCalculator::visiblePriority(bool drawsToRootSurface) -{ - return drawsToRootSurface ? 0 : 3; -} - -// static -int CCPriorityCalculator::renderSurfacePriority() -{ - return 1; -} - -// static -int CCPriorityCalculator::lingeringPriority(int previousPriority) -{ - // FIXME: We should remove this once we have priorities for all - // textures (we can't currently calculate distances for - // off-screen textures). - int lingeringPriority = 1000000; - return min(numeric_limits<int>::max() - 1, - max(lingeringPriority, previousPriority)) + 1; -} - -namespace { -unsigned manhattanDistance(const IntRect& a, const IntRect& b) -{ - IntRect c = unionRect(a, b); - int x = max(0, c.width() - a.width() - b.width() + 1); - int y = max(0, c.height() - a.height() - b.height() + 1); - return (x + y); -} -} - -int CCPriorityCalculator::priorityFromDistance(const IntRect& visibleRect, const IntRect& textureRect, bool drawsToRootSurface) const -{ - unsigned distance = manhattanDistance(visibleRect, textureRect); - if (!distance) - return visiblePriority(drawsToRootSurface); - return visiblePriority(false) + distance; -} - -int CCPriorityCalculator::priorityFromDistance(unsigned pixels, bool drawsToRootSurface) const -{ - if (!pixels) - return visiblePriority(drawsToRootSurface); - return visiblePriority(false) + pixels; -} - -int CCPriorityCalculator::priorityFromVisibility(bool visible, bool drawsToRootSurface) const -{ - return visible ? visiblePriority(drawsToRootSurface) : lowestPriority(); -} - -} // WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCPriorityCalculator.h b/Source/WebCore/platform/graphics/chromium/cc/CCPriorityCalculator.h deleted file mode 100644 index 7c2c8cda2..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCPriorityCalculator.h +++ /dev/null @@ -1,53 +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 CCPriorityCalculator_h -#define CCPriorityCalculator_h - -#include "GraphicsContext3D.h" -#include "IntRect.h" -#include "IntSize.h" - -namespace WebCore { - -class CCPriorityCalculator { -public: - static int uiPriority(bool drawsToRootSurface); - static int visiblePriority(bool drawsToRootSurface); - static int renderSurfacePriority(); - static int lingeringPriority(int previousPriority); - int priorityFromDistance(const IntRect& visibleRect, const IntRect& textureRect, bool drawsToRootSurface) const; - int priorityFromDistance(unsigned pixels, bool drawsToRootSurface) const; - int priorityFromVisibility(bool visible, bool drawsToRootSurface) const; - - static inline int highestPriority() { return std::numeric_limits<int>::min(); } - static inline int lowestPriority() { return std::numeric_limits<int>::max(); } - static inline bool priorityIsLower(int a, int b) { return a > b; } - static inline bool priorityIsHigher(int a, int b) { return a < b; } - static inline bool maxPriority(int a, int b) { return priorityIsHigher(a, b) ? a : b; } -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCProxy.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCProxy.cpp deleted file mode 100644 index 05752f0f8..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCProxy.cpp +++ /dev/null @@ -1,126 +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 "CCProxy.h" - -#include "CCThreadTask.h" -#include <wtf/MainThread.h> - -using namespace WTF; - -namespace WebCore { - -namespace { -#ifndef NDEBUG -bool implThreadIsOverridden = false; -bool s_isMainThreadBlocked = false; -ThreadIdentifier threadIDOverridenToBeImplThread; -#endif -CCThread* s_mainThread = 0; -CCThread* s_implThread = 0; -} - -void CCProxy::setMainThread(CCThread* thread) -{ - s_mainThread = thread; -} - -CCThread* CCProxy::mainThread() -{ - return s_mainThread; -} - -bool CCProxy::hasImplThread() -{ - return s_implThread; -} - -void CCProxy::setImplThread(CCThread* thread) -{ - s_implThread = thread; -} - -CCThread* CCProxy::implThread() -{ - return s_implThread; -} - -CCThread* CCProxy::currentThread() -{ - ThreadIdentifier currentThreadIdentifier = WTF::currentThread(); - if (s_mainThread && s_mainThread->threadID() == currentThreadIdentifier) - return s_mainThread; - if (s_implThread && s_implThread->threadID() == currentThreadIdentifier) - return s_implThread; - return 0; -} - -#ifndef NDEBUG -bool CCProxy::isMainThread() -{ - ASSERT(s_mainThread); - if (implThreadIsOverridden && WTF::currentThread() == threadIDOverridenToBeImplThread) - return false; - return WTF::currentThread() == s_mainThread->threadID(); -} - -bool CCProxy::isImplThread() -{ - WTF::ThreadIdentifier implThreadID = s_implThread ? s_implThread->threadID() : 0; - if (implThreadIsOverridden && WTF::currentThread() == threadIDOverridenToBeImplThread) - return true; - return WTF::currentThread() == implThreadID; -} - -void CCProxy::setCurrentThreadIsImplThread(bool isImplThread) -{ - implThreadIsOverridden = isImplThread; - if (isImplThread) - threadIDOverridenToBeImplThread = WTF::currentThread(); -} - -bool CCProxy::isMainThreadBlocked() -{ - return s_isMainThreadBlocked; -} - -void CCProxy::setMainThreadBlocked(bool isMainThreadBlocked) -{ - s_isMainThreadBlocked = isMainThreadBlocked; -} -#endif - -CCProxy::CCProxy() -{ - ASSERT(isMainThread()); -} - -CCProxy::~CCProxy() -{ - ASSERT(isMainThread()); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCProxy.h b/Source/WebCore/platform/graphics/chromium/cc/CCProxy.h deleted file mode 100644 index 42124c3a2..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCProxy.h +++ /dev/null @@ -1,147 +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 CCProxy_h -#define CCProxy_h - -#include "IntRect.h" -#include <public/WebCompositorOutputSurface.h> -#include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/PassRefPtr.h> -#include <wtf/Threading.h> - -namespace WebCore { - -class CCThread; -struct CCRenderingStats; -struct RendererCapabilities; - -// Abstract class responsible for proxying commands from the main-thread side of -// the compositor over to the compositor implementation. -class CCProxy { - WTF_MAKE_NONCOPYABLE(CCProxy); -public: - static void setMainThread(CCThread*); - static CCThread* mainThread(); - - static bool hasImplThread(); - static void setImplThread(CCThread*); - static CCThread* implThread(); - - // Returns 0 if the current thread is neither the main thread nor the impl thread. - static CCThread* currentThread(); - - virtual ~CCProxy(); - - virtual bool compositeAndReadback(void *pixels, const IntRect&) = 0; - - virtual void startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, double durationSec) = 0; - - virtual void finishAllRendering() = 0; - - virtual bool isStarted() const = 0; - - // Attempts to initialize a context to use for rendering. Returns false if the context could not be created. - // The context will not be used and no frames may be produced until initializeRenderer() is called. - virtual bool initializeContext() = 0; - - // Indicates that the compositing surface associated with our context is ready to use. - virtual void setSurfaceReady() = 0; - - virtual void setVisible(bool) = 0; - - // Attempts to initialize the layer renderer. Returns false if the context isn't usable for compositing. - virtual bool initializeRenderer() = 0; - - // Attempts to recreate the context and layer renderer after a context lost. Returns false if the renderer couldn't be - // reinitialized. - virtual bool recreateContext() = 0; - - virtual void implSideRenderingStats(CCRenderingStats&) = 0; - - virtual const RendererCapabilities& rendererCapabilities() const = 0; - - virtual void setNeedsAnimate() = 0; - virtual void setNeedsCommit() = 0; - virtual void setNeedsRedraw() = 0; - - virtual void didAddAnimation() = 0; - - virtual bool commitRequested() const = 0; - - virtual void start() = 0; // Must be called before using the proxy. - virtual void stop() = 0; // Must be called before deleting the proxy. - - // Forces 3D commands on all contexts to wait for all previous SwapBuffers to finish before executing in the GPU - // process. - virtual void forceSerializeOnSwapBuffers() = 0; - - // Maximum number of sub-region texture updates supported for each commit. - virtual size_t maxPartialTextureUpdates() const = 0; - - virtual void acquireLayerTextures() = 0; - - // Debug hooks -#ifndef NDEBUG - static bool isMainThread(); - static bool isImplThread(); - static bool isMainThreadBlocked(); - static void setMainThreadBlocked(bool); -#endif - - // Testing hooks - virtual void loseContext() = 0; - -#ifndef NDEBUG - static void setCurrentThreadIsImplThread(bool); -#endif - -protected: - CCProxy(); - friend class DebugScopedSetImplThread; - friend class DebugScopedSetMainThreadBlocked; -}; - -class DebugScopedSetMainThreadBlocked { -public: - DebugScopedSetMainThreadBlocked() - { -#if !ASSERT_DISABLED - ASSERT(!CCProxy::isMainThreadBlocked()); - CCProxy::setMainThreadBlocked(true); -#endif - } - ~DebugScopedSetMainThreadBlocked() - { -#if !ASSERT_DISABLED - ASSERT(CCProxy::isMainThreadBlocked()); - CCProxy::setMainThreadBlocked(false); -#endif - } -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCQuadCuller.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCQuadCuller.cpp deleted file mode 100644 index 94979ea8e..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCQuadCuller.cpp +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 USE(ACCELERATED_COMPOSITING) - -#include "CCQuadCuller.h" - -#include "CCAppendQuadsData.h" -#include "CCDebugBorderDrawQuad.h" -#include "CCLayerImpl.h" -#include "CCOcclusionTracker.h" -#include "CCOverdrawMetrics.h" -#include "CCRenderPass.h" -#include "Region.h" -#include "SkColor.h" -#include <public/WebTransformationMatrix.h> - -using namespace std; - -namespace WebCore { - -static const int debugTileBorderWidth = 1; -static const int debugTileBorderAlpha = 120; -static const int debugTileBorderColorRed = 160; -static const int debugTileBorderColorGreen = 100; -static const int debugTileBorderColorBlue = 0; - -CCQuadCuller::CCQuadCuller(CCQuadList& quadList, CCSharedQuadStateList& sharedQuadStateList, CCLayerImpl* layer, const CCOcclusionTrackerImpl* occlusionTracker, bool showCullingWithDebugBorderQuads, bool forSurface) - : m_quadList(quadList) - , m_sharedQuadStateList(sharedQuadStateList) - , m_currentSharedQuadState(0) - , m_layer(layer) - , m_occlusionTracker(occlusionTracker) - , m_showCullingWithDebugBorderQuads(showCullingWithDebugBorderQuads) - , m_forSurface(forSurface) -{ -} - -CCSharedQuadState* CCQuadCuller::useSharedQuadState(PassOwnPtr<CCSharedQuadState> passSharedQuadState) -{ - OwnPtr<CCSharedQuadState> sharedQuadState(passSharedQuadState); - sharedQuadState->id = m_sharedQuadStateList.size(); - - // FIXME: If all quads are culled for the sharedQuadState, we can drop it from the list. - m_currentSharedQuadState = sharedQuadState.get(); - m_sharedQuadStateList.append(sharedQuadState.release()); - return m_currentSharedQuadState; -} - -static inline bool appendQuadInternal(PassOwnPtr<CCDrawQuad> passDrawQuad, const IntRect& culledRect, CCQuadList& quadList, const CCOcclusionTrackerImpl& occlusionTracker, bool createDebugBorderQuads) -{ - OwnPtr<CCDrawQuad> drawQuad(passDrawQuad); - bool keepQuad = !culledRect.isEmpty(); - if (keepQuad) - drawQuad->setQuadVisibleRect(culledRect); - - occlusionTracker.overdrawMetrics().didCullForDrawing(drawQuad->quadTransform(), drawQuad->quadRect(), culledRect); - occlusionTracker.overdrawMetrics().didDraw(drawQuad->quadTransform(), culledRect, drawQuad->opaqueRect()); - - if (keepQuad) { - if (createDebugBorderQuads && !drawQuad->isDebugQuad() && drawQuad->quadVisibleRect() != drawQuad->quadRect()) { - SkColor borderColor = SkColorSetARGB(debugTileBorderAlpha, debugTileBorderColorRed, debugTileBorderColorGreen, debugTileBorderColorBlue); - quadList.append(CCDebugBorderDrawQuad::create(drawQuad->sharedQuadState(), drawQuad->quadVisibleRect(), borderColor, debugTileBorderWidth)); - } - - // Release the quad after we're done using it. - quadList.append(drawQuad.release()); - } - return keepQuad; -} - -bool CCQuadCuller::append(PassOwnPtr<CCDrawQuad> passDrawQuad, CCAppendQuadsData& appendQuadsData) -{ - ASSERT(passDrawQuad->sharedQuadState() == m_currentSharedQuadState); - ASSERT(passDrawQuad->sharedQuadStateId() == m_currentSharedQuadState->id); - ASSERT(!m_sharedQuadStateList.isEmpty()); - ASSERT(m_sharedQuadStateList.last().get() == m_currentSharedQuadState); - - IntRect culledRect; - bool hasOcclusionFromOutsideTargetSurface; - - if (m_forSurface) - culledRect = m_occlusionTracker->unoccludedContributingSurfaceContentRect(m_layer, false, passDrawQuad->quadRect(), &hasOcclusionFromOutsideTargetSurface); - else - culledRect = m_occlusionTracker->unoccludedContentRect(m_layer, passDrawQuad->quadRect(), &hasOcclusionFromOutsideTargetSurface); - - appendQuadsData.hadOcclusionFromOutsideTargetSurface |= hasOcclusionFromOutsideTargetSurface; - - return appendQuadInternal(passDrawQuad, culledRect, m_quadList, *m_occlusionTracker, m_showCullingWithDebugBorderQuads); -} - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCQuadCuller.h b/Source/WebCore/platform/graphics/chromium/cc/CCQuadCuller.h deleted file mode 100644 index 51d5409c3..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCQuadCuller.h +++ /dev/null @@ -1,58 +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 CCQuadCuller_h -#define CCQuadCuller_h - -#include "CCQuadSink.h" -#include "CCRenderPass.h" - -namespace WebCore { -class CCLayerImpl; -class CCRenderSurface; -template<typename LayerType, typename SurfaceType> -class CCOcclusionTrackerBase; - -class CCQuadCuller : public CCQuadSink { -public: - CCQuadCuller(CCQuadList&, CCSharedQuadStateList&, CCLayerImpl*, const CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>*, bool showCullingWithDebugBorderQuads, bool forSurface); - virtual ~CCQuadCuller() { } - - // CCQuadSink implementation. - virtual CCSharedQuadState* useSharedQuadState(PassOwnPtr<CCSharedQuadState>) OVERRIDE; - virtual bool append(PassOwnPtr<CCDrawQuad>, CCAppendQuadsData&) OVERRIDE; - -private: - CCQuadList& m_quadList; - CCSharedQuadStateList& m_sharedQuadStateList; - CCSharedQuadState* m_currentSharedQuadState; - CCLayerImpl* m_layer; - const CCOcclusionTrackerBase<CCLayerImpl, CCRenderSurface>* m_occlusionTracker; - bool m_showCullingWithDebugBorderQuads; - bool m_forSurface; -}; - -} -#endif // CCQuadCuller_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCQuadSink.h b/Source/WebCore/platform/graphics/chromium/cc/CCQuadSink.h deleted file mode 100644 index 5e47c684d..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCQuadSink.h +++ /dev/null @@ -1,51 +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 CCQuadSink_h -#define CCQuadSink_h - -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCDrawQuad; - -struct CCAppendQuadsData; -struct CCSharedQuadState; - -class CCQuadSink { -public: - virtual ~CCQuadSink() { } - - // Call this to add a SharedQuadState before appending quads that refer to it. Returns a pointer - // to the given SharedQuadState for convenience, that can be set on the quads to append. - virtual CCSharedQuadState* useSharedQuadState(PassOwnPtr<CCSharedQuadState>) = 0; - - // Returns true if the quad is added to the list, and false if the quad is entirely culled. - virtual bool append(PassOwnPtr<CCDrawQuad> passDrawQuad, CCAppendQuadsData&) = 0; -}; - -} -#endif // CCQuadCuller_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPass.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCRenderPass.cpp deleted file mode 100644 index a6771454f..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPass.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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "CCRenderPass.h" - -#include "CCLayerImpl.h" -#include "CCMathUtil.h" -#include "CCOcclusionTracker.h" -#include "CCQuadCuller.h" -#include "CCSharedQuadState.h" -#include "CCSolidColorDrawQuad.h" - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -PassOwnPtr<CCRenderPass> CCRenderPass::create(Id id, IntRect outputRect, const WebKit::WebTransformationMatrix& transformToRootTarget) -{ - return adoptPtr(new CCRenderPass(id, outputRect, transformToRootTarget)); -} - -CCRenderPass::CCRenderPass(Id id, IntRect outputRect, const WebKit::WebTransformationMatrix& transformToRootTarget) - : m_id(id) - , m_transformToRootTarget(transformToRootTarget) - , m_outputRect(outputRect) - , m_hasTransparentBackground(true) - , m_hasOcclusionFromOutsideTargetSurface(false) -{ - ASSERT(id.layerId > 0); - ASSERT(id.index >= 0); -} - -PassOwnPtr<CCRenderPass> CCRenderPass::copy(Id newId) const -{ - ASSERT(newId != m_id); - - OwnPtr<CCRenderPass> copyPass(create(newId, m_outputRect, m_transformToRootTarget)); - copyPass->setDamageRect(m_damageRect); - copyPass->setHasTransparentBackground(m_hasTransparentBackground); - copyPass->setHasOcclusionFromOutsideTargetSurface(m_hasOcclusionFromOutsideTargetSurface); - copyPass->setFilters(m_filters); - copyPass->setBackgroundFilters(m_backgroundFilters); - return copyPass.release(); -} - -void CCRenderPass::appendQuadsForLayer(CCLayerImpl* layer, CCOcclusionTrackerImpl* occlusionTracker, CCAppendQuadsData& appendQuadsData) -{ - const bool forSurface = false; - CCQuadCuller quadCuller(m_quadList, m_sharedQuadStateList, layer, occlusionTracker, layer->hasDebugBorders(), forSurface); - - layer->appendQuads(quadCuller, appendQuadsData); -} - -void CCRenderPass::appendQuadsForRenderSurfaceLayer(CCLayerImpl* layer, const CCRenderPass* contributingRenderPass, CCOcclusionTrackerImpl* occlusionTracker, CCAppendQuadsData& appendQuadsData) -{ - const bool forSurface = true; - CCQuadCuller quadCuller(m_quadList, m_sharedQuadStateList, layer, occlusionTracker, layer->hasDebugBorders(), forSurface); - - bool isReplica = false; - layer->renderSurface()->appendQuads(quadCuller, appendQuadsData, isReplica, contributingRenderPass->id()); - - // Add replica after the surface so that it appears below the surface. - if (layer->hasReplica()) { - isReplica = true; - layer->renderSurface()->appendQuads(quadCuller, appendQuadsData, isReplica, contributingRenderPass->id()); - } -} - -void CCRenderPass::appendQuadsToFillScreen(CCLayerImpl* rootLayer, SkColor screenBackgroundColor, const CCOcclusionTrackerImpl& occlusionTracker) -{ - if (!rootLayer || !screenBackgroundColor) - return; - - Region fillRegion = occlusionTracker.computeVisibleRegionInScreen(); - if (fillRegion.isEmpty()) - return; - - bool forSurface = false; - CCQuadCuller quadCuller(m_quadList, m_sharedQuadStateList, rootLayer, &occlusionTracker, rootLayer->hasDebugBorders(), forSurface); - - // Manually create the quad state for the gutter quads, as the root layer - // doesn't have any bounds and so can't generate this itself. - // FIXME: Make the gutter quads generated by the solid color layer (make it smarter about generating quads to fill unoccluded areas). - IntRect rootTargetRect = rootLayer->renderSurface()->contentRect(); - float opacity = 1; - bool opaque = true; - CCSharedQuadState* sharedQuadState = quadCuller.useSharedQuadState(CCSharedQuadState::create(rootLayer->drawTransform(), rootTargetRect, rootTargetRect, opacity, opaque)); - ASSERT(rootLayer->screenSpaceTransform().isInvertible()); - WebTransformationMatrix transformToLayerSpace = rootLayer->screenSpaceTransform().inverse(); - Vector<IntRect> fillRects = fillRegion.rects(); - for (size_t i = 0; i < fillRects.size(); ++i) { - // The root layer transform is composed of translations and scales only, no perspective, so mapping is sufficient. - IntRect layerRect = CCMathUtil::mapClippedRect(transformToLayerSpace, fillRects[i]); - // Skip the quad culler and just append the quads directly to avoid occlusion checks. - m_quadList.append(CCSolidColorDrawQuad::create(sharedQuadState, layerRect, screenBackgroundColor)); - } -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPass.h b/Source/WebCore/platform/graphics/chromium/cc/CCRenderPass.h deleted file mode 100644 index 7a5cc6106..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPass.h +++ /dev/null @@ -1,152 +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 CCRenderPass_h -#define CCRenderPass_h - -#include "CCDrawQuad.h" -#include "CCOcclusionTracker.h" -#include "CCSharedQuadState.h" -#include "SkColor.h" -#include <public/WebFilterOperations.h> -#include <public/WebTransformationMatrix.h> -#include <wtf/HashMap.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/Vector.h> - -namespace WebCore { - -class CCLayerImpl; -class CCRenderSurface; - -struct CCAppendQuadsData; - -// A list of CCDrawQuad objects, sorted internally in front-to-back order. -class CCQuadList : public Vector<OwnPtr<CCDrawQuad> > { -public: - typedef reverse_iterator backToFrontIterator; - typedef const_reverse_iterator constBackToFrontIterator; - - inline backToFrontIterator backToFrontBegin() { return rbegin(); } - inline backToFrontIterator backToFrontEnd() { return rend(); } - inline constBackToFrontIterator backToFrontBegin() const { return rbegin(); } - inline constBackToFrontIterator backToFrontEnd() const { return rend(); } -}; - -typedef Vector<OwnPtr<CCSharedQuadState> > CCSharedQuadStateList; - -class CCRenderPass { - WTF_MAKE_NONCOPYABLE(CCRenderPass); -public: - struct Id { - int layerId; - int index; - - Id(int layerId, int index) - : layerId(layerId) - , index(index) - { - } - - bool operator==(const Id& other) const { return layerId == other.layerId && index == other.index; } - bool operator!=(const Id& other) const { return !(*this == other); } - bool operator<(const Id& other) const { return layerId < other.layerId || (layerId == other.layerId && index < other.index); } - }; - - static PassOwnPtr<CCRenderPass> create(Id, IntRect outputRect, const WebKit::WebTransformationMatrix& transformToRootTarget); - - // A shallow copy of the render pass, which does not include its quads. - PassOwnPtr<CCRenderPass> copy(Id newId) const; - - void appendQuadsForLayer(CCLayerImpl*, CCOcclusionTrackerImpl*, CCAppendQuadsData&); - void appendQuadsForRenderSurfaceLayer(CCLayerImpl*, const CCRenderPass* contributingRenderPass, CCOcclusionTrackerImpl*, CCAppendQuadsData&); - void appendQuadsToFillScreen(CCLayerImpl* rootLayer, SkColor screenBackgroundColor, const CCOcclusionTrackerImpl&); - - const CCQuadList& quadList() const { return m_quadList; } - - Id id() const { return m_id; } - - // FIXME: Modify this transform when merging the RenderPass into a parent compositor. - // Transforms from quad's original content space to the root target's content space. - const WebKit::WebTransformationMatrix& transformToRootTarget() const { return m_transformToRootTarget; } - - // This denotes the bounds in physical pixels of the output generated by this RenderPass. - const IntRect& outputRect() const { return m_outputRect; } - - FloatRect damageRect() const { return m_damageRect; } - void setDamageRect(FloatRect rect) { m_damageRect = rect; } - - const WebKit::WebFilterOperations& filters() const { return m_filters; } - void setFilters(const WebKit::WebFilterOperations& filters) { m_filters = filters; } - - const WebKit::WebFilterOperations& backgroundFilters() const { return m_backgroundFilters; } - void setBackgroundFilters(const WebKit::WebFilterOperations& filters) { m_backgroundFilters = filters; } - - bool hasTransparentBackground() const { return m_hasTransparentBackground; } - void setHasTransparentBackground(bool transparent) { m_hasTransparentBackground = transparent; } - - bool hasOcclusionFromOutsideTargetSurface() const { return m_hasOcclusionFromOutsideTargetSurface; } - void setHasOcclusionFromOutsideTargetSurface(bool hasOcclusionFromOutsideTargetSurface) { m_hasOcclusionFromOutsideTargetSurface = hasOcclusionFromOutsideTargetSurface; } -protected: - CCRenderPass(Id, IntRect outputRect, const WebKit::WebTransformationMatrix& transformToRootTarget); - - Id m_id; - CCQuadList m_quadList; - CCSharedQuadStateList m_sharedQuadStateList; - WebKit::WebTransformationMatrix m_transformToRootTarget; - IntRect m_outputRect; - FloatRect m_damageRect; - bool m_hasTransparentBackground; - bool m_hasOcclusionFromOutsideTargetSurface; - WebKit::WebFilterOperations m_filters; - WebKit::WebFilterOperations m_backgroundFilters; -}; - -} // namespace WebCore - -namespace WTF { -template<> struct HashTraits<WebCore::CCRenderPass::Id> : GenericHashTraits<WebCore::CCRenderPass::Id> { - static const bool emptyValueIsZero = false; - static const bool needsDestruction = false; - static WebCore::CCRenderPass::Id emptyValue() { return WebCore::CCRenderPass::Id(0, 0); } - static void constructDeletedValue(WebCore::CCRenderPass::Id& slot) { slot = WebCore::CCRenderPass::Id(-1, -1); } - static bool isDeletedValue(WebCore::CCRenderPass::Id value) { return value.layerId == -1 && value.index == -1; } -}; -template<> struct IntHash<WebCore::CCRenderPass::Id> { - static unsigned hash(const WebCore::CCRenderPass::Id& key) { return PairHash<int, int>::hash(std::make_pair(key.layerId, key.index)); } - static bool equal(const WebCore::CCRenderPass::Id& a, const WebCore::CCRenderPass::Id& b) { return a == b; } - static const bool safeToCompareToEmptyOrDeleted = true; -}; -template<> struct DefaultHash<WebCore::CCRenderPass::Id> { - typedef IntHash<WebCore::CCRenderPass::Id> Hash; -}; -} // namespace WTF - -namespace WebCore { -typedef Vector<CCRenderPass*> CCRenderPassList; -typedef HashMap<CCRenderPass::Id, OwnPtr<CCRenderPass> > CCRenderPassIdHashMap; -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassDrawQuad.cpp deleted file mode 100644 index 4324110b8..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassDrawQuad.cpp +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCRenderPassDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCRenderPassDrawQuad> CCRenderPassDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, CCRenderPass::Id renderPassId, bool isReplica, const CCResourceProvider::ResourceId maskResourceId, const IntRect& contentsChangedSinceLastFrame, float maskTexCoordScaleX, float maskTexCoordScaleY, float maskTexCoordOffsetX, float maskTexCoordOffsetY) -{ - return adoptPtr(new CCRenderPassDrawQuad(sharedQuadState, quadRect, renderPassId, isReplica, maskResourceId, contentsChangedSinceLastFrame, maskTexCoordScaleX, maskTexCoordScaleY, maskTexCoordOffsetX, maskTexCoordOffsetY)); -} - -CCRenderPassDrawQuad::CCRenderPassDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, CCRenderPass::Id renderPassId, bool isReplica, CCResourceProvider::ResourceId maskResourceId, const IntRect& contentsChangedSinceLastFrame, float maskTexCoordScaleX, float maskTexCoordScaleY, float maskTexCoordOffsetX, float maskTexCoordOffsetY) - : CCDrawQuad(sharedQuadState, CCDrawQuad::RenderPass, quadRect) - , m_renderPassId(renderPassId) - , m_isReplica(isReplica) - , m_maskResourceId(maskResourceId) - , m_contentsChangedSinceLastFrame(contentsChangedSinceLastFrame) - , m_maskTexCoordScaleX(maskTexCoordScaleX) - , m_maskTexCoordScaleY(maskTexCoordScaleY) - , m_maskTexCoordOffsetX(maskTexCoordOffsetX) - , m_maskTexCoordOffsetY(maskTexCoordOffsetY) -{ - ASSERT(m_renderPassId.layerId > 0); - ASSERT(m_renderPassId.index >= 0); -} - -const CCRenderPassDrawQuad* CCRenderPassDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::RenderPass); - return static_cast<const CCRenderPassDrawQuad*>(quad); -} - -PassOwnPtr<CCRenderPassDrawQuad> CCRenderPassDrawQuad::copy(const CCSharedQuadState* copiedSharedQuadState, CCRenderPass::Id copiedRenderPassId) const -{ - unsigned bytes = size(); - ASSERT(bytes); - - OwnPtr<CCRenderPassDrawQuad> copyQuad(adoptPtr(reinterpret_cast<CCRenderPassDrawQuad*>(new char[bytes]))); - memcpy(copyQuad.get(), this, bytes); - copyQuad->setSharedQuadState(copiedSharedQuadState); - copyQuad->m_renderPassId = copiedRenderPassId; - - return copyQuad.release(); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassDrawQuad.h deleted file mode 100644 index 29136ef98..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassDrawQuad.h +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCRenderPassDrawQuad_h -#define CCRenderPassDrawQuad_h - -#include "CCDrawQuad.h" -#include "CCRenderPass.h" -#include "CCResourceProvider.h" -#include "IntRect.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCRenderPassDrawQuad : public CCDrawQuad { - WTF_MAKE_NONCOPYABLE(CCRenderPassDrawQuad); -public: - static PassOwnPtr<CCRenderPassDrawQuad> create(const CCSharedQuadState*, const IntRect&, CCRenderPass::Id renderPassId, bool isReplica, CCResourceProvider::ResourceId maskResourceId, const IntRect& contentsChangedSinceLastFrame, float maskTexCoordScaleX, float maskTexCoordScaleY, float maskTexCoordOffsetX, float maskTexCoordOffsetY); - - CCRenderPass::Id renderPassId() const { return m_renderPassId; } - bool isReplica() const { return m_isReplica; } - CCResourceProvider::ResourceId maskResourceId() const { return m_maskResourceId; } - const IntRect& contentsChangedSinceLastFrame() const { return m_contentsChangedSinceLastFrame; } - - static const CCRenderPassDrawQuad* materialCast(const CCDrawQuad*); - float maskTexCoordScaleX() const { return m_maskTexCoordScaleX; } - float maskTexCoordScaleY() const { return m_maskTexCoordScaleY; } - float maskTexCoordOffsetX() const { return m_maskTexCoordOffsetX; } - float maskTexCoordOffsetY() const { return m_maskTexCoordOffsetY; } - - PassOwnPtr<CCRenderPassDrawQuad> copy(const CCSharedQuadState* copiedSharedQuadState, CCRenderPass::Id copiedRenderPassId) const; - -private: - CCRenderPassDrawQuad(const CCSharedQuadState*, const IntRect&, CCRenderPass::Id renderPassId, bool isReplica, CCResourceProvider::ResourceId maskResourceId, const IntRect& contentsChangedSinceLastFrame, float maskTexCoordScaleX, float maskTexCoordScaleY, float maskTexCoordOffsetX, float maskTexCoordOffsetY); - - CCRenderPass::Id m_renderPassId; - bool m_isReplica; - CCResourceProvider::ResourceId m_maskResourceId; - IntRect m_contentsChangedSinceLastFrame; - float m_maskTexCoordScaleX; - float m_maskTexCoordScaleY; - float m_maskTexCoordOffsetX; - float m_maskTexCoordOffsetY; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassSink.h b/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassSink.h deleted file mode 100644 index 593a80909..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderPassSink.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCRenderPassSink_h -#define CCRenderPassSink_h - -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCRenderPass; - -class CCRenderPassSink { -public: - virtual void appendRenderPass(PassOwnPtr<CCRenderPass>) = 0; -}; - -} -#endif // CCRenderPassSink_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurface.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurface.cpp deleted file mode 100644 index 16393b930..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurface.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. - */ - -#include "config.h" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCRenderSurface.h" - -#include "CCDamageTracker.h" -#include "CCDebugBorderDrawQuad.h" -#include "CCLayerImpl.h" -#include "CCMathUtil.h" -#include "CCQuadSink.h" -#include "CCRenderPass.h" -#include "CCRenderPassDrawQuad.h" -#include "CCRenderPassSink.h" -#include "CCSharedQuadState.h" -#include "TextStream.h" -#include <public/WebTransformationMatrix.h> -#include <wtf/text/CString.h> - -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -static const int debugSurfaceBorderWidth = 2; -static const int debugSurfaceBorderAlpha = 100; -static const int debugSurfaceBorderColorRed = 0; -static const int debugSurfaceBorderColorGreen = 0; -static const int debugSurfaceBorderColorBlue = 255; -static const int debugReplicaBorderColorRed = 160; -static const int debugReplicaBorderColorGreen = 0; -static const int debugReplicaBorderColorBlue = 255; - -CCRenderSurface::CCRenderSurface(CCLayerImpl* owningLayer) - : m_owningLayer(owningLayer) - , m_surfacePropertyChanged(false) - , m_drawOpacity(1) - , m_drawOpacityIsAnimating(false) - , m_targetSurfaceTransformsAreAnimating(false) - , m_screenSpaceTransformsAreAnimating(false) - , m_nearestAncestorThatMovesPixels(0) - , m_targetRenderSurfaceLayerIndexHistory(0) - , m_currentLayerIndexHistory(0) -{ - m_damageTracker = CCDamageTracker::create(); -} - -CCRenderSurface::~CCRenderSurface() -{ -} - -FloatRect CCRenderSurface::drawableContentRect() const -{ - FloatRect drawableContentRect = CCMathUtil::mapClippedRect(m_drawTransform, m_contentRect); - if (m_owningLayer->hasReplica()) - drawableContentRect.unite(CCMathUtil::mapClippedRect(m_replicaDrawTransform, m_contentRect)); - - return drawableContentRect; -} - -String CCRenderSurface::name() const -{ - return String::format("RenderSurface(id=%i,owner=%s)", m_owningLayer->id(), m_owningLayer->debugName().utf8().data()); -} - -static void writeIndent(TextStream& ts, int indent) -{ - for (int i = 0; i != indent; ++i) - ts << " "; -} - -void CCRenderSurface::dumpSurface(TextStream& ts, int indent) const -{ - writeIndent(ts, indent); - ts << name() << "\n"; - - writeIndent(ts, indent+1); - ts << "contentRect: (" << m_contentRect.x() << ", " << m_contentRect.y() << ", " << m_contentRect.width() << ", " << m_contentRect.height() << "\n"; - - writeIndent(ts, indent+1); - ts << "drawTransform: "; - ts << m_drawTransform.m11() << ", " << m_drawTransform.m12() << ", " << m_drawTransform.m13() << ", " << m_drawTransform.m14() << " // "; - ts << m_drawTransform.m21() << ", " << m_drawTransform.m22() << ", " << m_drawTransform.m23() << ", " << m_drawTransform.m24() << " // "; - ts << m_drawTransform.m31() << ", " << m_drawTransform.m32() << ", " << m_drawTransform.m33() << ", " << m_drawTransform.m34() << " // "; - ts << m_drawTransform.m41() << ", " << m_drawTransform.m42() << ", " << m_drawTransform.m43() << ", " << m_drawTransform.m44() << "\n"; - - writeIndent(ts, indent+1); - ts << "damageRect is pos(" << m_damageTracker->currentDamageRect().x() << "," << m_damageTracker->currentDamageRect().y() << "), "; - ts << "size(" << m_damageTracker->currentDamageRect().width() << "," << m_damageTracker->currentDamageRect().height() << ")\n"; -} - -int CCRenderSurface::owningLayerId() const -{ - return m_owningLayer ? m_owningLayer->id() : 0; -} - - -void CCRenderSurface::setClipRect(const IntRect& clipRect) -{ - if (m_clipRect == clipRect) - return; - - m_surfacePropertyChanged = true; - m_clipRect = clipRect; -} - -bool CCRenderSurface::contentsChanged() const -{ - return !m_damageTracker->currentDamageRect().isEmpty(); -} - -void CCRenderSurface::setContentRect(const IntRect& contentRect) -{ - if (m_contentRect == contentRect) - return; - - m_surfacePropertyChanged = true; - m_contentRect = contentRect; -} - -bool CCRenderSurface::surfacePropertyChanged() const -{ - // Surface property changes are tracked as follows: - // - // - m_surfacePropertyChanged is flagged when the clipRect or contentRect change. As - // of now, these are the only two properties that can be affected by descendant layers. - // - // - all other property changes come from the owning layer (or some ancestor layer - // that propagates its change to the owning layer). - // - ASSERT(m_owningLayer); - return m_surfacePropertyChanged || m_owningLayer->layerPropertyChanged(); -} - -bool CCRenderSurface::surfacePropertyChangedOnlyFromDescendant() const -{ - return m_surfacePropertyChanged && !m_owningLayer->layerPropertyChanged(); -} - -static inline IntRect computeClippedRectInTarget(const CCLayerImpl* owningLayer) -{ - ASSERT(owningLayer->parent()); - - const CCLayerImpl* renderTarget = owningLayer->parent()->renderTarget(); - const CCRenderSurface* self = owningLayer->renderSurface(); - - IntRect clippedRectInTarget = self->clipRect(); - if (owningLayer->backgroundFilters().hasFilterThatMovesPixels()) { - // If the layer has background filters that move pixels, we cannot scissor as tightly. - // FIXME: this should be able to be a tighter scissor, perhaps expanded by the filter outsets? - clippedRectInTarget = renderTarget->renderSurface()->contentRect(); - } else if (clippedRectInTarget.isEmpty()) { - // For surfaces, empty clipRect means that the surface does not clip anything. - clippedRectInTarget = enclosingIntRect(intersection(renderTarget->renderSurface()->contentRect(), self->drawableContentRect())); - } else - clippedRectInTarget.intersect(enclosingIntRect(self->drawableContentRect())); - return clippedRectInTarget; -} - -CCRenderPass::Id CCRenderSurface::renderPassId() -{ - int layerId = m_owningLayer->id(); - int subId = 0; - ASSERT(layerId > 0); - return CCRenderPass::Id(layerId, subId); -} - -void CCRenderSurface::appendRenderPasses(CCRenderPassSink& passSink) -{ - OwnPtr<CCRenderPass> pass = CCRenderPass::create(renderPassId(), m_contentRect, m_screenSpaceTransform); - pass->setDamageRect(m_damageTracker->currentDamageRect()); - pass->setFilters(m_owningLayer->filters()); - pass->setBackgroundFilters(m_owningLayer->backgroundFilters()); - passSink.appendRenderPass(pass.release()); -} - -void CCRenderSurface::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData, bool forReplica, CCRenderPass::Id renderPassId) -{ - ASSERT(!forReplica || m_owningLayer->hasReplica()); - - IntRect clippedRectInTarget = computeClippedRectInTarget(m_owningLayer); - bool isOpaque = false; - const WebTransformationMatrix& drawTransform = forReplica ? m_replicaDrawTransform : m_drawTransform; - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(CCSharedQuadState::create(drawTransform, m_contentRect, clippedRectInTarget, m_drawOpacity, isOpaque)); - - if (m_owningLayer->hasDebugBorders()) { - int red = forReplica ? debugReplicaBorderColorRed : debugSurfaceBorderColorRed; - int green = forReplica ? debugReplicaBorderColorGreen : debugSurfaceBorderColorGreen; - int blue = forReplica ? debugReplicaBorderColorBlue : debugSurfaceBorderColorBlue; - SkColor color = SkColorSetARGB(debugSurfaceBorderAlpha, red, green, blue); - quadSink.append(CCDebugBorderDrawQuad::create(sharedQuadState, contentRect(), color, debugSurfaceBorderWidth), appendQuadsData); - } - - // FIXME: By using the same RenderSurface for both the content and its reflection, - // it's currently not possible to apply a separate mask to the reflection layer - // or correctly handle opacity in reflections (opacity must be applied after drawing - // both the layer and its reflection). The solution is to introduce yet another RenderSurface - // to draw the layer and its reflection in. For now we only apply a separate reflection - // mask if the contents don't have a mask of their own. - CCLayerImpl* maskLayer = m_owningLayer->maskLayer(); - if (maskLayer && (!maskLayer->drawsContent() || maskLayer->bounds().isEmpty())) - maskLayer = 0; - - if (!maskLayer && forReplica) { - maskLayer = m_owningLayer->replicaLayer()->maskLayer(); - if (maskLayer && (!maskLayer->drawsContent() || maskLayer->bounds().isEmpty())) - maskLayer = 0; - } - - float maskTexCoordScaleX = 1; - float maskTexCoordScaleY = 1; - float maskTexCoordOffsetX = 1; - float maskTexCoordOffsetY = 1; - if (maskLayer) { - maskTexCoordScaleX = static_cast<float>(contentRect().width()) / maskLayer->contentBounds().width(); - maskTexCoordScaleY = static_cast<float>(contentRect().height()) / maskLayer->contentBounds().height(); - maskTexCoordOffsetX = static_cast<float>(contentRect().x()) / contentRect().width() * maskTexCoordScaleX; - maskTexCoordOffsetY = static_cast<float>(contentRect().y()) / contentRect().height() * maskTexCoordScaleY; - } - - CCResourceProvider::ResourceId maskResourceId = maskLayer ? maskLayer->contentsResourceId() : 0; - IntRect contentsChangedSinceLastFrame = contentsChanged() ? m_contentRect : IntRect(); - - quadSink.append(CCRenderPassDrawQuad::create(sharedQuadState, contentRect(), renderPassId, forReplica, maskResourceId, contentsChangedSinceLastFrame, - maskTexCoordScaleX, maskTexCoordScaleY, maskTexCoordOffsetX, maskTexCoordOffsetY), appendQuadsData); -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurface.h b/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurface.h deleted file mode 100644 index 2d7aaa93e..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurface.h +++ /dev/null @@ -1,151 +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 CCRenderSurface_h -#define CCRenderSurface_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCRenderPass.h" -#include "CCSharedQuadState.h" -#include "FloatRect.h" -#include "IntRect.h" -#include <public/WebTransformationMatrix.h> -#include <wtf/Noncopyable.h> -#include <wtf/text/WTFString.h> - -namespace WebCore { - -class CCDamageTracker; -class CCQuadSink; -class CCRenderPassSink; -class CCLayerImpl; -class TextStream; - -struct CCAppendQuadsData; - -class CCRenderSurface { - WTF_MAKE_NONCOPYABLE(CCRenderSurface); -public: - explicit CCRenderSurface(CCLayerImpl*); - virtual ~CCRenderSurface(); - - String name() const; - void dumpSurface(TextStream&, int indent) const; - - FloatPoint contentRectCenter() const { return FloatRect(m_contentRect).center(); } - - // Returns the rect that encloses the RenderSurface including any reflection. - FloatRect drawableContentRect() const; - - float drawOpacity() const { return m_drawOpacity; } - void setDrawOpacity(float opacity) { m_drawOpacity = opacity; } - - void setNearestAncestorThatMovesPixels(CCRenderSurface* surface) { m_nearestAncestorThatMovesPixels = surface; } - const CCRenderSurface* nearestAncestorThatMovesPixels() const { return m_nearestAncestorThatMovesPixels; } - - bool drawOpacityIsAnimating() const { return m_drawOpacityIsAnimating; } - void setDrawOpacityIsAnimating(bool drawOpacityIsAnimating) { m_drawOpacityIsAnimating = drawOpacityIsAnimating; } - - void setDrawTransform(const WebKit::WebTransformationMatrix& drawTransform) { m_drawTransform = drawTransform; } - const WebKit::WebTransformationMatrix& drawTransform() const { return m_drawTransform; } - - void setScreenSpaceTransform(const WebKit::WebTransformationMatrix& screenSpaceTransform) { m_screenSpaceTransform = screenSpaceTransform; } - const WebKit::WebTransformationMatrix& screenSpaceTransform() const { return m_screenSpaceTransform; } - - void setReplicaDrawTransform(const WebKit::WebTransformationMatrix& replicaDrawTransform) { m_replicaDrawTransform = replicaDrawTransform; } - const WebKit::WebTransformationMatrix& replicaDrawTransform() const { return m_replicaDrawTransform; } - - void setReplicaScreenSpaceTransform(const WebKit::WebTransformationMatrix& replicaScreenSpaceTransform) { m_replicaScreenSpaceTransform = replicaScreenSpaceTransform; } - const WebKit::WebTransformationMatrix& replicaScreenSpaceTransform() const { return m_replicaScreenSpaceTransform; } - - bool targetSurfaceTransformsAreAnimating() const { return m_targetSurfaceTransformsAreAnimating; } - void setTargetSurfaceTransformsAreAnimating(bool animating) { m_targetSurfaceTransformsAreAnimating = animating; } - bool screenSpaceTransformsAreAnimating() const { return m_screenSpaceTransformsAreAnimating; } - void setScreenSpaceTransformsAreAnimating(bool animating) { m_screenSpaceTransformsAreAnimating = animating; } - - void setClipRect(const IntRect&); - const IntRect& clipRect() const { return m_clipRect; } - - bool contentsChanged() const; - - void setContentRect(const IntRect&); - const IntRect& contentRect() const { return m_contentRect; } - - void clearLayerList() { m_layerList.clear(); } - Vector<CCLayerImpl*>& layerList() { return m_layerList; } - - int owningLayerId() const; - - void resetPropertyChangedFlag() { m_surfacePropertyChanged = false; } - bool surfacePropertyChanged() const; - bool surfacePropertyChangedOnlyFromDescendant() const; - - CCDamageTracker* damageTracker() const { return m_damageTracker.get(); } - - CCRenderPass::Id renderPassId(); - - void appendRenderPasses(CCRenderPassSink&); - void appendQuads(CCQuadSink&, CCAppendQuadsData&, bool forReplica, CCRenderPass::Id renderPassId); - -private: - CCLayerImpl* m_owningLayer; - - // Uses this surface's space. - IntRect m_contentRect; - bool m_surfacePropertyChanged; - - float m_drawOpacity; - bool m_drawOpacityIsAnimating; - WebKit::WebTransformationMatrix m_drawTransform; - WebKit::WebTransformationMatrix m_screenSpaceTransform; - WebKit::WebTransformationMatrix m_replicaDrawTransform; - WebKit::WebTransformationMatrix m_replicaScreenSpaceTransform; - bool m_targetSurfaceTransformsAreAnimating; - bool m_screenSpaceTransformsAreAnimating; - - // Uses the space of the surface's target surface. - IntRect m_clipRect; - - Vector<CCLayerImpl*> m_layerList; - - // The nearest ancestor target surface that will contain the contents of this surface, and that is going - // to move pixels within the surface (such as with a blur). This can point to itself. - CCRenderSurface* m_nearestAncestorThatMovesPixels; - - OwnPtr<CCDamageTracker> m_damageTracker; - - // For CCLayerIteratorActions - int m_targetRenderSurfaceLayerIndexHistory; - int m_currentLayerIndexHistory; - - friend struct CCLayerIteratorActions; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurfaceFilters.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurfaceFilters.cpp deleted file mode 100644 index b8692633b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurfaceFilters.cpp +++ /dev/null @@ -1,465 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCRenderSurfaceFilters.h" - -#include "FloatSize.h" -#include "SkBlurImageFilter.h" -#include "SkCanvas.h" -#include "SkColorMatrixFilter.h" -#include "SkGpuDevice.h" -#include "SkGrPixelRef.h" -#include "SkMagnifierImageFilter.h" -#include <public/WebFilterOperation.h> -#include <public/WebFilterOperations.h> -#include <public/WebGraphicsContext3D.h> -#include <wtf/MathExtras.h> - -namespace { - -void getBrightnessMatrix(float amount, SkScalar matrix[20]) -{ - memset(matrix, 0, 20 * sizeof(SkScalar)); - // Old implementation, a la the draft spec, a straight-up scale, - // representing <feFunc[R|G|B] type="linear" slope="[amount]"> - // (See http://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#brightnessEquivalent) - // matrix[0] = matrix[6] = matrix[12] = amount; - // matrix[18] = 1; - // New implementation, a translation in color space, representing - // <feFunc[R|G|B] type="linear" intercept="[amount]"/> - // (See https://www.w3.org/Bugs/Public/show_bug.cgi?id=15647) - matrix[0] = matrix[6] = matrix[12] = matrix[18] = 1; - matrix[4] = matrix[9] = matrix[14] = amount * 255; -} - -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; -} - -// The 5x4 matrix is really a "compressed" version of a 5x5 matrix that'd have -// (0 0 0 0 1) as a last row, and that would be applied to a 5-vector extended -// from the 4-vector color with a 1. -void multColorMatrix(SkScalar a[20], SkScalar b[20], SkScalar out[20]) -{ - for (int j = 0; j < 4; ++j) { - for (int i = 0; i < 5; ++i) { - out[i+j*5] = i == 4 ? a[4+j*5] : 0; - for (int k = 0; k < 4; ++k) - out[i+j*5] += a[k+j*5] * b[i+k*5]; - } - } -} - -// To detect if we need to apply clamping after applying a matrix, we check if -// any output component might go outside of [0, 255] for any combination of -// input components in [0..255]. -// Each output component is an affine transformation of the input component, so -// the minimum and maximum values are for any combination of minimum or maximum -// values of input components (i.e. 0 or 255). -// E.g. if R' = x*R + y*G + z*B + w*A + t -// Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the -// minimum value will be for R=0 if x>0 or R=255 if x<0. -// Same goes for all components. -bool componentNeedsClamping(SkScalar row[5]) -{ - SkScalar maxValue = row[4] / 255; - SkScalar minValue = row[4] / 255; - for (int i = 0; i < 4; ++i) { - if (row[i] > 0) - maxValue += row[i]; - else - minValue += row[i]; - } - return (maxValue > 1) || (minValue < 0); -} - -bool matrixNeedsClamping(SkScalar matrix[20]) -{ - return componentNeedsClamping(matrix) - || componentNeedsClamping(matrix+5) - || componentNeedsClamping(matrix+10) - || componentNeedsClamping(matrix+15); -} - -bool getColorMatrix(const WebKit::WebFilterOperation& op, SkScalar matrix[20]) -{ - switch (op.type()) { - case WebKit::WebFilterOperation::FilterTypeBrightness: { - getBrightnessMatrix(op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeContrast: { - getContrastMatrix(op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeGrayscale: { - getGrayscaleMatrix(1 - op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeSepia: { - getSepiaMatrix(1 - op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeSaturate: { - getSaturateMatrix(op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeHueRotate: { - getHueRotateMatrix(op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeInvert: { - getInvertMatrix(op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeOpacity: { - getOpacityMatrix(op.amount(), matrix); - return true; - } - case WebKit::WebFilterOperation::FilterTypeColorMatrix: { - memcpy(matrix, op.matrix(), sizeof(SkScalar[20])); - return true; - } - default: - return false; - } -} - -class FilterBufferState { -public: - FilterBufferState(GrContext* grContext, const WebCore::FloatSize& size, unsigned textureId) - : m_grContext(grContext) - , m_currentTexture(0) - { - // Wrap the source texture in a Ganesh platform texture. - GrPlatformTextureDesc platformTextureDescription; - platformTextureDescription.fWidth = size.width(); - platformTextureDescription.fHeight = size.height(); - platformTextureDescription.fConfig = kSkia8888_GrPixelConfig; - platformTextureDescription.fTextureHandle = textureId; - SkAutoTUnref<GrTexture> texture(grContext->createPlatformTexture(platformTextureDescription)); - // Place the platform texture inside an SkBitmap. - m_source.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height()); - m_source.setPixelRef(new SkGrPixelRef(texture.get()))->unref(); - } - - ~FilterBufferState() { } - - bool init(int filterCount) - { - int scratchCount = std::min(2, filterCount); - GrTextureDesc desc; - desc.fFlags = kRenderTarget_GrTextureFlagBit | kNoStencil_GrTextureFlagBit; - desc.fSampleCnt = 0; - desc.fWidth = m_source.width(); - desc.fHeight = m_source.height(); - desc.fConfig = kSkia8888_GrPixelConfig; - for (int i = 0; i < scratchCount; ++i) { - GrAutoScratchTexture scratchTexture(m_grContext, desc, GrContext::kExact_ScratchTexMatch); - m_scratchTextures[i].reset(scratchTexture.detach()); - if (!m_scratchTextures[i].get()) - return false; - } - return true; - } - - SkCanvas* canvas() - { - if (!m_canvas.get()) - createCanvas(); - return m_canvas.get(); - } - - const SkBitmap& source() { return m_source; } - - void swap() - { - m_canvas->flush(); - m_canvas.reset(0); - m_device.reset(0); - - m_source.setPixelRef(new SkGrPixelRef(m_scratchTextures[m_currentTexture].get()))->unref(); - m_currentTexture = 1 - m_currentTexture; - } - -private: - void createCanvas() - { - ASSERT(m_scratchTextures[m_currentTexture].get()); - m_device.reset(new SkGpuDevice(m_grContext, m_scratchTextures[m_currentTexture].get())); - m_canvas.reset(new SkCanvas(m_device.get())); - m_canvas->clear(0x0); - } - - GrContext* m_grContext; - SkBitmap m_source; - SkAutoTUnref<GrTexture> m_scratchTextures[2]; - int m_currentTexture; - SkAutoTUnref<SkGpuDevice> m_device; - SkAutoTUnref<SkCanvas> m_canvas; -}; - -} - -namespace WebCore { - -WebKit::WebFilterOperations CCRenderSurfaceFilters::optimize(const WebKit::WebFilterOperations& filters) -{ - WebKit::WebFilterOperations newList; - - SkScalar accumulatedColorMatrix[20]; - bool haveAccumulatedColorMatrix = false; - for (unsigned i = 0; i < filters.size(); ++i) { - const WebKit::WebFilterOperation& op = filters.at(i); - - // If the filter is a color matrix, we may be able to combine it with - // following filter(s) that also are color matrices. - SkScalar matrix[20]; - if (getColorMatrix(op, matrix)) { - if (haveAccumulatedColorMatrix) { - SkScalar newMatrix[20]; - multColorMatrix(matrix, accumulatedColorMatrix, newMatrix); - memcpy(accumulatedColorMatrix, newMatrix, sizeof(accumulatedColorMatrix)); - } else { - memcpy(accumulatedColorMatrix, matrix, sizeof(accumulatedColorMatrix)); - haveAccumulatedColorMatrix = true; - } - - // We can only combine matrices if clamping of color components - // would have no effect. - if (!matrixNeedsClamping(accumulatedColorMatrix)) - continue; - } - - if (haveAccumulatedColorMatrix) - newList.append(WebKit::WebFilterOperation::createColorMatrixFilter(accumulatedColorMatrix)); - haveAccumulatedColorMatrix = false; - - switch (op.type()) { - case WebKit::WebFilterOperation::FilterTypeBlur: - case WebKit::WebFilterOperation::FilterTypeDropShadow: - case WebKit::WebFilterOperation::FilterTypeZoom: - newList.append(op); - break; - case WebKit::WebFilterOperation::FilterTypeBrightness: - case WebKit::WebFilterOperation::FilterTypeContrast: - case WebKit::WebFilterOperation::FilterTypeGrayscale: - case WebKit::WebFilterOperation::FilterTypeSepia: - case WebKit::WebFilterOperation::FilterTypeSaturate: - case WebKit::WebFilterOperation::FilterTypeHueRotate: - case WebKit::WebFilterOperation::FilterTypeInvert: - case WebKit::WebFilterOperation::FilterTypeOpacity: - case WebKit::WebFilterOperation::FilterTypeColorMatrix: - break; - } - } - if (haveAccumulatedColorMatrix) - newList.append(WebKit::WebFilterOperation::createColorMatrixFilter(accumulatedColorMatrix)); - return newList; -} - -SkBitmap CCRenderSurfaceFilters::apply(const WebKit::WebFilterOperations& filters, unsigned textureId, const FloatSize& size, WebKit::WebGraphicsContext3D* context3D, GrContext* grContext) -{ - if (!context3D || !grContext) - return SkBitmap(); - - WebKit::WebFilterOperations optimizedFilters = optimize(filters); - FilterBufferState state(grContext, size, textureId); - if (!state.init(optimizedFilters.size())) - return SkBitmap(); - - for (unsigned i = 0; i < optimizedFilters.size(); ++i) { - const WebKit::WebFilterOperation& op = optimizedFilters.at(i); - SkCanvas* canvas = state.canvas(); - switch (op.type()) { - case WebKit::WebFilterOperation::FilterTypeColorMatrix: { - SkPaint paint; - paint.setColorFilter(new SkColorMatrixFilter(op.matrix()))->unref(); - canvas->drawBitmap(state.source(), 0, 0, &paint); - break; - } - case WebKit::WebFilterOperation::FilterTypeBlur: { - float stdDeviation = op.amount(); - SkAutoTUnref<SkImageFilter> filter(new SkBlurImageFilter(stdDeviation, stdDeviation)); - SkPaint paint; - paint.setImageFilter(filter.get()); - canvas->drawSprite(state.source(), 0, 0, &paint); - break; - } - case WebKit::WebFilterOperation::FilterTypeDropShadow: { - SkAutoTUnref<SkImageFilter> blurFilter(new SkBlurImageFilter(op.amount(), op.amount())); - SkAutoTUnref<SkColorFilter> colorFilter(SkColorFilter::CreateModeFilter(op.dropShadowColor(), SkXfermode::kSrcIn_Mode)); - SkPaint paint; - paint.setImageFilter(blurFilter.get()); - paint.setColorFilter(colorFilter.get()); - paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); - canvas->saveLayer(0, &paint); - canvas->drawBitmap(state.source(), op.dropShadowOffset().x, -op.dropShadowOffset().y); - canvas->restore(); - canvas->drawBitmap(state.source(), 0, 0); - break; - } - case WebKit::WebFilterOperation::FilterTypeZoom: { - SkPaint paint; - SkAutoTUnref<SkImageFilter> zoomFilter( - new SkMagnifierImageFilter( - SkRect::MakeXYWH(op.zoomRect().x, - op.zoomRect().y, - op.zoomRect().width, - op.zoomRect().height), - op.amount())); - paint.setImageFilter(zoomFilter.get()); - canvas->saveLayer(0, &paint); - canvas->drawBitmap(state.source(), 0, 0); - canvas->restore(); - break; - } - case WebKit::WebFilterOperation::FilterTypeBrightness: - case WebKit::WebFilterOperation::FilterTypeContrast: - case WebKit::WebFilterOperation::FilterTypeGrayscale: - case WebKit::WebFilterOperation::FilterTypeSepia: - case WebKit::WebFilterOperation::FilterTypeSaturate: - case WebKit::WebFilterOperation::FilterTypeHueRotate: - case WebKit::WebFilterOperation::FilterTypeInvert: - case WebKit::WebFilterOperation::FilterTypeOpacity: - ASSERT_NOT_REACHED(); - break; - } - state.swap(); - } - context3D->flush(); - return state.source(); -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurfaceFilters.h b/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurfaceFilters.h deleted file mode 100644 index 4ae97a201..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderSurfaceFilters.h +++ /dev/null @@ -1,55 +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 CCRenderSurfaceFilters_h -#define CCRenderSurfaceFilters_h - -#if USE(ACCELERATED_COMPOSITING) - -class GrContext; -class SkBitmap; - -namespace WebKit { -class WebFilterOperations; -class WebGraphicsContext3D; -} - -namespace WebCore { -class FloatSize; - -class CCRenderSurfaceFilters { -public: - static SkBitmap apply(const WebKit::WebFilterOperations& filters, unsigned textureId, const FloatSize&, WebKit::WebGraphicsContext3D*, GrContext*); - static WebKit::WebFilterOperations optimize(const WebKit::WebFilterOperations& filters); - -private: - CCRenderSurfaceFilters(); -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderer.h b/Source/WebCore/platform/graphics/chromium/cc/CCRenderer.h deleted file mode 100644 index 047bd80f3..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderer.h +++ /dev/null @@ -1,111 +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 CCRenderer_h -#define CCRenderer_h - -#include "CCLayerTreeHost.h" -#include "CCRenderPass.h" -#include "FloatQuad.h" -#include "IntRect.h" -#include <wtf/Noncopyable.h> -#include <wtf/PassRefPtr.h> - -namespace WebCore { - -class CCScopedTexture; -class TextureCopier; -class TextureUploader; - -enum TextureUploaderOption { ThrottledUploader, UnthrottledUploader }; - -class CCRendererClient { -public: - virtual const IntSize& deviceViewportSize() const = 0; - virtual const CCLayerTreeSettings& settings() const = 0; - virtual void didLoseContext() = 0; - virtual void onSwapBuffersComplete() = 0; - virtual void releaseContentsTextures() = 0; - virtual void setFullRootLayerDamage() = 0; - virtual void setMemoryAllocationLimitBytes(size_t) = 0; -protected: - virtual ~CCRendererClient() { } -}; - -class CCRenderer { - WTF_MAKE_NONCOPYABLE(CCRenderer); -public: - // This enum defines the various resource pools for the CCResourceProvider - // where textures get allocated. - enum ResourcePool { - ImplPool = 1, // This pool is for textures that get allocated on the impl thread (e.g. RenderSurfaces). - ContentPool // This pool is for textures that get allocated on the main thread (e.g. tiles). - }; - - virtual ~CCRenderer() { } - - virtual const RendererCapabilities& capabilities() const = 0; - - const CCLayerTreeSettings& settings() const { return m_client->settings(); } - - const IntSize& viewportSize() { return m_client->deviceViewportSize(); } - int viewportWidth() { return viewportSize().width(); } - int viewportHeight() { return viewportSize().height(); } - - virtual void viewportChanged() { } - - virtual void decideRenderPassAllocationsForFrame(const CCRenderPassList&) { } - virtual bool haveCachedResourcesForRenderPassId(CCRenderPass::Id) const { return false; } - - virtual void drawFrame(const CCRenderPassList&, const CCRenderPassIdHashMap&) = 0; - - // waits for rendering to finish - virtual void finish() = 0; - - virtual void doNoOp() { } - // puts backbuffer onscreen - virtual bool swapBuffers() = 0; - - virtual void getFramebufferPixels(void *pixels, const IntRect&) = 0; - - virtual TextureCopier* textureCopier() const = 0; - virtual TextureUploader* textureUploader() const = 0; - - virtual bool isContextLost() { return false; } - - virtual void setVisible(bool) = 0; - -protected: - explicit CCRenderer(CCRendererClient* client) - : m_client(client) - { - } - - CCRendererClient* m_client; -}; - -} - -#endif // CCRenderer_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRendererGL.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCRendererGL.cpp deleted file mode 100644 index 84d2c3a03..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRendererGL.cpp +++ /dev/null @@ -1,1552 +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 USE(ACCELERATED_COMPOSITING) -#include "CCRendererGL.h" - -#include "CCDamageTracker.h" -#include "CCLayerQuad.h" -#include "CCMathUtil.h" -#include "CCProxy.h" -#include "CCRenderPass.h" -#include "CCRenderSurfaceFilters.h" -#include "CCScopedTexture.h" -#include "CCSettings.h" -#include "CCSingleThreadProxy.h" -#include "CCVideoLayerImpl.h" -#include "Extensions3D.h" -#include "FloatQuad.h" -#include "GeometryBinding.h" -#include "GrTexture.h" -#include "NotImplemented.h" -#include "PlatformColor.h" -#include "SkBitmap.h" -#include "SkColor.h" -#include "ThrottledTextureUploader.h" -#include "TraceEvent.h" -#include "UnthrottledTextureUploader.h" -#include <public/WebGraphicsContext3D.h> -#include <public/WebSharedGraphicsContext3D.h> -#include <public/WebVideoFrame.h> -#include <wtf/CurrentTime.h> -#include <wtf/MainThread.h> -#include <wtf/text/StringHash.h> - -using namespace std; -using WebKit::WebGraphicsContext3D; -using WebKit::WebGraphicsMemoryAllocation; -using WebKit::WebSharedGraphicsContext3D; -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -namespace { - -bool needsIOSurfaceReadbackWorkaround() -{ -#if OS(DARWIN) - return true; -#else - return false; -#endif -} - -} // anonymous namespace - -PassOwnPtr<CCRendererGL> CCRendererGL::create(CCRendererClient* client, CCResourceProvider* resourceProvider, TextureUploaderOption textureUploaderSetting) -{ - OwnPtr<CCRendererGL> renderer(adoptPtr(new CCRendererGL(client, resourceProvider, textureUploaderSetting))); - if (!renderer->initialize()) - return nullptr; - - return renderer.release(); -} - -CCRendererGL::CCRendererGL(CCRendererClient* client, - CCResourceProvider* resourceProvider, - TextureUploaderOption textureUploaderSetting) - : CCDirectRenderer(client, resourceProvider) - , m_offscreenFramebufferId(0) - , m_sharedGeometryQuad(FloatRect(-0.5f, -0.5f, 1.0f, 1.0f)) - , m_context(resourceProvider->graphicsContext3D()) - , m_isViewportChanged(false) - , m_isFramebufferDiscarded(false) - , m_isUsingBindUniform(false) - , m_visible(true) - , m_textureUploaderSetting(textureUploaderSetting) -{ - ASSERT(m_context); -} - -bool CCRendererGL::initialize() -{ - if (!m_context->makeContextCurrent()) - return false; - - m_context->setContextLostCallback(this); - m_context->pushGroupMarkerEXT("CompositorContext"); - - WebKit::WebString extensionsWebString = m_context->getString(GraphicsContext3D::EXTENSIONS); - String extensionsString(extensionsWebString.data(), extensionsWebString.length()); - Vector<String> extensionsList; - extensionsString.split(' ', extensionsList); - HashSet<String> extensions; - for (size_t i = 0; i < extensionsList.size(); ++i) - extensions.add(extensionsList[i]); - - if (settings().acceleratePainting && extensions.contains("GL_EXT_texture_format_BGRA8888") - && extensions.contains("GL_EXT_read_format_bgra")) - m_capabilities.usingAcceleratedPainting = true; - else - m_capabilities.usingAcceleratedPainting = false; - - - m_capabilities.contextHasCachedFrontBuffer = extensions.contains("GL_CHROMIUM_front_buffer_cached"); - - m_capabilities.usingPartialSwap = CCSettings::partialSwapEnabled() && extensions.contains("GL_CHROMIUM_post_sub_buffer"); - - // Use the swapBuffers callback only with the threaded proxy. - if (CCProxy::hasImplThread()) - m_capabilities.usingSwapCompleteCallback = extensions.contains("GL_CHROMIUM_swapbuffers_complete_callback"); - if (m_capabilities.usingSwapCompleteCallback) - m_context->setSwapBuffersCompleteCallbackCHROMIUM(this); - - m_capabilities.usingSetVisibility = extensions.contains("GL_CHROMIUM_set_visibility"); - - if (extensions.contains("GL_CHROMIUM_iosurface")) - ASSERT(extensions.contains("GL_ARB_texture_rectangle")); - - m_capabilities.usingGpuMemoryManager = extensions.contains("GL_CHROMIUM_gpu_memory_manager"); - if (m_capabilities.usingGpuMemoryManager) - m_context->setMemoryAllocationChangedCallbackCHROMIUM(this); - - m_capabilities.usingDiscardFramebuffer = extensions.contains("GL_CHROMIUM_discard_framebuffer"); - - m_capabilities.usingEglImage = extensions.contains("GL_OES_EGL_image_external"); - - GLC(m_context, m_context->getIntegerv(GraphicsContext3D::MAX_TEXTURE_SIZE, &m_capabilities.maxTextureSize)); - m_capabilities.bestTextureFormat = PlatformColor::bestTextureFormat(m_context, extensions.contains("GL_EXT_texture_format_BGRA8888")); - - m_isUsingBindUniform = extensions.contains("GL_CHROMIUM_bind_uniform_location"); - - if (!initializeSharedObjects()) - return false; - - // Make sure the viewport and context gets initialized, even if it is to zero. - viewportChanged(); - return true; -} - -CCRendererGL::~CCRendererGL() -{ - ASSERT(CCProxy::isImplThread()); - m_context->setSwapBuffersCompleteCallbackCHROMIUM(0); - m_context->setMemoryAllocationChangedCallbackCHROMIUM(0); - m_context->setContextLostCallback(0); - cleanupSharedObjects(); -} - -WebGraphicsContext3D* CCRendererGL::context() -{ - return m_context; -} - -void CCRendererGL::debugGLCall(WebGraphicsContext3D* context, const char* command, const char* file, int line) -{ - unsigned long error = context->getError(); - if (error != GraphicsContext3D::NO_ERROR) - LOG_ERROR("GL command failed: File: %s\n\tLine %d\n\tcommand: %s, error %x\n", file, line, command, static_cast<int>(error)); -} - -void CCRendererGL::setVisible(bool visible) -{ - if (m_visible == visible) - return; - m_visible = visible; - - // TODO: Replace setVisibilityCHROMIUM with an extension to explicitly manage front/backbuffers - // crbug.com/116049 - if (m_capabilities.usingSetVisibility) - m_context->setVisibilityCHROMIUM(visible); -} - -void CCRendererGL::releaseRenderPassTextures() -{ - m_renderPassTextures.clear(); -} - -void CCRendererGL::viewportChanged() -{ - m_isViewportChanged = true; -} - -void CCRendererGL::clearFramebuffer(DrawingFrame& frame) -{ - // On DEBUG builds, opaque render passes are cleared to blue to easily see regions that were not drawn on the screen. - if (frame.currentRenderPass->hasTransparentBackground()) - GLC(m_context, m_context->clearColor(0, 0, 0, 0)); - else - GLC(m_context, m_context->clearColor(0, 0, 1, 1)); - -#if defined(NDEBUG) - if (frame.currentRenderPass->hasTransparentBackground()) -#endif - m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT); -} - -void CCRendererGL::beginDrawingFrame(DrawingFrame& frame) -{ - // FIXME: Remove this once framebuffer is automatically recreated on first use - ensureFramebuffer(); - - if (viewportSize().isEmpty()) - return; - - TRACE_EVENT0("cc", "CCRendererGL::drawLayers"); - if (m_isViewportChanged) { - // Only reshape when we know we are going to draw. Otherwise, the reshape - // can leave the window at the wrong size if we never draw and the proper - // viewport size is never set. - m_isViewportChanged = false; - m_context->reshape(viewportWidth(), viewportHeight()); - } - - makeContextCurrent(); - // Bind the common vertex attributes used for drawing all the layers. - m_sharedGeometry->prepareForDraw(); - - GLC(m_context, m_context->disable(GraphicsContext3D::DEPTH_TEST)); - GLC(m_context, m_context->disable(GraphicsContext3D::CULL_FACE)); - GLC(m_context, m_context->colorMask(true, true, true, true)); - GLC(m_context, m_context->enable(GraphicsContext3D::BLEND)); - GLC(m_context, m_context->blendFunc(GraphicsContext3D::ONE, GraphicsContext3D::ONE_MINUS_SRC_ALPHA)); -} - -void CCRendererGL::doNoOp() -{ - GLC(m_context, m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0)); - GLC(m_context, m_context->flush()); -} - -void CCRendererGL::drawQuad(DrawingFrame& frame, const CCDrawQuad* quad) -{ - if (quad->needsBlending()) - GLC(m_context, m_context->enable(GraphicsContext3D::BLEND)); - else - GLC(m_context, m_context->disable(GraphicsContext3D::BLEND)); - - switch (quad->material()) { - case CCDrawQuad::Invalid: - ASSERT_NOT_REACHED(); - break; - case CCDrawQuad::Checkerboard: - drawCheckerboardQuad(frame, CCCheckerboardDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::DebugBorder: - drawDebugBorderQuad(frame, CCDebugBorderDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::IOSurfaceContent: - drawIOSurfaceQuad(frame, CCIOSurfaceDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::RenderPass: - drawRenderPassQuad(frame, CCRenderPassDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::SolidColor: - drawSolidColorQuad(frame, CCSolidColorDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::StreamVideoContent: - drawStreamVideoQuad(frame, CCStreamVideoDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::TextureContent: - drawTextureQuad(frame, CCTextureDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::TiledContent: - drawTileQuad(frame, CCTileDrawQuad::materialCast(quad)); - break; - case CCDrawQuad::YUVVideoContent: - drawYUVVideoQuad(frame, CCYUVVideoDrawQuad::materialCast(quad)); - break; - } -} - -void CCRendererGL::drawCheckerboardQuad(const DrawingFrame& frame, const CCCheckerboardDrawQuad* quad) -{ - const TileCheckerboardProgram* program = tileCheckerboardProgram(); - ASSERT(program && program->initialized()); - GLC(context(), context()->useProgram(program->program())); - - IntRect tileRect = quad->quadRect(); - float texOffsetX = tileRect.x(); - float texOffsetY = tileRect.y(); - float texScaleX = tileRect.width(); - float texScaleY = tileRect.height(); - GLC(context(), context()->uniform4f(program->fragmentShader().texTransformLocation(), texOffsetX, texOffsetY, texScaleX, texScaleY)); - - const int checkerboardWidth = 16; - float frequency = 1.0 / checkerboardWidth; - - GLC(context(), context()->uniform1f(program->fragmentShader().frequencyLocation(), frequency)); - - setShaderOpacity(quad->opacity(), program->fragmentShader().alphaLocation()); - drawQuadGeometry(frame, quad->quadTransform(), quad->quadRect(), program->vertexShader().matrixLocation()); -} - -void CCRendererGL::drawDebugBorderQuad(const DrawingFrame& frame, const CCDebugBorderDrawQuad* quad) -{ - static float glMatrix[16]; - const SolidColorProgram* program = solidColorProgram(); - ASSERT(program && program->initialized()); - GLC(context(), context()->useProgram(program->program())); - - // Use the full quadRect for debug quads to not move the edges based on partial swaps. - const IntRect& layerRect = quad->quadRect(); - WebTransformationMatrix renderMatrix = quad->quadTransform(); - renderMatrix.translate(0.5 * layerRect.width() + layerRect.x(), 0.5 * layerRect.height() + layerRect.y()); - renderMatrix.scaleNonUniform(layerRect.width(), layerRect.height()); - CCRendererGL::toGLMatrix(&glMatrix[0], frame.projectionMatrix * renderMatrix); - GLC(context(), context()->uniformMatrix4fv(program->vertexShader().matrixLocation(), 1, false, &glMatrix[0])); - - SkColor color = quad->color(); - float alpha = SkColorGetA(color) / 255.0; - - GLC(context(), context()->uniform4f(program->fragmentShader().colorLocation(), (SkColorGetR(color) / 255.0) * alpha, (SkColorGetG(color) / 255.0) * alpha, (SkColorGetB(color) / 255.0) * alpha, alpha)); - - GLC(context(), context()->lineWidth(quad->width())); - - // The indices for the line are stored in the same array as the triangle indices. - GLC(context(), context()->drawElements(GraphicsContext3D::LINE_LOOP, 4, GraphicsContext3D::UNSIGNED_SHORT, 6 * sizeof(unsigned short))); -} - -static inline SkBitmap applyFilters(CCRendererGL* renderer, const WebKit::WebFilterOperations& filters, CCScopedTexture* sourceTexture) -{ - if (filters.isEmpty()) - return SkBitmap(); - - WebGraphicsContext3D* filterContext = CCProxy::hasImplThread() ? WebSharedGraphicsContext3D::compositorThreadContext() : WebSharedGraphicsContext3D::mainThreadContext(); - GrContext* filterGrContext = CCProxy::hasImplThread() ? WebSharedGraphicsContext3D::compositorThreadGrContext() : WebSharedGraphicsContext3D::mainThreadGrContext(); - - if (!filterContext || !filterGrContext) - return SkBitmap(); - - renderer->context()->flush(); - - CCResourceProvider::ScopedWriteLockGL lock(renderer->resourceProvider(), sourceTexture->id()); - SkBitmap source = CCRenderSurfaceFilters::apply(filters, lock.textureId(), sourceTexture->size(), filterContext, filterGrContext); - return source; -} - -PassOwnPtr<CCScopedTexture> CCRendererGL::drawBackgroundFilters(DrawingFrame& frame, const CCRenderPassDrawQuad* quad, const WebKit::WebFilterOperations& filters, const WebTransformationMatrix& contentsDeviceTransform) -{ - // This method draws a background filter, which applies a filter to any pixels behind the quad and seen through its background. - // The algorithm works as follows: - // 1. Compute a bounding box around the pixels that will be visible through the quad. - // 2. Read the pixels in the bounding box into a buffer R. - // 3. Apply the background filter to R, so that it is applied in the pixels' coordinate space. - // 4. Apply the quad's inverse transform to map the pixels in R into the quad's content space. This implicitly - // clips R by the content bounds of the quad since the destination texture has bounds matching the quad's content. - // 5. Draw the background texture for the contents using the same transform as used to draw the contents itself. This is done - // without blending to replace the current background pixels with the new filtered background. - // 6. Draw the contents of the quad over drop of the new background with blending, as per usual. The filtered background - // pixels will show through any non-opaque pixels in this draws. - // - // Pixel copies in this algorithm occur at steps 2, 3, 4, and 5. - - // FIXME: When this algorithm changes, update CCLayerTreeHost::prioritizeTextures() accordingly. - - if (filters.isEmpty()) - return nullptr; - - // FIXME: We only allow background filters on an opaque render surface because other surfaces may contain - // translucent pixels, and the contents behind those translucent pixels wouldn't have the filter applied. - if (frame.currentRenderPass->hasTransparentBackground()) - return nullptr; - ASSERT(!frame.currentTexture); - - // FIXME: Do a single readback for both the surface and replica and cache the filtered results (once filter textures are not reused). - IntRect deviceRect = enclosingIntRect(CCMathUtil::mapClippedRect(contentsDeviceTransform, sharedGeometryQuad().boundingBox())); - - int top, right, bottom, left; - filters.getOutsets(top, right, bottom, left); - deviceRect.move(-left, -top); - deviceRect.expand(left + right, top + bottom); - - deviceRect.intersect(frame.currentRenderPass->outputRect()); - - OwnPtr<CCScopedTexture> deviceBackgroundTexture = CCScopedTexture::create(m_resourceProvider); - if (!getFramebufferTexture(deviceBackgroundTexture.get(), deviceRect)) - return nullptr; - - SkBitmap filteredDeviceBackground = applyFilters(this, filters, deviceBackgroundTexture.get()); - if (!filteredDeviceBackground.getTexture()) - return nullptr; - - GrTexture* texture = reinterpret_cast<GrTexture*>(filteredDeviceBackground.getTexture()); - int filteredDeviceBackgroundTextureId = texture->getTextureHandle(); - - OwnPtr<CCScopedTexture> backgroundTexture = CCScopedTexture::create(m_resourceProvider); - if (!backgroundTexture->allocate(CCRenderer::ImplPool, quad->quadRect().size(), GraphicsContext3D::RGBA, CCResourceProvider::TextureUsageFramebuffer)) - return nullptr; - - const CCRenderPass* targetRenderPass = frame.currentRenderPass; - bool usingBackgroundTexture = useScopedTexture(frame, backgroundTexture.get(), quad->quadRect()); - - if (usingBackgroundTexture) { - // Copy the readback pixels from device to the background texture for the surface. - WebTransformationMatrix deviceToFramebufferTransform; - deviceToFramebufferTransform.translate(quad->quadRect().width() / 2.0, quad->quadRect().height() / 2.0); - deviceToFramebufferTransform.scale3d(quad->quadRect().width(), quad->quadRect().height(), 1); - deviceToFramebufferTransform.multiply(contentsDeviceTransform.inverse()); - copyTextureToFramebuffer(frame, filteredDeviceBackgroundTextureId, deviceRect, deviceToFramebufferTransform); - } - - useRenderPass(frame, targetRenderPass); - - if (!usingBackgroundTexture) - return nullptr; - return backgroundTexture.release(); -} - -void CCRendererGL::drawRenderPassQuad(DrawingFrame& frame, const CCRenderPassDrawQuad* quad) -{ - CachedTexture* contentsTexture = m_renderPassTextures.get(quad->renderPassId()); - if (!contentsTexture || !contentsTexture->id()) - return; - - const CCRenderPass* renderPass = frame.renderPassesById->get(quad->renderPassId()); - ASSERT(renderPass); - if (!renderPass) - return; - - WebTransformationMatrix renderMatrix = quad->quadTransform(); - renderMatrix.translate(0.5 * quad->quadRect().width() + quad->quadRect().x(), 0.5 * quad->quadRect().height() + quad->quadRect().y()); - WebTransformationMatrix deviceMatrix = renderMatrix; - deviceMatrix.scaleNonUniform(quad->quadRect().width(), quad->quadRect().height()); - WebTransformationMatrix contentsDeviceTransform = WebTransformationMatrix(frame.windowMatrix * frame.projectionMatrix * deviceMatrix).to2dTransform(); - - // Can only draw surface if device matrix is invertible. - if (!contentsDeviceTransform.isInvertible()) - return; - - OwnPtr<CCScopedTexture> backgroundTexture = drawBackgroundFilters(frame, quad, renderPass->backgroundFilters(), contentsDeviceTransform); - - // FIXME: Cache this value so that we don't have to do it for both the surface and its replica. - // Apply filters to the contents texture. - SkBitmap filterBitmap = applyFilters(this, renderPass->filters(), contentsTexture); - OwnPtr<CCResourceProvider::ScopedReadLockGL> contentsResourceLock; - unsigned contentsTextureId = 0; - if (filterBitmap.getTexture()) { - GrTexture* texture = reinterpret_cast<GrTexture*>(filterBitmap.getTexture()); - contentsTextureId = texture->getTextureHandle(); - } else { - contentsResourceLock = adoptPtr(new CCResourceProvider::ScopedReadLockGL(m_resourceProvider, contentsTexture->id())); - contentsTextureId = contentsResourceLock->textureId(); - } - - // Draw the background texture if there is one. - if (backgroundTexture) { - ASSERT(backgroundTexture->size() == quad->quadRect().size()); - CCResourceProvider::ScopedReadLockGL lock(m_resourceProvider, backgroundTexture->id()); - copyTextureToFramebuffer(frame, lock.textureId(), quad->quadRect(), quad->quadTransform()); - } - - bool clipped = false; - FloatQuad deviceQuad = CCMathUtil::mapQuad(contentsDeviceTransform, sharedGeometryQuad(), clipped); - ASSERT(!clipped); - CCLayerQuad deviceLayerBounds = CCLayerQuad(FloatQuad(deviceQuad.boundingBox())); - CCLayerQuad deviceLayerEdges = CCLayerQuad(deviceQuad); - - // Use anti-aliasing programs only when necessary. - bool useAA = (!deviceQuad.isRectilinear() || !deviceQuad.boundingBox().isExpressibleAsIntRect()); - if (useAA) { - deviceLayerBounds.inflateAntiAliasingDistance(); - deviceLayerEdges.inflateAntiAliasingDistance(); - } - - OwnPtr<CCResourceProvider::ScopedReadLockGL> maskResourceLock; - unsigned maskTextureId = 0; - if (quad->maskResourceId()) { - maskResourceLock = adoptPtr(new CCResourceProvider::ScopedReadLockGL(m_resourceProvider, quad->maskResourceId())); - maskTextureId = maskResourceLock->textureId(); - } - - // FIXME: use the backgroundTexture and blend the background in with this draw instead of having a separate copy of the background texture. - - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); - context()->bindTexture(GraphicsContext3D::TEXTURE_2D, contentsTextureId); - - int shaderQuadLocation = -1; - int shaderEdgeLocation = -1; - int shaderMaskSamplerLocation = -1; - int shaderMaskTexCoordScaleLocation = -1; - int shaderMaskTexCoordOffsetLocation = -1; - int shaderMatrixLocation = -1; - int shaderAlphaLocation = -1; - if (useAA && maskTextureId) { - const RenderPassMaskProgramAA* program = renderPassMaskProgramAA(); - GLC(context(), context()->useProgram(program->program())); - GLC(context(), context()->uniform1i(program->fragmentShader().samplerLocation(), 0)); - - shaderQuadLocation = program->vertexShader().pointLocation(); - shaderEdgeLocation = program->fragmentShader().edgeLocation(); - shaderMaskSamplerLocation = program->fragmentShader().maskSamplerLocation(); - shaderMaskTexCoordScaleLocation = program->fragmentShader().maskTexCoordScaleLocation(); - shaderMaskTexCoordOffsetLocation = program->fragmentShader().maskTexCoordOffsetLocation(); - shaderMatrixLocation = program->vertexShader().matrixLocation(); - shaderAlphaLocation = program->fragmentShader().alphaLocation(); - } else if (!useAA && maskTextureId) { - const RenderPassMaskProgram* program = renderPassMaskProgram(); - GLC(context(), context()->useProgram(program->program())); - GLC(context(), context()->uniform1i(program->fragmentShader().samplerLocation(), 0)); - - shaderMaskSamplerLocation = program->fragmentShader().maskSamplerLocation(); - shaderMaskTexCoordScaleLocation = program->fragmentShader().maskTexCoordScaleLocation(); - shaderMaskTexCoordOffsetLocation = program->fragmentShader().maskTexCoordOffsetLocation(); - shaderMatrixLocation = program->vertexShader().matrixLocation(); - shaderAlphaLocation = program->fragmentShader().alphaLocation(); - } else if (useAA && !maskTextureId) { - const RenderPassProgramAA* program = renderPassProgramAA(); - GLC(context(), context()->useProgram(program->program())); - GLC(context(), context()->uniform1i(program->fragmentShader().samplerLocation(), 0)); - - shaderQuadLocation = program->vertexShader().pointLocation(); - shaderEdgeLocation = program->fragmentShader().edgeLocation(); - shaderMatrixLocation = program->vertexShader().matrixLocation(); - shaderAlphaLocation = program->fragmentShader().alphaLocation(); - } else { - const RenderPassProgram* program = renderPassProgram(); - GLC(context(), context()->useProgram(program->program())); - GLC(context(), context()->uniform1i(program->fragmentShader().samplerLocation(), 0)); - - shaderMatrixLocation = program->vertexShader().matrixLocation(); - shaderAlphaLocation = program->fragmentShader().alphaLocation(); - } - - if (shaderMaskSamplerLocation != -1) { - ASSERT(shaderMaskTexCoordScaleLocation != 1); - ASSERT(shaderMaskTexCoordOffsetLocation != 1); - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE1)); - GLC(context(), context()->uniform1i(shaderMaskSamplerLocation, 1)); - GLC(context(), context()->uniform2f(shaderMaskTexCoordScaleLocation, quad->maskTexCoordScaleX(), quad->maskTexCoordScaleY())); - GLC(context(), context()->uniform2f(shaderMaskTexCoordOffsetLocation, quad->maskTexCoordOffsetX(), quad->maskTexCoordOffsetY())); - context()->bindTexture(GraphicsContext3D::TEXTURE_2D, maskTextureId); - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); - } - - if (shaderEdgeLocation != -1) { - float edge[24]; - deviceLayerEdges.toFloatArray(edge); - deviceLayerBounds.toFloatArray(&edge[12]); - GLC(context(), context()->uniform3fv(shaderEdgeLocation, 8, edge)); - } - - // Map device space quad to surface space. contentsDeviceTransform has no 3d component since it was generated with to2dTransform() so we don't need to project. - FloatQuad surfaceQuad = CCMathUtil::mapQuad(contentsDeviceTransform.inverse(), deviceLayerEdges.floatQuad(), clipped); - ASSERT(!clipped); - - setShaderOpacity(quad->opacity(), shaderAlphaLocation); - setShaderFloatQuad(surfaceQuad, shaderQuadLocation); - drawQuadGeometry(frame, quad->quadTransform(), quad->quadRect(), shaderMatrixLocation); -} - -void CCRendererGL::drawSolidColorQuad(const DrawingFrame& frame, const CCSolidColorDrawQuad* quad) -{ - const SolidColorProgram* program = solidColorProgram(); - GLC(context(), context()->useProgram(program->program())); - - SkColor color = quad->color(); - float opacity = quad->opacity(); - float alpha = (SkColorGetA(color) / 255.0) * opacity; - - GLC(context(), context()->uniform4f(program->fragmentShader().colorLocation(), (SkColorGetR(color) / 255.0) * alpha, (SkColorGetG(color) / 255.0) * alpha, (SkColorGetB(color) / 255.0) * alpha, alpha)); - - drawQuadGeometry(frame, quad->quadTransform(), quad->quadRect(), program->vertexShader().matrixLocation()); -} - -struct TileProgramUniforms { - unsigned program; - unsigned samplerLocation; - unsigned vertexTexTransformLocation; - unsigned fragmentTexTransformLocation; - unsigned edgeLocation; - unsigned matrixLocation; - unsigned alphaLocation; - unsigned pointLocation; -}; - -template<class T> -static void tileUniformLocation(T program, TileProgramUniforms& uniforms) -{ - uniforms.program = program->program(); - uniforms.vertexTexTransformLocation = program->vertexShader().vertexTexTransformLocation(); - uniforms.matrixLocation = program->vertexShader().matrixLocation(); - uniforms.pointLocation = program->vertexShader().pointLocation(); - - uniforms.samplerLocation = program->fragmentShader().samplerLocation(); - uniforms.alphaLocation = program->fragmentShader().alphaLocation(); - uniforms.fragmentTexTransformLocation = program->fragmentShader().fragmentTexTransformLocation(); - uniforms.edgeLocation = program->fragmentShader().edgeLocation(); -} - -void CCRendererGL::drawTileQuad(const DrawingFrame& frame, const CCTileDrawQuad* quad) -{ - IntRect tileRect = quad->quadVisibleRect(); - - FloatRect clampRect(tileRect); - // Clamp texture coordinates to avoid sampling outside the layer - // by deflating the tile region half a texel or half a texel - // minus epsilon for one pixel layers. The resulting clamp region - // is mapped to the unit square by the vertex shader and mapped - // back to normalized texture coordinates by the fragment shader - // after being clamped to 0-1 range. - const float epsilon = 1 / 1024.0f; - float clampX = min(0.5, clampRect.width() / 2.0 - epsilon); - float clampY = min(0.5, clampRect.height() / 2.0 - epsilon); - clampRect.inflateX(-clampX); - clampRect.inflateY(-clampY); - FloatSize clampOffset = clampRect.minXMinYCorner() - FloatRect(tileRect).minXMinYCorner(); - - FloatPoint textureOffset = quad->textureOffset() + clampOffset + - IntPoint(tileRect.location() - quad->quadRect().location()); - - // Map clamping rectangle to unit square. - float vertexTexTranslateX = -clampRect.x() / clampRect.width(); - float vertexTexTranslateY = -clampRect.y() / clampRect.height(); - float vertexTexScaleX = tileRect.width() / clampRect.width(); - float vertexTexScaleY = tileRect.height() / clampRect.height(); - - // Map to normalized texture coordinates. - const IntSize& textureSize = quad->textureSize(); - float fragmentTexTranslateX = textureOffset.x() / textureSize.width(); - float fragmentTexTranslateY = textureOffset.y() / textureSize.height(); - float fragmentTexScaleX = clampRect.width() / textureSize.width(); - float fragmentTexScaleY = clampRect.height() / textureSize.height(); - - - FloatQuad localQuad; - WebTransformationMatrix deviceTransform = WebTransformationMatrix(frame.windowMatrix * frame.projectionMatrix * quad->quadTransform()).to2dTransform(); - if (!deviceTransform.isInvertible()) - return; - - bool clipped = false; - FloatQuad deviceLayerQuad = CCMathUtil::mapQuad(deviceTransform, FloatQuad(quad->visibleContentRect()), clipped); - ASSERT(!clipped); - - TileProgramUniforms uniforms; - // For now, we simply skip anti-aliasing with the quad is clipped. This only happens - // on perspective transformed layers that go partially behind the camera. - if (quad->isAntialiased() && !clipped) { - if (quad->swizzleContents()) - tileUniformLocation(tileProgramSwizzleAA(), uniforms); - else - tileUniformLocation(tileProgramAA(), uniforms); - } else { - if (quad->needsBlending()) { - if (quad->swizzleContents()) - tileUniformLocation(tileProgramSwizzle(), uniforms); - else - tileUniformLocation(tileProgram(), uniforms); - } else { - if (quad->swizzleContents()) - tileUniformLocation(tileProgramSwizzleOpaque(), uniforms); - else - tileUniformLocation(tileProgramOpaque(), uniforms); - } - } - - GLC(context(), context()->useProgram(uniforms.program)); - GLC(context(), context()->uniform1i(uniforms.samplerLocation, 0)); - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); - CCResourceProvider::ScopedReadLockGL quadResourceLock(m_resourceProvider, quad->resourceId()); - GLC(context(), context()->bindTexture(GraphicsContext3D::TEXTURE_2D, quadResourceLock.textureId())); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, quad->textureFilter())); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, quad->textureFilter())); - - bool useAA = !clipped && quad->isAntialiased(); - if (useAA) { - CCLayerQuad deviceLayerBounds = CCLayerQuad(FloatQuad(deviceLayerQuad.boundingBox())); - deviceLayerBounds.inflateAntiAliasingDistance(); - - CCLayerQuad deviceLayerEdges = CCLayerQuad(deviceLayerQuad); - deviceLayerEdges.inflateAntiAliasingDistance(); - - float edge[24]; - deviceLayerEdges.toFloatArray(edge); - deviceLayerBounds.toFloatArray(&edge[12]); - GLC(context(), context()->uniform3fv(uniforms.edgeLocation, 8, edge)); - - GLC(context(), context()->uniform4f(uniforms.vertexTexTransformLocation, vertexTexTranslateX, vertexTexTranslateY, vertexTexScaleX, vertexTexScaleY)); - GLC(context(), context()->uniform4f(uniforms.fragmentTexTransformLocation, fragmentTexTranslateX, fragmentTexTranslateY, fragmentTexScaleX, fragmentTexScaleY)); - - FloatPoint bottomRight(tileRect.maxX(), tileRect.maxY()); - FloatPoint bottomLeft(tileRect.x(), tileRect.maxY()); - FloatPoint topLeft(tileRect.x(), tileRect.y()); - FloatPoint topRight(tileRect.maxX(), tileRect.y()); - - // Map points to device space. - bottomRight = CCMathUtil::mapPoint(deviceTransform, bottomRight, clipped); - ASSERT(!clipped); - bottomLeft = CCMathUtil::mapPoint(deviceTransform, bottomLeft, clipped); - ASSERT(!clipped); - topLeft = CCMathUtil::mapPoint(deviceTransform, topLeft, clipped); - ASSERT(!clipped); - topRight = CCMathUtil::mapPoint(deviceTransform, topRight, clipped); - ASSERT(!clipped); - - CCLayerQuad::Edge bottomEdge(bottomRight, bottomLeft); - CCLayerQuad::Edge leftEdge(bottomLeft, topLeft); - CCLayerQuad::Edge topEdge(topLeft, topRight); - CCLayerQuad::Edge rightEdge(topRight, bottomRight); - - // Only apply anti-aliasing to edges not clipped by culling or scissoring. - if (quad->topEdgeAA() && tileRect.y() == quad->quadRect().y()) - topEdge = deviceLayerEdges.top(); - if (quad->leftEdgeAA() && tileRect.x() == quad->quadRect().x()) - leftEdge = deviceLayerEdges.left(); - if (quad->rightEdgeAA() && tileRect.maxX() == quad->quadRect().maxX()) - rightEdge = deviceLayerEdges.right(); - if (quad->bottomEdgeAA() && tileRect.maxY() == quad->quadRect().maxY()) - bottomEdge = deviceLayerEdges.bottom(); - - float sign = FloatQuad(tileRect).isCounterclockwise() ? -1 : 1; - bottomEdge.scale(sign); - leftEdge.scale(sign); - topEdge.scale(sign); - rightEdge.scale(sign); - - // Create device space quad. - CCLayerQuad deviceQuad(leftEdge, topEdge, rightEdge, bottomEdge); - - // Map device space quad to local space. contentsDeviceTransform has no 3d component since it was generated with to2dTransform() so we don't need to project. - WebTransformationMatrix inverseDeviceTransform = deviceTransform.inverse(); - localQuad = CCMathUtil::mapQuad(inverseDeviceTransform, deviceQuad.floatQuad(), clipped); - - // We should not ASSERT(!clipped) here, because anti-aliasing inflation may cause deviceQuad to become - // clipped. To our knowledge this scenario does not need to be handled differently than the unclipped case. - } else { - // Move fragment shader transform to vertex shader. We can do this while - // still producing correct results as fragmentTexTransformLocation - // should always be non-negative when tiles are transformed in a way - // that could result in sampling outside the layer. - vertexTexScaleX *= fragmentTexScaleX; - vertexTexScaleY *= fragmentTexScaleY; - vertexTexTranslateX *= fragmentTexScaleX; - vertexTexTranslateY *= fragmentTexScaleY; - vertexTexTranslateX += fragmentTexTranslateX; - vertexTexTranslateY += fragmentTexTranslateY; - - GLC(context(), context()->uniform4f(uniforms.vertexTexTransformLocation, vertexTexTranslateX, vertexTexTranslateY, vertexTexScaleX, vertexTexScaleY)); - - localQuad = FloatRect(tileRect); - } - - // Normalize to tileRect. - localQuad.scale(1.0f / tileRect.width(), 1.0f / tileRect.height()); - - setShaderOpacity(quad->opacity(), uniforms.alphaLocation); - setShaderFloatQuad(localQuad, uniforms.pointLocation); - - // The tile quad shader behaves differently compared to all other shaders. - // The transform and vertex data are used to figure out the extents that the - // un-antialiased quad should have and which vertex this is and the float - // quad passed in via uniform is the actual geometry that gets used to draw - // it. This is why this centered rect is used and not the original quadRect. - FloatRect centeredRect(FloatPoint(-0.5 * tileRect.width(), -0.5 * tileRect.height()), tileRect.size()); - drawQuadGeometry(frame, quad->quadTransform(), centeredRect, uniforms.matrixLocation); -} - -void CCRendererGL::drawYUVVideoQuad(const DrawingFrame& frame, const CCYUVVideoDrawQuad* quad) -{ - const VideoYUVProgram* program = videoYUVProgram(); - ASSERT(program && program->initialized()); - - const CCVideoLayerImpl::FramePlane& yPlane = quad->yPlane(); - const CCVideoLayerImpl::FramePlane& uPlane = quad->uPlane(); - const CCVideoLayerImpl::FramePlane& vPlane = quad->vPlane(); - - CCResourceProvider::ScopedReadLockGL yPlaneLock(m_resourceProvider, yPlane.resourceId); - CCResourceProvider::ScopedReadLockGL uPlaneLock(m_resourceProvider, uPlane.resourceId); - CCResourceProvider::ScopedReadLockGL vPlaneLock(m_resourceProvider, vPlane.resourceId); - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE1)); - GLC(context(), context()->bindTexture(GraphicsContext3D::TEXTURE_2D, yPlaneLock.textureId())); - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE2)); - GLC(context(), context()->bindTexture(GraphicsContext3D::TEXTURE_2D, uPlaneLock.textureId())); - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE3)); - GLC(context(), context()->bindTexture(GraphicsContext3D::TEXTURE_2D, vPlaneLock.textureId())); - - GLC(context(), context()->useProgram(program->program())); - - float yWidthScaleFactor = static_cast<float>(yPlane.visibleSize.width()) / yPlane.size.width(); - // Arbitrarily take the u sizes because u and v dimensions are identical. - float uvWidthScaleFactor = static_cast<float>(uPlane.visibleSize.width()) / uPlane.size.width(); - GLC(context(), context()->uniform1f(program->vertexShader().yWidthScaleFactorLocation(), yWidthScaleFactor)); - GLC(context(), context()->uniform1f(program->vertexShader().uvWidthScaleFactorLocation(), uvWidthScaleFactor)); - - GLC(context(), context()->uniform1i(program->fragmentShader().yTextureLocation(), 1)); - GLC(context(), context()->uniform1i(program->fragmentShader().uTextureLocation(), 2)); - GLC(context(), context()->uniform1i(program->fragmentShader().vTextureLocation(), 3)); - - // These values are magic numbers that are used in the transformation from YUV to RGB color values. - // They are taken from the following webpage: http://www.fourcc.org/fccyvrgb.php - float yuv2RGB[9] = { - 1.164f, 1.164f, 1.164f, - 0.f, -.391f, 2.018f, - 1.596f, -.813f, 0.f, - }; - GLC(context(), context()->uniformMatrix3fv(program->fragmentShader().ccMatrixLocation(), 1, 0, yuv2RGB)); - - // These values map to 16, 128, and 128 respectively, and are computed - // as a fraction over 256 (e.g. 16 / 256 = 0.0625). - // They are used in the YUV to RGBA conversion formula: - // Y - 16 : Gives 16 values of head and footroom for overshooting - // U - 128 : Turns unsigned U into signed U [-128,127] - // V - 128 : Turns unsigned V into signed V [-128,127] - float yuvAdjust[3] = { - -0.0625f, - -0.5f, - -0.5f, - }; - GLC(context(), context()->uniform3fv(program->fragmentShader().yuvAdjLocation(), 1, yuvAdjust)); - - setShaderOpacity(quad->opacity(), program->fragmentShader().alphaLocation()); - drawQuadGeometry(frame, quad->quadTransform(), quad->quadRect(), program->vertexShader().matrixLocation()); - - // Reset active texture back to texture 0. - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); -} - -void CCRendererGL::drawStreamVideoQuad(const DrawingFrame& frame, const CCStreamVideoDrawQuad* quad) -{ - static float glMatrix[16]; - - ASSERT(m_capabilities.usingEglImage); - - const VideoStreamTextureProgram* program = videoStreamTextureProgram(); - GLC(context(), context()->useProgram(program->program())); - - toGLMatrix(&glMatrix[0], quad->matrix()); - GLC(context(), context()->uniformMatrix4fv(program->vertexShader().texMatrixLocation(), 1, false, glMatrix)); - - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); - GLC(context(), context()->bindTexture(Extensions3DChromium::GL_TEXTURE_EXTERNAL_OES, quad->textureId())); - - GLC(context(), context()->uniform1i(program->fragmentShader().samplerLocation(), 0)); - - setShaderOpacity(quad->opacity(), program->fragmentShader().alphaLocation()); - drawQuadGeometry(frame, quad->quadTransform(), quad->quadRect(), program->vertexShader().matrixLocation()); -} - -struct TextureProgramBinding { - template<class Program> void set(Program* program) - { - ASSERT(program && program->initialized()); - programId = program->program(); - samplerLocation = program->fragmentShader().samplerLocation(); - matrixLocation = program->vertexShader().matrixLocation(); - alphaLocation = program->fragmentShader().alphaLocation(); - } - int programId; - int samplerLocation; - int matrixLocation; - int alphaLocation; -}; - -struct TexTransformTextureProgramBinding : TextureProgramBinding { - template<class Program> void set(Program* program) - { - TextureProgramBinding::set(program); - texTransformLocation = program->vertexShader().texTransformLocation(); - } - int texTransformLocation; -}; - -void CCRendererGL::drawTextureQuad(const DrawingFrame& frame, const CCTextureDrawQuad* quad) -{ - ASSERT(CCProxy::isImplThread()); - - TexTransformTextureProgramBinding binding; - if (quad->flipped()) - binding.set(textureProgramFlip()); - else - binding.set(textureProgram()); - GLC(context(), context()->useProgram(binding.programId)); - GLC(context(), context()->uniform1i(binding.samplerLocation, 0)); - const FloatRect& uvRect = quad->uvRect(); - GLC(context(), context()->uniform4f(binding.texTransformLocation, uvRect.x(), uvRect.y(), uvRect.width(), uvRect.height())); - - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); - CCResourceProvider::ScopedReadLockGL quadResourceLock(m_resourceProvider, quad->resourceId()); - GLC(context(), context()->bindTexture(GraphicsContext3D::TEXTURE_2D, quadResourceLock.textureId())); - - // FIXME: setting the texture parameters every time is redundant. Move this code somewhere - // where it will only happen once per texture. - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR)); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR)); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE)); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE)); - - if (!quad->premultipliedAlpha()) { - // As it turns out, the premultiplied alpha blending function (ONE, ONE_MINUS_SRC_ALPHA) - // will never cause the alpha channel to be set to anything less than 1.0 if it is - // initialized to that value! Therefore, premultipliedAlpha being false is the first - // situation we can generally see an alpha channel less than 1.0 coming out of the - // compositor. This is causing platform differences in some layout tests (see - // https://bugs.webkit.org/show_bug.cgi?id=82412), so in this situation, use a separate - // blend function for the alpha channel to avoid modifying it. Don't use colorMask for this - // as it has performance implications on some platforms. - GLC(context(), context()->blendFuncSeparate(GraphicsContext3D::SRC_ALPHA, GraphicsContext3D::ONE_MINUS_SRC_ALPHA, GraphicsContext3D::ZERO, GraphicsContext3D::ONE)); - } - - setShaderOpacity(quad->opacity(), binding.alphaLocation); - drawQuadGeometry(frame, quad->quadTransform(), quad->quadRect(), binding.matrixLocation); - - if (!quad->premultipliedAlpha()) - GLC(m_context, m_context->blendFunc(GraphicsContext3D::ONE, GraphicsContext3D::ONE_MINUS_SRC_ALPHA)); -} - -void CCRendererGL::drawIOSurfaceQuad(const DrawingFrame& frame, const CCIOSurfaceDrawQuad* quad) -{ - ASSERT(CCProxy::isImplThread()); - TexTransformTextureProgramBinding binding; - binding.set(textureIOSurfaceProgram()); - - GLC(context(), context()->useProgram(binding.programId)); - GLC(context(), context()->uniform1i(binding.samplerLocation, 0)); - if (quad->orientation() == CCIOSurfaceDrawQuad::Flipped) - GLC(context(), context()->uniform4f(binding.texTransformLocation, 0, quad->ioSurfaceSize().height(), quad->ioSurfaceSize().width(), quad->ioSurfaceSize().height() * -1.0)); - else - GLC(context(), context()->uniform4f(binding.texTransformLocation, 0, 0, quad->ioSurfaceSize().width(), quad->ioSurfaceSize().height())); - - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); - GLC(context(), context()->bindTexture(Extensions3D::TEXTURE_RECTANGLE_ARB, quad->ioSurfaceTextureId())); - - setShaderOpacity(quad->opacity(), binding.alphaLocation); - drawQuadGeometry(frame, quad->quadTransform(), quad->quadRect(), binding.matrixLocation); - - GLC(context(), context()->bindTexture(Extensions3D::TEXTURE_RECTANGLE_ARB, 0)); -} - -void CCRendererGL::finishDrawingFrame(DrawingFrame& frame) -{ - m_currentFramebufferLock.clear(); - m_swapBufferRect.unite(enclosingIntRect(frame.rootDamageRect)); - - GLC(m_context, m_context->disable(GraphicsContext3D::SCISSOR_TEST)); - GLC(m_context, m_context->disable(GraphicsContext3D::BLEND)); -} - -void CCRendererGL::toGLMatrix(float* flattened, const WebTransformationMatrix& m) -{ - flattened[0] = m.m11(); - flattened[1] = m.m12(); - flattened[2] = m.m13(); - flattened[3] = m.m14(); - flattened[4] = m.m21(); - flattened[5] = m.m22(); - flattened[6] = m.m23(); - flattened[7] = m.m24(); - flattened[8] = m.m31(); - flattened[9] = m.m32(); - flattened[10] = m.m33(); - flattened[11] = m.m34(); - flattened[12] = m.m41(); - flattened[13] = m.m42(); - flattened[14] = m.m43(); - flattened[15] = m.m44(); -} - -void CCRendererGL::setShaderFloatQuad(const FloatQuad& quad, int quadLocation) -{ - if (quadLocation == -1) - return; - - float point[8]; - point[0] = quad.p1().x(); - point[1] = quad.p1().y(); - point[2] = quad.p2().x(); - point[3] = quad.p2().y(); - point[4] = quad.p3().x(); - point[5] = quad.p3().y(); - point[6] = quad.p4().x(); - point[7] = quad.p4().y(); - GLC(m_context, m_context->uniform2fv(quadLocation, 4, point)); -} - -void CCRendererGL::setShaderOpacity(float opacity, int alphaLocation) -{ - if (alphaLocation != -1) - GLC(m_context, m_context->uniform1f(alphaLocation, opacity)); -} - -void CCRendererGL::drawQuadGeometry(const DrawingFrame& frame, const WebKit::WebTransformationMatrix& drawTransform, const FloatRect& quadRect, int matrixLocation) -{ - WebTransformationMatrix quadRectMatrix; - quadRectTransform(&quadRectMatrix, drawTransform, quadRect); - static float glMatrix[16]; - toGLMatrix(&glMatrix[0], frame.projectionMatrix * quadRectMatrix); - GLC(m_context, m_context->uniformMatrix4fv(matrixLocation, 1, false, &glMatrix[0])); - - GLC(m_context, m_context->drawElements(GraphicsContext3D::TRIANGLES, 6, GraphicsContext3D::UNSIGNED_SHORT, 0)); -} - -void CCRendererGL::copyTextureToFramebuffer(const DrawingFrame& frame, int textureId, const IntRect& rect, const WebTransformationMatrix& drawMatrix) -{ - const RenderPassProgram* program = renderPassProgram(); - - GLC(context(), context()->activeTexture(GraphicsContext3D::TEXTURE0)); - GLC(context(), context()->bindTexture(GraphicsContext3D::TEXTURE_2D, textureId)); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR)); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR)); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE)); - GLC(context(), context()->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE)); - - GLC(context(), context()->useProgram(program->program())); - GLC(context(), context()->uniform1i(program->fragmentShader().samplerLocation(), 0)); - setShaderOpacity(1, program->fragmentShader().alphaLocation()); - drawQuadGeometry(frame, drawMatrix, rect, program->vertexShader().matrixLocation()); -} - -void CCRendererGL::finish() -{ - TRACE_EVENT0("cc", "CCRendererGL::finish"); - m_context->finish(); -} - -bool CCRendererGL::swapBuffers() -{ - ASSERT(m_visible); - ASSERT(!m_isFramebufferDiscarded); - - TRACE_EVENT0("cc", "CCRendererGL::swapBuffers"); - // We're done! Time to swapbuffers! - - if (m_capabilities.usingPartialSwap) { - // If supported, we can save significant bandwidth by only swapping the damaged/scissored region (clamped to the viewport) - m_swapBufferRect.intersect(IntRect(IntPoint(), viewportSize())); - int flippedYPosOfRectBottom = viewportHeight() - m_swapBufferRect.y() - m_swapBufferRect.height(); - m_context->postSubBufferCHROMIUM(m_swapBufferRect.x(), flippedYPosOfRectBottom, m_swapBufferRect.width(), m_swapBufferRect.height()); - } else { - // Note that currently this has the same effect as swapBuffers; we should - // consider exposing a different entry point on WebGraphicsContext3D. - m_context->prepareTexture(); - } - - m_swapBufferRect = IntRect(); - - return true; -} - -void CCRendererGL::onSwapBuffersComplete() -{ - m_client->onSwapBuffersComplete(); -} - -void CCRendererGL::onMemoryAllocationChanged(WebGraphicsMemoryAllocation allocation) -{ - // FIXME: This is called on the main thread in single threaded mode, but we expect it on the impl thread. - if (!CCProxy::hasImplThread()) { - ASSERT(CCProxy::isMainThread()); - DebugScopedSetImplThread impl; - onMemoryAllocationChangedOnImplThread(allocation); - } else { - ASSERT(CCProxy::isImplThread()); - onMemoryAllocationChangedOnImplThread(allocation); - } -} - -void CCRendererGL::onMemoryAllocationChangedOnImplThread(WebKit::WebGraphicsMemoryAllocation allocation) -{ - if (m_visible && !allocation.gpuResourceSizeInBytes) - return; - - if (!allocation.suggestHaveBackbuffer && !m_visible) - discardFramebuffer(); - - if (!allocation.gpuResourceSizeInBytes) { - releaseRenderPassTextures(); - m_client->releaseContentsTextures(); - GLC(m_context, m_context->flush()); - } else - m_client->setMemoryAllocationLimitBytes(allocation.gpuResourceSizeInBytes); -} - -void CCRendererGL::discardFramebuffer() -{ - if (m_isFramebufferDiscarded) - return; - - if (!m_capabilities.usingDiscardFramebuffer) - return; - - // FIXME: Update attachments argument to appropriate values once they are no longer ignored. - m_context->discardFramebufferEXT(GraphicsContext3D::TEXTURE_2D, 0, 0); - m_isFramebufferDiscarded = true; - - // Damage tracker needs a full reset every time framebuffer is discarded. - m_client->setFullRootLayerDamage(); -} - -void CCRendererGL::ensureFramebuffer() -{ - if (!m_isFramebufferDiscarded) - return; - - if (!m_capabilities.usingDiscardFramebuffer) - return; - - m_context->ensureFramebufferCHROMIUM(); - m_isFramebufferDiscarded = false; -} - -void CCRendererGL::onContextLost() -{ - m_client->didLoseContext(); -} - - -void CCRendererGL::getFramebufferPixels(void *pixels, const IntRect& rect) -{ - ASSERT(rect.maxX() <= viewportWidth() && rect.maxY() <= viewportHeight()); - - if (!pixels) - return; - - makeContextCurrent(); - - bool doWorkaround = needsIOSurfaceReadbackWorkaround(); - - Platform3DObject temporaryTexture = 0; - Platform3DObject temporaryFBO = 0; - - if (doWorkaround) { - // On Mac OS X, calling glReadPixels against an FBO whose color attachment is an - // IOSurface-backed texture causes corruption of future glReadPixels calls, even those on - // different OpenGL contexts. It is believed that this is the root cause of top crasher - // http://crbug.com/99393. <rdar://problem/10949687> - - temporaryTexture = m_context->createTexture(); - GLC(m_context, m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, temporaryTexture)); - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR)); - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR)); - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE)); - GLC(m_context, m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE)); - // Copy the contents of the current (IOSurface-backed) framebuffer into a temporary texture. - GLC(m_context, m_context->copyTexImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, 0, 0, viewportSize().width(), viewportSize().height(), 0)); - temporaryFBO = m_context->createFramebuffer(); - // Attach this texture to an FBO, and perform the readback from that FBO. - GLC(m_context, m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, temporaryFBO)); - GLC(m_context, m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, temporaryTexture, 0)); - - ASSERT(m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) == GraphicsContext3D::FRAMEBUFFER_COMPLETE); - } - - OwnPtr<uint8_t> srcPixels = adoptPtr(new uint8_t[rect.width() * rect.height() * 4]); - GLC(m_context, m_context->readPixels(rect.x(), viewportSize().height() - rect.maxY(), rect.width(), rect.height(), - GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, srcPixels.get())); - - uint8_t* destPixels = static_cast<uint8_t*>(pixels); - size_t rowBytes = rect.width() * 4; - int numRows = rect.height(); - size_t totalBytes = numRows * rowBytes; - for (size_t destY = 0; destY < totalBytes; destY += rowBytes) { - // Flip Y axis. - size_t srcY = totalBytes - destY - rowBytes; - // Swizzle BGRA -> RGBA. - for (size_t x = 0; x < rowBytes; x += 4) { - destPixels[destY + (x+0)] = srcPixels.get()[srcY + (x+2)]; - destPixels[destY + (x+1)] = srcPixels.get()[srcY + (x+1)]; - destPixels[destY + (x+2)] = srcPixels.get()[srcY + (x+0)]; - destPixels[destY + (x+3)] = srcPixels.get()[srcY + (x+3)]; - } - } - - if (doWorkaround) { - // Clean up. - GLC(m_context, m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0)); - GLC(m_context, m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, 0)); - GLC(m_context, m_context->deleteFramebuffer(temporaryFBO)); - GLC(m_context, m_context->deleteTexture(temporaryTexture)); - } - - if (!m_visible) { - TRACE_EVENT0("cc", "CCRendererGL::getFramebufferPixels dropping resources after readback"); - discardFramebuffer(); - releaseRenderPassTextures(); - m_client->releaseContentsTextures(); - GLC(m_context, m_context->flush()); - } -} - -bool CCRendererGL::getFramebufferTexture(CCScopedTexture* texture, const IntRect& deviceRect) -{ - ASSERT(!texture->id() || (texture->size() == deviceRect.size() && texture->format() == GraphicsContext3D::RGB)); - - if (!texture->id() && !texture->allocate(CCRenderer::ImplPool, deviceRect.size(), GraphicsContext3D::RGB, CCResourceProvider::TextureUsageAny)) - return false; - - CCResourceProvider::ScopedWriteLockGL lock(m_resourceProvider, texture->id()); - GLC(m_context, m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, lock.textureId())); - GLC(m_context, m_context->copyTexImage2D(GraphicsContext3D::TEXTURE_2D, 0, texture->format(), - deviceRect.x(), deviceRect.y(), deviceRect.width(), deviceRect.height(), 0)); - return true; -} - -bool CCRendererGL::useScopedTexture(DrawingFrame& frame, const CCScopedTexture* texture, const IntRect& viewportRect) -{ - ASSERT(texture->id()); - frame.currentRenderPass = 0; - frame.currentTexture = texture; - - return bindFramebufferToTexture(frame, texture, viewportRect); -} - -void CCRendererGL::bindFramebufferToOutputSurface(DrawingFrame& frame) -{ - m_currentFramebufferLock.clear(); - GLC(m_context, m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0)); -} - -bool CCRendererGL::bindFramebufferToTexture(DrawingFrame& frame, const CCScopedTexture* texture, const IntRect& framebufferRect) -{ - ASSERT(texture->id()); - - GLC(m_context, m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_offscreenFramebufferId)); - m_currentFramebufferLock = adoptPtr(new CCResourceProvider::ScopedWriteLockGL(m_resourceProvider, texture->id())); - unsigned textureId = m_currentFramebufferLock->textureId(); - GLC(m_context, m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, textureId, 0)); - -#if !defined ( NDEBUG ) - if (m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) { - ASSERT_NOT_REACHED(); - return false; - } -#endif - - initializeMatrices(frame, framebufferRect, false); - setDrawViewportSize(framebufferRect.size()); - - return true; -} - -void CCRendererGL::enableScissorTestRect(const IntRect& scissorRect) -{ - GLC(m_context, m_context->enable(GraphicsContext3D::SCISSOR_TEST)); - GLC(m_context, m_context->scissor(scissorRect.x(), scissorRect.y(), scissorRect.width(), scissorRect.height())); -} - -void CCRendererGL::disableScissorTest() -{ - GLC(m_context, m_context->disable(GraphicsContext3D::SCISSOR_TEST)); -} - -void CCRendererGL::setDrawViewportSize(const IntSize& viewportSize) -{ - GLC(m_context, m_context->viewport(0, 0, viewportSize.width(), viewportSize.height())); -} - -bool CCRendererGL::makeContextCurrent() -{ - return m_context->makeContextCurrent(); -} - -bool CCRendererGL::initializeSharedObjects() -{ - TRACE_EVENT0("cc", "CCRendererGL::initializeSharedObjects"); - makeContextCurrent(); - - // Create an FBO for doing offscreen rendering. - GLC(m_context, m_offscreenFramebufferId = m_context->createFramebuffer()); - - // We will always need these programs to render, so create the programs eagerly so that the shader compilation can - // start while we do other work. Other programs are created lazily on first access. - m_sharedGeometry = adoptPtr(new GeometryBinding(m_context, quadVertexRect())); - m_renderPassProgram = adoptPtr(new RenderPassProgram(m_context)); - m_tileProgram = adoptPtr(new TileProgram(m_context)); - m_tileProgramOpaque = adoptPtr(new TileProgramOpaque(m_context)); - - GLC(m_context, m_context->flush()); - - m_textureCopier = AcceleratedTextureCopier::create(m_context, m_isUsingBindUniform); - if (m_textureUploaderSetting == ThrottledUploader) - m_textureUploader = ThrottledTextureUploader::create(m_context); - else - m_textureUploader = UnthrottledTextureUploader::create(); - - return true; -} - -const CCRendererGL::TileCheckerboardProgram* CCRendererGL::tileCheckerboardProgram() -{ - if (!m_tileCheckerboardProgram) - m_tileCheckerboardProgram = adoptPtr(new TileCheckerboardProgram(m_context)); - if (!m_tileCheckerboardProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::checkerboardProgram::initalize"); - m_tileCheckerboardProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_tileCheckerboardProgram.get(); -} - -const CCRendererGL::SolidColorProgram* CCRendererGL::solidColorProgram() -{ - if (!m_solidColorProgram) - m_solidColorProgram = adoptPtr(new SolidColorProgram(m_context)); - if (!m_solidColorProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::solidColorProgram::initialize"); - m_solidColorProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_solidColorProgram.get(); -} - -const CCRendererGL::RenderPassProgram* CCRendererGL::renderPassProgram() -{ - ASSERT(m_renderPassProgram); - if (!m_renderPassProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::renderPassProgram::initialize"); - m_renderPassProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_renderPassProgram.get(); -} - -const CCRendererGL::RenderPassProgramAA* CCRendererGL::renderPassProgramAA() -{ - if (!m_renderPassProgramAA) - m_renderPassProgramAA = adoptPtr(new RenderPassProgramAA(m_context)); - if (!m_renderPassProgramAA->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::renderPassProgramAA::initialize"); - m_renderPassProgramAA->initialize(m_context, m_isUsingBindUniform); - } - return m_renderPassProgramAA.get(); -} - -const CCRendererGL::RenderPassMaskProgram* CCRendererGL::renderPassMaskProgram() -{ - if (!m_renderPassMaskProgram) - m_renderPassMaskProgram = adoptPtr(new RenderPassMaskProgram(m_context)); - if (!m_renderPassMaskProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::renderPassMaskProgram::initialize"); - m_renderPassMaskProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_renderPassMaskProgram.get(); -} - -const CCRendererGL::RenderPassMaskProgramAA* CCRendererGL::renderPassMaskProgramAA() -{ - if (!m_renderPassMaskProgramAA) - m_renderPassMaskProgramAA = adoptPtr(new RenderPassMaskProgramAA(m_context)); - if (!m_renderPassMaskProgramAA->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::renderPassMaskProgramAA::initialize"); - m_renderPassMaskProgramAA->initialize(m_context, m_isUsingBindUniform); - } - return m_renderPassMaskProgramAA.get(); -} - -const CCRendererGL::TileProgram* CCRendererGL::tileProgram() -{ - ASSERT(m_tileProgram); - if (!m_tileProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::tileProgram::initialize"); - m_tileProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_tileProgram.get(); -} - -const CCRendererGL::TileProgramOpaque* CCRendererGL::tileProgramOpaque() -{ - ASSERT(m_tileProgramOpaque); - if (!m_tileProgramOpaque->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::tileProgramOpaque::initialize"); - m_tileProgramOpaque->initialize(m_context, m_isUsingBindUniform); - } - return m_tileProgramOpaque.get(); -} - -const CCRendererGL::TileProgramAA* CCRendererGL::tileProgramAA() -{ - if (!m_tileProgramAA) - m_tileProgramAA = adoptPtr(new TileProgramAA(m_context)); - if (!m_tileProgramAA->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::tileProgramAA::initialize"); - m_tileProgramAA->initialize(m_context, m_isUsingBindUniform); - } - return m_tileProgramAA.get(); -} - -const CCRendererGL::TileProgramSwizzle* CCRendererGL::tileProgramSwizzle() -{ - if (!m_tileProgramSwizzle) - m_tileProgramSwizzle = adoptPtr(new TileProgramSwizzle(m_context)); - if (!m_tileProgramSwizzle->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::tileProgramSwizzle::initialize"); - m_tileProgramSwizzle->initialize(m_context, m_isUsingBindUniform); - } - return m_tileProgramSwizzle.get(); -} - -const CCRendererGL::TileProgramSwizzleOpaque* CCRendererGL::tileProgramSwizzleOpaque() -{ - if (!m_tileProgramSwizzleOpaque) - m_tileProgramSwizzleOpaque = adoptPtr(new TileProgramSwizzleOpaque(m_context)); - if (!m_tileProgramSwizzleOpaque->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::tileProgramSwizzleOpaque::initialize"); - m_tileProgramSwizzleOpaque->initialize(m_context, m_isUsingBindUniform); - } - return m_tileProgramSwizzleOpaque.get(); -} - -const CCRendererGL::TileProgramSwizzleAA* CCRendererGL::tileProgramSwizzleAA() -{ - if (!m_tileProgramSwizzleAA) - m_tileProgramSwizzleAA = adoptPtr(new TileProgramSwizzleAA(m_context)); - if (!m_tileProgramSwizzleAA->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::tileProgramSwizzleAA::initialize"); - m_tileProgramSwizzleAA->initialize(m_context, m_isUsingBindUniform); - } - return m_tileProgramSwizzleAA.get(); -} - -const CCRendererGL::TextureProgram* CCRendererGL::textureProgram() -{ - if (!m_textureProgram) - m_textureProgram = adoptPtr(new TextureProgram(m_context)); - if (!m_textureProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::textureProgram::initialize"); - m_textureProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_textureProgram.get(); -} - -const CCRendererGL::TextureProgramFlip* CCRendererGL::textureProgramFlip() -{ - if (!m_textureProgramFlip) - m_textureProgramFlip = adoptPtr(new TextureProgramFlip(m_context)); - if (!m_textureProgramFlip->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::textureProgramFlip::initialize"); - m_textureProgramFlip->initialize(m_context, m_isUsingBindUniform); - } - return m_textureProgramFlip.get(); -} - -const CCRendererGL::TextureIOSurfaceProgram* CCRendererGL::textureIOSurfaceProgram() -{ - if (!m_textureIOSurfaceProgram) - m_textureIOSurfaceProgram = adoptPtr(new TextureIOSurfaceProgram(m_context)); - if (!m_textureIOSurfaceProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::textureIOSurfaceProgram::initialize"); - m_textureIOSurfaceProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_textureIOSurfaceProgram.get(); -} - -const CCRendererGL::VideoYUVProgram* CCRendererGL::videoYUVProgram() -{ - if (!m_videoYUVProgram) - m_videoYUVProgram = adoptPtr(new VideoYUVProgram(m_context)); - if (!m_videoYUVProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::videoYUVProgram::initialize"); - m_videoYUVProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_videoYUVProgram.get(); -} - -const CCRendererGL::VideoStreamTextureProgram* CCRendererGL::videoStreamTextureProgram() -{ - if (!m_videoStreamTextureProgram) - m_videoStreamTextureProgram = adoptPtr(new VideoStreamTextureProgram(m_context)); - if (!m_videoStreamTextureProgram->initialized()) { - TRACE_EVENT0("cc", "CCRendererGL::streamTextureProgram::initialize"); - m_videoStreamTextureProgram->initialize(m_context, m_isUsingBindUniform); - } - return m_videoStreamTextureProgram.get(); -} - -void CCRendererGL::cleanupSharedObjects() -{ - makeContextCurrent(); - - m_sharedGeometry.clear(); - - if (m_tileProgram) - m_tileProgram->cleanup(m_context); - if (m_tileProgramOpaque) - m_tileProgramOpaque->cleanup(m_context); - if (m_tileProgramSwizzle) - m_tileProgramSwizzle->cleanup(m_context); - if (m_tileProgramSwizzleOpaque) - m_tileProgramSwizzleOpaque->cleanup(m_context); - if (m_tileProgramAA) - m_tileProgramAA->cleanup(m_context); - if (m_tileProgramSwizzleAA) - m_tileProgramSwizzleAA->cleanup(m_context); - if (m_tileCheckerboardProgram) - m_tileCheckerboardProgram->cleanup(m_context); - - if (m_renderPassMaskProgram) - m_renderPassMaskProgram->cleanup(m_context); - if (m_renderPassProgram) - m_renderPassProgram->cleanup(m_context); - if (m_renderPassMaskProgramAA) - m_renderPassMaskProgramAA->cleanup(m_context); - if (m_renderPassProgramAA) - m_renderPassProgramAA->cleanup(m_context); - - if (m_textureProgram) - m_textureProgram->cleanup(m_context); - if (m_textureProgramFlip) - m_textureProgramFlip->cleanup(m_context); - if (m_textureIOSurfaceProgram) - m_textureIOSurfaceProgram->cleanup(m_context); - - if (m_videoYUVProgram) - m_videoYUVProgram->cleanup(m_context); - if (m_videoStreamTextureProgram) - m_videoStreamTextureProgram->cleanup(m_context); - - if (m_solidColorProgram) - m_solidColorProgram->cleanup(m_context); - - if (m_offscreenFramebufferId) - GLC(m_context, m_context->deleteFramebuffer(m_offscreenFramebufferId)); - - m_textureCopier.clear(); - m_textureUploader.clear(); - - releaseRenderPassTextures(); -} - -bool CCRendererGL::isContextLost() -{ - return (m_context->getGraphicsResetStatusARB() != GraphicsContext3D::NO_ERROR); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRendererGL.h b/Source/WebCore/platform/graphics/chromium/cc/CCRendererGL.h deleted file mode 100644 index 832503352..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRendererGL.h +++ /dev/null @@ -1,271 +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 CCRendererGL_h -#define CCRendererGL_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCCheckerboardDrawQuad.h" -#include "CCDebugBorderDrawQuad.h" -#include "CCDirectRenderer.h" -#include "CCIOSurfaceDrawQuad.h" -#include "CCRenderPassDrawQuad.h" -#include "CCRenderer.h" -#include "CCSolidColorDrawQuad.h" -#include "CCStreamVideoDrawQuad.h" -#include "CCTextureDrawQuad.h" -#include "CCTileDrawQuad.h" -#include "CCYUVVideoDrawQuad.h" -#include "Extensions3DChromium.h" -#include "TextureCopier.h" -#include <wtf/PassOwnPtr.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class CCScopedTexture; -class GeometryBinding; -class ScopedEnsureFramebufferAllocation; - -// Class that handles drawing of composited render layers using GL. -class CCRendererGL : public CCDirectRenderer, - public WebKit::WebGraphicsContext3D::WebGraphicsSwapBuffersCompleteCallbackCHROMIUM, - public WebKit::WebGraphicsContext3D::WebGraphicsMemoryAllocationChangedCallbackCHROMIUM , - public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback { - WTF_MAKE_NONCOPYABLE(CCRendererGL); -public: - static PassOwnPtr<CCRendererGL> create(CCRendererClient*, CCResourceProvider*, TextureUploaderOption); - - virtual ~CCRendererGL(); - - virtual const RendererCapabilities& capabilities() const OVERRIDE { return m_capabilities; } - - WebKit::WebGraphicsContext3D* context(); - - virtual void viewportChanged() OVERRIDE; - - const FloatQuad& sharedGeometryQuad() const { return m_sharedGeometryQuad; } - - // waits for rendering to finish - virtual void finish() OVERRIDE; - - virtual void doNoOp() OVERRIDE; - // puts backbuffer onscreen - virtual bool swapBuffers() OVERRIDE; - - static void debugGLCall(WebKit::WebGraphicsContext3D*, const char* command, const char* file, int line); - - const GeometryBinding* sharedGeometry() const { return m_sharedGeometry.get(); } - - virtual void getFramebufferPixels(void *pixels, const IntRect&) OVERRIDE; - bool getFramebufferTexture(CCScopedTexture*, const IntRect& deviceRect); - - virtual TextureCopier* textureCopier() const OVERRIDE { return m_textureCopier.get(); } - virtual TextureUploader* textureUploader() const OVERRIDE { return m_textureUploader.get(); } - - virtual bool isContextLost() OVERRIDE; - - virtual void setVisible(bool) OVERRIDE; - -protected: - CCRendererGL(CCRendererClient*, CCResourceProvider*, TextureUploaderOption); - - bool isFramebufferDiscarded() const { return m_isFramebufferDiscarded; } - bool initialize(); - - void releaseRenderPassTextures(); - - virtual void bindFramebufferToOutputSurface(DrawingFrame&) OVERRIDE; - virtual bool bindFramebufferToTexture(DrawingFrame&, const CCScopedTexture*, const IntRect& framebufferRect) OVERRIDE; - virtual void setDrawViewportSize(const IntSize&) OVERRIDE; - virtual void enableScissorTestRect(const IntRect& scissorRect) OVERRIDE; - virtual void disableScissorTest() OVERRIDE; - virtual void clearFramebuffer(DrawingFrame&) OVERRIDE; - virtual void drawQuad(DrawingFrame&, const CCDrawQuad*) OVERRIDE; - virtual void beginDrawingFrame(DrawingFrame&) OVERRIDE; - virtual void finishDrawingFrame(DrawingFrame&) OVERRIDE; - -private: - static void toGLMatrix(float*, const WebKit::WebTransformationMatrix&); - - void drawCheckerboardQuad(const DrawingFrame&, const CCCheckerboardDrawQuad*); - void drawDebugBorderQuad(const DrawingFrame&, const CCDebugBorderDrawQuad*); - PassOwnPtr<CCScopedTexture> drawBackgroundFilters(DrawingFrame&, const CCRenderPassDrawQuad*, const WebKit::WebFilterOperations&, const WebKit::WebTransformationMatrix& deviceTransform); - void drawRenderPassQuad(DrawingFrame&, const CCRenderPassDrawQuad*); - void drawSolidColorQuad(const DrawingFrame&, const CCSolidColorDrawQuad*); - void drawStreamVideoQuad(const DrawingFrame&, const CCStreamVideoDrawQuad*); - void drawTextureQuad(const DrawingFrame&, const CCTextureDrawQuad*); - void drawIOSurfaceQuad(const DrawingFrame&, const CCIOSurfaceDrawQuad*); - void drawTileQuad(const DrawingFrame&, const CCTileDrawQuad*); - void drawYUVVideoQuad(const DrawingFrame&, const CCYUVVideoDrawQuad*); - - void setShaderOpacity(float opacity, int alphaLocation); - void setShaderFloatQuad(const FloatQuad&, int quadLocation); - void drawQuadGeometry(const DrawingFrame&, const WebKit::WebTransformationMatrix& drawTransform, const FloatRect& quadRect, int matrixLocation); - - void copyTextureToFramebuffer(const DrawingFrame&, int textureId, const IntRect&, const WebKit::WebTransformationMatrix& drawMatrix); - - bool useScopedTexture(DrawingFrame&, const CCScopedTexture*, const IntRect& viewportRect); - - bool makeContextCurrent(); - - bool initializeSharedObjects(); - void cleanupSharedObjects(); - - // WebKit::WebGraphicsContext3D::WebGraphicsSwapBuffersCompleteCallbackCHROMIUM implementation. - virtual void onSwapBuffersComplete() OVERRIDE; - - // WebKit::WebGraphicsContext3D::WebGraphicsMemoryAllocationChangedCallbackCHROMIUM implementation. - virtual void onMemoryAllocationChanged(WebKit::WebGraphicsMemoryAllocation) OVERRIDE; - void onMemoryAllocationChangedOnImplThread(WebKit::WebGraphicsMemoryAllocation); - void discardFramebuffer(); - void ensureFramebuffer(); - - // WebGraphicsContext3D::WebGraphicsContextLostCallback implementation. - virtual void onContextLost() OVERRIDE; - - RendererCapabilities m_capabilities; - - unsigned m_offscreenFramebufferId; - - OwnPtr<GeometryBinding> m_sharedGeometry; - FloatQuad m_sharedGeometryQuad; - - // This block of bindings defines all of the programs used by the compositor itself. - - // Tiled layer shaders. - typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexAlpha> TileProgram; - typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexClampAlphaAA> TileProgramAA; - typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexClampSwizzleAlphaAA> TileProgramSwizzleAA; - typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexOpaque> TileProgramOpaque; - typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexSwizzleAlpha> TileProgramSwizzle; - typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexSwizzleOpaque> TileProgramSwizzleOpaque; - typedef ProgramBinding<VertexShaderPosTex, FragmentShaderCheckerboard> TileCheckerboardProgram; - - // Render surface shaders. - typedef ProgramBinding<VertexShaderPosTex, FragmentShaderRGBATexAlpha> RenderPassProgram; - typedef ProgramBinding<VertexShaderPosTex, FragmentShaderRGBATexAlphaMask> RenderPassMaskProgram; - typedef ProgramBinding<VertexShaderQuad, FragmentShaderRGBATexAlphaAA> RenderPassProgramAA; - typedef ProgramBinding<VertexShaderQuad, FragmentShaderRGBATexAlphaMaskAA> RenderPassMaskProgramAA; - - // Texture shaders. - typedef ProgramBinding<VertexShaderPosTexTransform, FragmentShaderRGBATexAlpha> TextureProgram; - typedef ProgramBinding<VertexShaderPosTexTransform, FragmentShaderRGBATexFlipAlpha> TextureProgramFlip; - typedef ProgramBinding<VertexShaderPosTexTransform, FragmentShaderRGBATexRectAlpha> TextureIOSurfaceProgram; - - // Video shaders. - typedef ProgramBinding<VertexShaderVideoTransform, FragmentShaderOESImageExternal> VideoStreamTextureProgram; - typedef ProgramBinding<VertexShaderPosTexYUVStretch, FragmentShaderYUVVideo> VideoYUVProgram; - - // Special purpose / effects shaders. - typedef ProgramBinding<VertexShaderPos, FragmentShaderColor> SolidColorProgram; - - const TileProgram* tileProgram(); - const TileProgramOpaque* tileProgramOpaque(); - const TileProgramAA* tileProgramAA(); - const TileProgramSwizzle* tileProgramSwizzle(); - const TileProgramSwizzleOpaque* tileProgramSwizzleOpaque(); - const TileProgramSwizzleAA* tileProgramSwizzleAA(); - const TileCheckerboardProgram* tileCheckerboardProgram(); - - const RenderPassProgram* renderPassProgram(); - const RenderPassProgramAA* renderPassProgramAA(); - const RenderPassMaskProgram* renderPassMaskProgram(); - const RenderPassMaskProgramAA* renderPassMaskProgramAA(); - - const TextureProgram* textureProgram(); - const TextureProgramFlip* textureProgramFlip(); - const TextureIOSurfaceProgram* textureIOSurfaceProgram(); - - const VideoYUVProgram* videoYUVProgram(); - const VideoStreamTextureProgram* videoStreamTextureProgram(); - - const SolidColorProgram* solidColorProgram(); - - OwnPtr<TileProgram> m_tileProgram; - OwnPtr<TileProgramOpaque> m_tileProgramOpaque; - OwnPtr<TileProgramAA> m_tileProgramAA; - OwnPtr<TileProgramSwizzle> m_tileProgramSwizzle; - OwnPtr<TileProgramSwizzleOpaque> m_tileProgramSwizzleOpaque; - OwnPtr<TileProgramSwizzleAA> m_tileProgramSwizzleAA; - OwnPtr<TileCheckerboardProgram> m_tileCheckerboardProgram; - - OwnPtr<RenderPassProgram> m_renderPassProgram; - OwnPtr<RenderPassProgramAA> m_renderPassProgramAA; - OwnPtr<RenderPassMaskProgram> m_renderPassMaskProgram; - OwnPtr<RenderPassMaskProgramAA> m_renderPassMaskProgramAA; - - OwnPtr<TextureProgram> m_textureProgram; - OwnPtr<TextureProgramFlip> m_textureProgramFlip; - OwnPtr<TextureIOSurfaceProgram> m_textureIOSurfaceProgram; - - OwnPtr<VideoYUVProgram> m_videoYUVProgram; - OwnPtr<VideoStreamTextureProgram> m_videoStreamTextureProgram; - - OwnPtr<SolidColorProgram> m_solidColorProgram; - - OwnPtr<AcceleratedTextureCopier> m_textureCopier; - OwnPtr<TextureUploader> m_textureUploader; - - WebKit::WebGraphicsContext3D* m_context; - - IntRect m_swapBufferRect; - bool m_isViewportChanged; - bool m_isFramebufferDiscarded; - bool m_isUsingBindUniform; - bool m_visible; - TextureUploaderOption m_textureUploaderSetting; - - OwnPtr<CCResourceProvider::ScopedWriteLockGL> m_currentFramebufferLock; -}; - - -// Setting DEBUG_GL_CALLS to 1 will call glGetError() after almost every GL -// call made by the compositor. Useful for debugging rendering issues but -// will significantly degrade performance. -#define DEBUG_GL_CALLS 0 - -#if DEBUG_GL_CALLS && !defined ( NDEBUG ) -#define GLC(context, x) (x, CCRendererGL::debugGLCall(&*context, #x, __FILE__, __LINE__)) -#else -#define GLC(context, x) (x) -#endif - - -} - -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCRenderingStats.h b/Source/WebCore/platform/graphics/chromium/cc/CCRenderingStats.h deleted file mode 100644 index cabaa8b39..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCRenderingStats.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 CCRenderingStats_h -#define CCRenderingStats_h - -namespace WebCore { - -struct CCRenderingStats { - // FIXME: Rename these to animationFrameCount and screenFrameCount, crbug.com/138641. - int numAnimationFrames; - int numFramesSentToScreen; - int droppedFrameCount; - double totalPaintTimeInSeconds; - double totalRasterizeTimeInSeconds; - - CCRenderingStats() - : numAnimationFrames(0) - , numFramesSentToScreen(0) - , droppedFrameCount(0) - , totalPaintTimeInSeconds(0) - , totalRasterizeTimeInSeconds(0) - { - } -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCResourceProvider.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCResourceProvider.cpp deleted file mode 100644 index fc3bfe7e1..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCResourceProvider.cpp +++ /dev/null @@ -1,564 +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 "CCResourceProvider.h" - -#include "CCProxy.h" -#include "CCRendererGL.h" // For the GLC() macro. -#include "Extensions3DChromium.h" -#include "IntRect.h" -#include "LayerTextureSubImage.h" -#include <limits.h> -#include <public/WebGraphicsContext3D.h> -#include <wtf/HashSet.h> - -using WebKit::WebGraphicsContext3D; - -namespace WebCore { - -static GC3Denum textureToStorageFormat(GC3Denum textureFormat) -{ - GC3Denum storageFormat = Extensions3D::RGBA8_OES; - switch (textureFormat) { - case GraphicsContext3D::RGBA: - break; - case Extensions3D::BGRA_EXT: - storageFormat = Extensions3DChromium::BGRA8_EXT; - break; - default: - ASSERT_NOT_REACHED(); - break; - } - - return storageFormat; -} - -static bool isTextureFormatSupportedForStorage(GC3Denum format) -{ - return (format == GraphicsContext3D::RGBA || format == Extensions3D::BGRA_EXT); -} - -PassOwnPtr<CCResourceProvider> CCResourceProvider::create(CCGraphicsContext* context) -{ - OwnPtr<CCResourceProvider> resourceProvider(adoptPtr(new CCResourceProvider(context))); - if (!resourceProvider->initialize()) - return nullptr; - return resourceProvider.release(); -} - -CCResourceProvider::~CCResourceProvider() -{ -} - -WebGraphicsContext3D* CCResourceProvider::graphicsContext3D() -{ - ASSERT(CCProxy::isImplThread()); - return m_context->context3D(); -} - -bool CCResourceProvider::inUseByConsumer(ResourceId id) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - return !!it->second.lockForReadCount || it->second.exported; -} - -CCResourceProvider::ResourceId CCResourceProvider::createResource(int pool, const IntSize& size, GC3Denum format, TextureUsageHint hint) -{ - switch (m_defaultResourceType) { - case GLTexture: - return createGLTexture(pool, size, format, hint); - case Bitmap: - ASSERT(format == GraphicsContext3D::RGBA); - return createBitmap(pool, size); - } - - CRASH(); - return 0; -} - -CCResourceProvider::ResourceId CCResourceProvider::createGLTexture(int pool, const IntSize& size, GC3Denum format, TextureUsageHint hint) -{ - ASSERT(CCProxy::isImplThread()); - unsigned textureId = 0; - WebGraphicsContext3D* context3d = m_context->context3D(); - ASSERT(context3d); - GLC(context3d, textureId = context3d->createTexture()); - GLC(context3d, context3d->bindTexture(GraphicsContext3D::TEXTURE_2D, textureId)); - GLC(context3d, context3d->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR)); - GLC(context3d, context3d->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR)); - GLC(context3d, context3d->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE)); - GLC(context3d, context3d->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE)); - - if (m_useTextureUsageHint && hint == TextureUsageFramebuffer) - GLC(context3d, context3d->texParameteri(GraphicsContext3D::TEXTURE_2D, Extensions3DChromium::GL_TEXTURE_USAGE_ANGLE, Extensions3DChromium::GL_FRAMEBUFFER_ATTACHMENT_ANGLE)); - if (m_useTextureStorageExt && isTextureFormatSupportedForStorage(format)) { - GC3Denum storageFormat = textureToStorageFormat(format); - GLC(context3d, context3d->texStorage2DEXT(GraphicsContext3D::TEXTURE_2D, 1, storageFormat, size.width(), size.height())); - } else - GLC(context3d, context3d->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, format, size.width(), size.height(), 0, format, GraphicsContext3D::UNSIGNED_BYTE, 0)); - ResourceId id = m_nextId++; - Resource resource(textureId, pool, size, format); - m_resources.add(id, resource); - return id; -} - -CCResourceProvider::ResourceId CCResourceProvider::createBitmap(int pool, const IntSize& size) -{ - ASSERT(CCProxy::isImplThread()); - - uint8_t* pixels = new uint8_t[size.width() * size.height() * 4]; - - ResourceId id = m_nextId++; - Resource resource(pixels, pool, size, GraphicsContext3D::RGBA); - m_resources.add(id, resource); - return id; -} - -CCResourceProvider::ResourceId CCResourceProvider::createResourceFromExternalTexture(unsigned textureId) -{ - ASSERT(CCProxy::isImplThread()); - ASSERT(m_context->context3D()); - ResourceId id = m_nextId++; - Resource resource(textureId, 0, IntSize(), 0); - resource.external = true; - m_resources.add(id, resource); - return id; -} - -void CCResourceProvider::deleteResource(ResourceId id) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - ASSERT(!it->second.lockedForWrite); - ASSERT(!it->second.lockForReadCount); - - if (it->second.glId && !it->second.external) { - WebGraphicsContext3D* context3d = m_context->context3D(); - ASSERT(context3d); - GLC(context3d, context3d->deleteTexture(it->second.glId)); - } - if (it->second.pixels) - delete it->second.pixels; - - m_resources.remove(it); -} - -void CCResourceProvider::deleteOwnedResources(int pool) -{ - ASSERT(CCProxy::isImplThread()); - ResourceIdArray toDelete; - for (ResourceMap::iterator it = m_resources.begin(); it != m_resources.end(); ++it) { - if (it->second.pool == pool && !it->second.external) - toDelete.append(it->first); - } - for (ResourceIdArray::iterator it = toDelete.begin(); it != toDelete.end(); ++it) - deleteResource(*it); -} - -CCResourceProvider::ResourceType CCResourceProvider::resourceType(ResourceId id) -{ - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - return it->second.type; -} - -void CCResourceProvider::upload(ResourceId id, const uint8_t* image, const IntRect& imageRect, const IntRect& sourceRect, const IntSize& destOffset) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - ASSERT(!it->second.lockedForWrite); - ASSERT(!it->second.lockForReadCount); - ASSERT(!it->second.external); - - if (it->second.glId) { - WebGraphicsContext3D* context3d = m_context->context3D(); - ASSERT(context3d); - ASSERT(m_texSubImage.get()); - context3d->bindTexture(GraphicsContext3D::TEXTURE_2D, it->second.glId); - m_texSubImage->upload(image, imageRect, sourceRect, destOffset, it->second.format, context3d); - } - - if (it->second.pixels) { - SkBitmap srcFull; - srcFull.setConfig(SkBitmap::kARGB_8888_Config, imageRect.width(), imageRect.height()); - srcFull.setPixels(const_cast<uint8_t*>(image)); - SkBitmap srcSubset; - SkIRect skSourceRect = SkIRect::MakeXYWH(sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height()); - skSourceRect.offset(-imageRect.x(), -imageRect.y()); - srcFull.extractSubset(&srcSubset, skSourceRect); - - ScopedWriteLockSoftware lock(this, id); - SkCanvas* dest = lock.skCanvas(); - dest->writePixels(srcSubset, destOffset.width(), destOffset.height()); - } -} - -void CCResourceProvider::flush() -{ - ASSERT(CCProxy::isImplThread()); - WebGraphicsContext3D* context3d = m_context->context3D(); - if (context3d) - context3d->flush(); -} - -bool CCResourceProvider::shallowFlushIfSupported() -{ - ASSERT(CCProxy::isImplThread()); - WebGraphicsContext3D* context3d = m_context->context3D(); - if (!context3d || !m_useShallowFlush) - return false; - - context3d->shallowFlushCHROMIUM(); - return true; -} - -const CCResourceProvider::Resource* CCResourceProvider::lockForRead(ResourceId id) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - ASSERT(!it->second.lockedForWrite); - it->second.lockForReadCount++; - return &it->second; -} - -void CCResourceProvider::unlockForRead(ResourceId id) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - ASSERT(it->second.lockForReadCount > 0); - it->second.lockForReadCount--; -} - -const CCResourceProvider::Resource* CCResourceProvider::lockForWrite(ResourceId id) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - ASSERT(!it->second.lockedForWrite); - ASSERT(!it->second.lockForReadCount); - ASSERT(!it->second.external); - it->second.lockedForWrite = true; - return &it->second; -} - -void CCResourceProvider::unlockForWrite(ResourceId id) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - ASSERT(it->second.lockedForWrite); - ASSERT(!it->second.external); - it->second.lockedForWrite = false; -} - -CCResourceProvider::ScopedReadLockGL::ScopedReadLockGL(CCResourceProvider* resourceProvider, CCResourceProvider::ResourceId resourceId) - : m_resourceProvider(resourceProvider) - , m_resourceId(resourceId) - , m_textureId(resourceProvider->lockForRead(resourceId)->glId) -{ - ASSERT(m_textureId); -} - -CCResourceProvider::ScopedReadLockGL::~ScopedReadLockGL() -{ - m_resourceProvider->unlockForRead(m_resourceId); -} - -CCResourceProvider::ScopedWriteLockGL::ScopedWriteLockGL(CCResourceProvider* resourceProvider, CCResourceProvider::ResourceId resourceId) - : m_resourceProvider(resourceProvider) - , m_resourceId(resourceId) - , m_textureId(resourceProvider->lockForWrite(resourceId)->glId) -{ - ASSERT(m_textureId); -} - -CCResourceProvider::ScopedWriteLockGL::~ScopedWriteLockGL() -{ - m_resourceProvider->unlockForWrite(m_resourceId); -} - -void CCResourceProvider::populateSkBitmapWithResource(SkBitmap* skBitmap, const Resource* resource) -{ - ASSERT(resource->pixels); - ASSERT(resource->format == GraphicsContext3D::RGBA); - skBitmap->setConfig(SkBitmap::kARGB_8888_Config, resource->size.width(), resource->size.height()); - skBitmap->setPixels(resource->pixels); -} - -CCResourceProvider::ScopedReadLockSoftware::ScopedReadLockSoftware(CCResourceProvider* resourceProvider, CCResourceProvider::ResourceId resourceId) - : m_resourceProvider(resourceProvider) - , m_resourceId(resourceId) -{ - CCResourceProvider::populateSkBitmapWithResource(&m_skBitmap, resourceProvider->lockForRead(resourceId)); -} - -CCResourceProvider::ScopedReadLockSoftware::~ScopedReadLockSoftware() -{ - m_resourceProvider->unlockForRead(m_resourceId); -} - -CCResourceProvider::ScopedWriteLockSoftware::ScopedWriteLockSoftware(CCResourceProvider* resourceProvider, CCResourceProvider::ResourceId resourceId) - : m_resourceProvider(resourceProvider) - , m_resourceId(resourceId) -{ - CCResourceProvider::populateSkBitmapWithResource(&m_skBitmap, resourceProvider->lockForWrite(resourceId)); - m_skCanvas.setBitmapDevice(m_skBitmap); -} - -CCResourceProvider::ScopedWriteLockSoftware::~ScopedWriteLockSoftware() -{ - m_resourceProvider->unlockForWrite(m_resourceId); -} - -CCResourceProvider::CCResourceProvider(CCGraphicsContext* context) - : m_context(context) - , m_nextId(1) - , m_nextChild(1) - , m_defaultResourceType(GLTexture) - , m_useTextureStorageExt(false) - , m_useTextureUsageHint(false) - , m_useShallowFlush(false) - , m_maxTextureSize(0) -{ -} - -bool CCResourceProvider::initialize() -{ - ASSERT(CCProxy::isImplThread()); - WebGraphicsContext3D* context3d = m_context->context3D(); - if (!context3d) { - m_maxTextureSize = INT_MAX; - - // FIXME: Implement this path for software compositing. - return false; - } - if (!context3d->makeContextCurrent()) - return false; - - WebKit::WebString extensionsWebString = context3d->getString(GraphicsContext3D::EXTENSIONS); - String extensionsString(extensionsWebString.data(), extensionsWebString.length()); - Vector<String> extensions; - extensionsString.split(' ', extensions); - bool useMapSub = false; - for (size_t i = 0; i < extensions.size(); ++i) { - if (extensions[i] == "GL_EXT_texture_storage") - m_useTextureStorageExt = true; - else if (extensions[i] == "GL_ANGLE_texture_usage") - m_useTextureUsageHint = true; - else if (extensions[i] == "GL_CHROMIUM_map_sub") - useMapSub = true; - else if (extensions[i] == "GL_CHROMIUM_shallow_flush") - m_useShallowFlush = true; - } - - m_texSubImage = adoptPtr(new LayerTextureSubImage(useMapSub)); - GLC(context3d, context3d->getIntegerv(GraphicsContext3D::MAX_TEXTURE_SIZE, &m_maxTextureSize)); - return true; -} - -int CCResourceProvider::createChild(int pool) -{ - ASSERT(CCProxy::isImplThread()); - Child childInfo; - childInfo.pool = pool; - int child = m_nextChild++; - m_children.add(child, childInfo); - return child; -} - -void CCResourceProvider::destroyChild(int child) -{ - ASSERT(CCProxy::isImplThread()); - ChildMap::iterator it = m_children.find(child); - ASSERT(it != m_children.end()); - deleteOwnedResources(it->second.pool); - m_children.remove(it); - trimMailboxDeque(); -} - -const CCResourceProvider::ResourceIdMap& CCResourceProvider::getChildToParentMap(int child) const -{ - ASSERT(CCProxy::isImplThread()); - ChildMap::const_iterator it = m_children.find(child); - ASSERT(it != m_children.end()); - return it->second.childToParentMap; -} - -CCResourceProvider::TransferableResourceList CCResourceProvider::prepareSendToParent(const ResourceIdArray& resources) -{ - ASSERT(CCProxy::isImplThread()); - TransferableResourceList list; - list.syncPoint = 0; - WebGraphicsContext3D* context3d = m_context->context3D(); - if (!context3d || !context3d->makeContextCurrent()) { - // FIXME: Implement this path for software compositing. - return list; - } - for (ResourceIdArray::const_iterator it = resources.begin(); it != resources.end(); ++it) { - TransferableResource resource; - if (transferResource(context3d, *it, &resource)) { - m_resources.find(*it)->second.exported = true; - list.resources.append(resource); - } - } - if (list.resources.size()) - list.syncPoint = context3d->insertSyncPoint(); - return list; -} - -CCResourceProvider::TransferableResourceList CCResourceProvider::prepareSendToChild(int child, const ResourceIdArray& resources) -{ - ASSERT(CCProxy::isImplThread()); - TransferableResourceList list; - list.syncPoint = 0; - WebGraphicsContext3D* context3d = m_context->context3D(); - if (!context3d || !context3d->makeContextCurrent()) { - // FIXME: Implement this path for software compositing. - return list; - } - Child& childInfo = m_children.find(child)->second; - for (ResourceIdArray::const_iterator it = resources.begin(); it != resources.end(); ++it) { - TransferableResource resource; - if (!transferResource(context3d, *it, &resource)) - ASSERT_NOT_REACHED(); - resource.id = childInfo.parentToChildMap.get(*it); - childInfo.parentToChildMap.remove(*it); - childInfo.childToParentMap.remove(resource.id); - list.resources.append(resource); - deleteResource(*it); - } - if (list.resources.size()) - list.syncPoint = context3d->insertSyncPoint(); - return list; -} - -void CCResourceProvider::receiveFromChild(int child, const TransferableResourceList& resources) -{ - ASSERT(CCProxy::isImplThread()); - WebGraphicsContext3D* context3d = m_context->context3D(); - if (!context3d || !context3d->makeContextCurrent()) { - // FIXME: Implement this path for software compositing. - return; - } - if (resources.syncPoint) { - // NOTE: If the parent is a browser and the child a renderer, the parent - // is not supposed to have its context wait, because that could induce - // deadlocks and/or security issues. The caller is responsible for - // waiting asynchronously, and resetting syncPoint before calling this. - // However if the parent is a renderer (e.g. browser tag), it may be ok - // (and is simpler) to wait. - GLC(context3d, context3d->waitSyncPoint(resources.syncPoint)); - } - Child& childInfo = m_children.find(child)->second; - for (Vector<TransferableResource>::const_iterator it = resources.resources.begin(); it != resources.resources.end(); ++it) { - unsigned textureId; - GLC(context3d, textureId = context3d->createTexture()); - GLC(context3d, context3d->bindTexture(GraphicsContext3D::TEXTURE_2D, textureId)); - GLC(context3d, context3d->consumeTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, it->mailbox.name)); - ResourceId id = m_nextId++; - Resource resource(textureId, childInfo.pool, it->size, it->format); - m_resources.add(id, resource); - m_mailboxes.append(it->mailbox); - childInfo.parentToChildMap.add(id, it->id); - childInfo.childToParentMap.add(it->id, id); - } -} - -void CCResourceProvider::receiveFromParent(const TransferableResourceList& resources) -{ - ASSERT(CCProxy::isImplThread()); - WebGraphicsContext3D* context3d = m_context->context3D(); - if (!context3d || !context3d->makeContextCurrent()) { - // FIXME: Implement this path for software compositing. - return; - } - if (resources.syncPoint) - GLC(context3d, context3d->waitSyncPoint(resources.syncPoint)); - for (Vector<TransferableResource>::const_iterator it = resources.resources.begin(); it != resources.resources.end(); ++it) { - Resource& resource = m_resources.find(it->id)->second; - ASSERT(resource.exported); - resource.exported = false; - GLC(context3d, context3d->bindTexture(GraphicsContext3D::TEXTURE_2D, resource.glId)); - GLC(context3d, context3d->consumeTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, it->mailbox.name)); - m_mailboxes.append(it->mailbox); - } -} - -bool CCResourceProvider::transferResource(WebGraphicsContext3D* context, ResourceId id, TransferableResource* resource) -{ - ASSERT(CCProxy::isImplThread()); - ResourceMap::const_iterator it = m_resources.find(id); - ASSERT(it != m_resources.end()); - ASSERT(!it->second.lockedForWrite); - ASSERT(!it->second.lockForReadCount); - ASSERT(!it->second.external); - if (it->second.exported) - return false; - resource->id = id; - resource->format = it->second.format; - resource->size = it->second.size; - if (!m_mailboxes.isEmpty()) - resource->mailbox = m_mailboxes.takeFirst(); - else - GLC(context, context->genMailboxCHROMIUM(resource->mailbox.name)); - GLC(context, context->bindTexture(GraphicsContext3D::TEXTURE_2D, it->second.glId)); - GLC(context, context->produceTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, resource->mailbox.name)); - return true; -} - -void CCResourceProvider::trimMailboxDeque() -{ - // Trim the mailbox deque to the maximum number of resources we may need to - // send. - // If we have a parent, any non-external resource not already transfered is - // eligible to be sent to the parent. Otherwise, all resources belonging to - // a child might need to be sent back to the child. - size_t maxMailboxCount = 0; - if (m_context->capabilities().hasParentCompositor) { - for (ResourceMap::iterator it = m_resources.begin(); it != m_resources.end(); ++it) { - if (!it->second.exported && !it->second.external) - ++maxMailboxCount; - } - } else { - HashSet<int> childPoolSet; - for (ChildMap::iterator it = m_children.begin(); it != m_children.end(); ++it) - childPoolSet.add(it->second.pool); - for (ResourceMap::iterator it = m_resources.begin(); it != m_resources.end(); ++it) { - if (childPoolSet.contains(it->second.pool)) - ++maxMailboxCount; - } - } - while (m_mailboxes.size() > maxMailboxCount) - m_mailboxes.removeFirst(); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCResourceProvider.h b/Source/WebCore/platform/graphics/chromium/cc/CCResourceProvider.h deleted file mode 100644 index ebad4b986..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCResourceProvider.h +++ /dev/null @@ -1,310 +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 CCResourceProvider_h -#define CCResourceProvider_h - -#include "CCGraphicsContext.h" -#include "GraphicsContext3D.h" -#include "IntSize.h" -#include "SkBitmap.h" -#include "SkCanvas.h" -#include <wtf/Deque.h> -#include <wtf/HashMap.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> -#include <wtf/PassRefPtr.h> -#include <wtf/RefPtr.h> -#include <wtf/Vector.h> - -namespace WebKit { -class WebGraphicsContext3D; -} - -namespace WebCore { - -class IntRect; -class LayerTextureSubImage; - -// Thread-safety notes: this class is not thread-safe and can only be called -// from the thread it was created on (in practice, the compositor thread). -class CCResourceProvider { - WTF_MAKE_NONCOPYABLE(CCResourceProvider); -public: - typedef unsigned ResourceId; - typedef Vector<ResourceId> ResourceIdArray; - typedef HashMap<ResourceId, ResourceId> ResourceIdMap; - enum TextureUsageHint { TextureUsageAny, TextureUsageFramebuffer }; - enum ResourceType { - GLTexture = 1, - Bitmap, - }; - struct Mailbox { - GC3Dbyte name[64]; - }; - struct TransferableResource { - unsigned id; - GC3Denum format; - IntSize size; - Mailbox mailbox; - }; - typedef Vector<TransferableResource> TransferableResourceArray; - struct TransferableResourceList { - TransferableResourceArray resources; - unsigned syncPoint; - }; - - static PassOwnPtr<CCResourceProvider> create(CCGraphicsContext*); - - virtual ~CCResourceProvider(); - - WebKit::WebGraphicsContext3D* graphicsContext3D(); - int maxTextureSize() const { return m_maxTextureSize; } - unsigned numResources() const { return m_resources.size(); } - - // Checks whether a resource is in use by a consumer. - bool inUseByConsumer(ResourceId); - - - // Producer interface. - - void setDefaultResourceType(ResourceType type) { m_defaultResourceType = type; } - ResourceType defaultResourceType() const { return m_defaultResourceType; } - ResourceType resourceType(ResourceId); - - // Creates a resource of the default resource type. - ResourceId createResource(int pool, const IntSize&, GC3Denum format, TextureUsageHint); - - // You can also explicitly create a specific resource type. - ResourceId createGLTexture(int pool, const IntSize&, GC3Denum format, TextureUsageHint); - ResourceId createBitmap(int pool, const IntSize&); - // Wraps an external texture into a GL resource. - ResourceId createResourceFromExternalTexture(unsigned textureId); - - void deleteResource(ResourceId); - - // Deletes all resources owned by a given pool. - void deleteOwnedResources(int pool); - - // Upload data from image, copying sourceRect (in image) into destRect (in the resource). - void upload(ResourceId, const uint8_t* image, const IntRect& imageRect, const IntRect& sourceRect, const IntSize& destOffset); - - // Flush all context operations, kicking uploads and ensuring ordering with - // respect to other contexts. - void flush(); - - // Only flush the command buffer if supported. - // Returns true if the shallow flush occurred, false otherwise. - bool shallowFlushIfSupported(); - - // Creates accounting for a child, and associate it with a pool. Resources - // transfered from that child will go to that pool. Returns a child ID. - int createChild(int pool); - - // Destroys accounting for the child, deleting all resources from that pool. - void destroyChild(int child); - - // Gets the child->parent resource ID map. - const ResourceIdMap& getChildToParentMap(int child) const; - - // Prepares resources to be transfered to the parent, moving them to - // mailboxes and serializing meta-data into TransferableResources. - // Resources are not removed from the CCResourceProvider, but are markes as - // "in use". - TransferableResourceList prepareSendToParent(const ResourceIdArray&); - - // Prepares resources to be transfered back to the child, moving them to - // mailboxes and serializing meta-data into TransferableResources. - // Resources are removed from the CCResourceProvider. Note: the resource IDs - // passed are in the parent namespace and will be translated to the child - // namespace when returned. - TransferableResourceList prepareSendToChild(int child, const ResourceIdArray&); - - // Receives resources from a child, moving them from mailboxes. Resource IDs - // passed are in the child namespace, and will be translated to the parent - // namespace, added to the child->parent map. - // NOTE: if the syncPoint filed in TransferableResourceList is set, this - // will wait on it. - void receiveFromChild(int child, const TransferableResourceList&); - - // Receives resources from the parent, moving them from mailboxes. Resource IDs - // passed are in the child namespace. - // NOTE: if the syncPoint filed in TransferableResourceList is set, this - // will wait on it. - void receiveFromParent(const TransferableResourceList&); - - // Only for testing - size_t mailboxCount() const { return m_mailboxes.size(); } - - // The following lock classes are part of the CCResourceProvider API and are - // needed to read and write the resource contents. The user must ensure - // that they only use GL locks on GL resources, etc, and this is enforced - // by assertions. - class ScopedReadLockGL { - WTF_MAKE_NONCOPYABLE(ScopedReadLockGL); - public: - ScopedReadLockGL(CCResourceProvider*, CCResourceProvider::ResourceId); - ~ScopedReadLockGL(); - - unsigned textureId() const { return m_textureId; } - - private: - CCResourceProvider* m_resourceProvider; - CCResourceProvider::ResourceId m_resourceId; - unsigned m_textureId; - }; - - class ScopedWriteLockGL { - WTF_MAKE_NONCOPYABLE(ScopedWriteLockGL); - public: - ScopedWriteLockGL(CCResourceProvider*, CCResourceProvider::ResourceId); - ~ScopedWriteLockGL(); - - unsigned textureId() const { return m_textureId; } - - private: - CCResourceProvider* m_resourceProvider; - CCResourceProvider::ResourceId m_resourceId; - unsigned m_textureId; - }; - - class ScopedReadLockSoftware { - WTF_MAKE_NONCOPYABLE(ScopedReadLockSoftware); - public: - ScopedReadLockSoftware(CCResourceProvider*, CCResourceProvider::ResourceId); - ~ScopedReadLockSoftware(); - - const SkBitmap* skBitmap() const { return &m_skBitmap; } - - private: - CCResourceProvider* m_resourceProvider; - CCResourceProvider::ResourceId m_resourceId; - SkBitmap m_skBitmap; - }; - - class ScopedWriteLockSoftware { - WTF_MAKE_NONCOPYABLE(ScopedWriteLockSoftware); - public: - ScopedWriteLockSoftware(CCResourceProvider*, CCResourceProvider::ResourceId); - ~ScopedWriteLockSoftware(); - - SkCanvas* skCanvas() { return &m_skCanvas; } - - private: - CCResourceProvider* m_resourceProvider; - CCResourceProvider::ResourceId m_resourceId; - SkBitmap m_skBitmap; - SkCanvas m_skCanvas; - }; - -private: - struct Resource { - Resource() - : glId(0) - , pixels(0) - , pool(0) - , lockForReadCount(0) - , lockedForWrite(false) - , external(false) - , exported(false) - , size() - , format(0) - , type(static_cast<ResourceType>(0)) - { } - Resource(unsigned textureId, int pool, const IntSize& size, GC3Denum format) - : glId(textureId) - , pixels(0) - , pool(pool) - , lockForReadCount(0) - , lockedForWrite(false) - , external(false) - , exported(false) - , size(size) - , format(format) - , type(GLTexture) - { } - Resource(uint8_t* pixels, int pool, const IntSize& size, GC3Denum format) - : glId(0) - , pixels(pixels) - , pool(pool) - , lockForReadCount(0) - , lockedForWrite(false) - , external(false) - , exported(false) - , size(size) - , format(format) - , type(Bitmap) - { } - unsigned glId; - uint8_t* pixels; - int pool; - int lockForReadCount; - bool lockedForWrite; - bool external; - bool exported; - IntSize size; - GC3Denum format; - ResourceType type; - }; - typedef HashMap<ResourceId, Resource> ResourceMap; - struct Child { - int pool; - ResourceIdMap childToParentMap; - ResourceIdMap parentToChildMap; - }; - typedef HashMap<int, Child> ChildMap; - - explicit CCResourceProvider(CCGraphicsContext*); - bool initialize(); - - const Resource* lockForRead(ResourceId); - void unlockForRead(ResourceId); - const Resource* lockForWrite(ResourceId); - void unlockForWrite(ResourceId); - static void populateSkBitmapWithResource(SkBitmap*, const Resource*); - - bool transferResource(WebKit::WebGraphicsContext3D*, ResourceId, TransferableResource*); - void trimMailboxDeque(); - - CCGraphicsContext* m_context; - ResourceId m_nextId; - ResourceMap m_resources; - int m_nextChild; - ChildMap m_children; - - Deque<Mailbox> m_mailboxes; - - ResourceType m_defaultResourceType; - bool m_useTextureStorageExt; - bool m_useTextureUsageHint; - bool m_useShallowFlush; - OwnPtr<LayerTextureSubImage> m_texSubImage; - int m_maxTextureSize; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScheduler.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCScheduler.cpp deleted file mode 100644 index 01984210b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScheduler.cpp +++ /dev/null @@ -1,220 +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 "CCScheduler.h" - -#include "TraceEvent.h" - -namespace WebCore { - -CCScheduler::CCScheduler(CCSchedulerClient* client, PassOwnPtr<CCFrameRateController> frameRateController) - : m_client(client) - , m_frameRateController(frameRateController) - , m_updateMoreResourcesPending(false) -{ - ASSERT(m_client); - m_frameRateController->setClient(this); - m_frameRateController->setActive(m_stateMachine.vsyncCallbackNeeded()); -} - -CCScheduler::~CCScheduler() -{ - m_frameRateController->setActive(false); -} - -void CCScheduler::setCanBeginFrame(bool can) -{ - m_stateMachine.setCanBeginFrame(can); - processScheduledActions(); -} - -void CCScheduler::setVisible(bool visible) -{ - m_stateMachine.setVisible(visible); - processScheduledActions(); -} - -void CCScheduler::setCanDraw(bool canDraw) -{ - m_stateMachine.setCanDraw(canDraw); - - // Defer processScheduleActions so we don't recurse and commit/draw - // multiple frames. We can call processScheduledActions directly - // once it is no longer re-entrant. - m_frameRateController->setActive(m_stateMachine.vsyncCallbackNeeded()); -} - -void CCScheduler::setNeedsCommit() -{ - m_stateMachine.setNeedsCommit(); - processScheduledActions(); -} - -void CCScheduler::setNeedsForcedCommit() -{ - m_stateMachine.setNeedsForcedCommit(); - processScheduledActions(); -} - -void CCScheduler::setNeedsRedraw() -{ - m_stateMachine.setNeedsRedraw(); - processScheduledActions(); -} - -void CCScheduler::setNeedsForcedRedraw() -{ - m_stateMachine.setNeedsForcedRedraw(); - processScheduledActions(); -} - -void CCScheduler::setMainThreadNeedsLayerTextures() -{ - m_stateMachine.setMainThreadNeedsLayerTextures(); - processScheduledActions(); -} - -void CCScheduler::beginFrameComplete() -{ - TRACE_EVENT0("cc", "CCScheduler::beginFrameComplete"); - m_stateMachine.beginFrameComplete(); - processScheduledActions(); -} - -void CCScheduler::beginFrameAborted() -{ - TRACE_EVENT0("cc", "CCScheduler::beginFrameAborted"); - m_stateMachine.beginFrameAborted(); - processScheduledActions(); -} - -void CCScheduler::setMaxFramesPending(int maxFramesPending) -{ - m_frameRateController->setMaxFramesPending(maxFramesPending); -} - -void CCScheduler::setSwapBuffersCompleteSupported(bool supported) -{ - m_frameRateController->setSwapBuffersCompleteSupported(supported); -} - -void CCScheduler::didSwapBuffersComplete() -{ - TRACE_EVENT0("cc", "CCScheduler::didSwapBuffersComplete"); - m_frameRateController->didFinishFrame(); -} - -void CCScheduler::didLoseContext() -{ - TRACE_EVENT0("cc", "CCScheduler::didLoseContext"); - m_frameRateController->didAbortAllPendingFrames(); - m_stateMachine.didLoseContext(); - processScheduledActions(); -} - -void CCScheduler::didRecreateContext() -{ - TRACE_EVENT0("cc", "CCScheduler::didRecreateContext"); - m_stateMachine.didRecreateContext(); - processScheduledActions(); -} - -void CCScheduler::setTimebaseAndInterval(double timebase, double intervalSeconds) -{ - m_frameRateController->setTimebaseAndInterval(timebase, intervalSeconds); -} - -void CCScheduler::vsyncTick() -{ - if (m_updateMoreResourcesPending) { - m_updateMoreResourcesPending = false; - m_stateMachine.beginUpdateMoreResourcesComplete(m_client->hasMoreResourceUpdates()); - } - TRACE_EVENT0("cc", "CCScheduler::vsyncTick"); - - m_stateMachine.didEnterVSync(); - processScheduledActions(); - m_stateMachine.didLeaveVSync(); -} - -void CCScheduler::processScheduledActions() -{ - // Early out so we don't spam TRACE_EVENTS with useless processScheduledActions. - if (m_stateMachine.nextAction() == CCSchedulerStateMachine::ACTION_NONE) { - m_frameRateController->setActive(m_stateMachine.vsyncCallbackNeeded()); - return; - } - - // This function can re-enter itself. For example, draw may call - // setNeedsCommit. Proceeed with caution. - CCSchedulerStateMachine::Action action; - do { - action = m_stateMachine.nextAction(); - m_stateMachine.updateState(action); - TRACE_EVENT1("cc", "CCScheduler::processScheduledActions()", "action", action); - - switch (action) { - case CCSchedulerStateMachine::ACTION_NONE: - break; - case CCSchedulerStateMachine::ACTION_BEGIN_FRAME: - m_client->scheduledActionBeginFrame(); - break; - case CCSchedulerStateMachine::ACTION_BEGIN_UPDATE_MORE_RESOURCES: - if (m_client->hasMoreResourceUpdates()) { - m_client->scheduledActionUpdateMoreResources(m_frameRateController->nextTickTimeIfActivated()); - m_updateMoreResourcesPending = true; - } else - m_stateMachine.beginUpdateMoreResourcesComplete(false); - break; - case CCSchedulerStateMachine::ACTION_COMMIT: - m_client->scheduledActionCommit(); - break; - case CCSchedulerStateMachine::ACTION_DRAW_IF_POSSIBLE: { - CCScheduledActionDrawAndSwapResult result = m_client->scheduledActionDrawAndSwapIfPossible(); - m_stateMachine.didDrawIfPossibleCompleted(result.didDraw); - if (result.didSwap) - m_frameRateController->didBeginFrame(); - break; - } - case CCSchedulerStateMachine::ACTION_DRAW_FORCED: { - CCScheduledActionDrawAndSwapResult result = m_client->scheduledActionDrawAndSwapForced(); - if (result.didSwap) - m_frameRateController->didBeginFrame(); - break; - } case CCSchedulerStateMachine::ACTION_BEGIN_CONTEXT_RECREATION: - m_client->scheduledActionBeginContextRecreation(); - break; - case CCSchedulerStateMachine::ACTION_ACQUIRE_LAYER_TEXTURES_FOR_MAIN_THREAD: - m_client->scheduledActionAcquireLayerTexturesForMainThread(); - break; - } - } while (action != CCSchedulerStateMachine::ACTION_NONE); - - // Activate or deactivate the frame rate controller. - m_frameRateController->setActive(m_stateMachine.vsyncCallbackNeeded()); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScheduler.h b/Source/WebCore/platform/graphics/chromium/cc/CCScheduler.h deleted file mode 100644 index 9ac871fbf..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScheduler.h +++ /dev/null @@ -1,127 +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 CCScheduler_h -#define CCScheduler_h - -#include "CCFrameRateController.h" -#include "CCSchedulerStateMachine.h" - -#include <wtf/Noncopyable.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCThread; - -struct CCScheduledActionDrawAndSwapResult { - CCScheduledActionDrawAndSwapResult() - : didDraw(false) - , didSwap(false) - { - } - CCScheduledActionDrawAndSwapResult(bool didDraw, bool didSwap) - : didDraw(didDraw) - , didSwap(didSwap) - { - } - bool didDraw; - bool didSwap; -}; - -class CCSchedulerClient { -public: - virtual bool hasMoreResourceUpdates() const = 0; - - virtual void scheduledActionBeginFrame() = 0; - virtual CCScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapIfPossible() = 0; - virtual CCScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapForced() = 0; - virtual void scheduledActionUpdateMoreResources(double monotonicTimeLimit) = 0; - virtual void scheduledActionCommit() = 0; - virtual void scheduledActionBeginContextRecreation() = 0; - virtual void scheduledActionAcquireLayerTexturesForMainThread() = 0; - -protected: - virtual ~CCSchedulerClient() { } -}; - -class CCScheduler : CCFrameRateControllerClient { - WTF_MAKE_NONCOPYABLE(CCScheduler); -public: - static PassOwnPtr<CCScheduler> create(CCSchedulerClient* client, PassOwnPtr<CCFrameRateController> frameRateController) - { - return adoptPtr(new CCScheduler(client, frameRateController)); - } - - virtual ~CCScheduler(); - - void setCanBeginFrame(bool); - - void setVisible(bool); - void setCanDraw(bool); - - void setNeedsCommit(); - - // Like setNeedsCommit(), but ensures a commit will definitely happen even if we are not visible. - void setNeedsForcedCommit(); - - void setNeedsRedraw(); - - void setMainThreadNeedsLayerTextures(); - - // Like setNeedsRedraw(), but ensures the draw will definitely happen even if we are not visible. - void setNeedsForcedRedraw(); - - void beginFrameComplete(); - void beginFrameAborted(); - - void setMaxFramesPending(int); - void setSwapBuffersCompleteSupported(bool); - void didSwapBuffersComplete(); - - void didLoseContext(); - void didRecreateContext(); - - bool commitPending() const { return m_stateMachine.commitPending(); } - bool redrawPending() const { return m_stateMachine.redrawPending(); } - - void setTimebaseAndInterval(double timebase, double intervalSeconds); - - // CCFrameRateControllerClient implementation - virtual void vsyncTick() OVERRIDE; - -private: - CCScheduler(CCSchedulerClient*, PassOwnPtr<CCFrameRateController>); - - void processScheduledActions(); - - CCSchedulerClient* m_client; - OwnPtr<CCFrameRateController> m_frameRateController; - CCSchedulerStateMachine m_stateMachine; - bool m_updateMoreResourcesPending; -}; - -} - -#endif // CCScheduler_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSchedulerStateMachine.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCSchedulerStateMachine.cpp deleted file mode 100644 index 08b407df8..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSchedulerStateMachine.cpp +++ /dev/null @@ -1,364 +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 "CCSchedulerStateMachine.h" -#include "TextStream.h" - - -namespace WebCore { - -CCSchedulerStateMachine::CCSchedulerStateMachine() - : m_commitState(COMMIT_STATE_IDLE) - , m_currentFrameNumber(0) - , m_lastFrameNumberWhereDrawWasCalled(-1) - , m_consecutiveFailedDraws(0) - , m_maximumNumberOfFailedDrawsBeforeDrawIsForced(3) - , m_needsRedraw(false) - , m_needsForcedRedraw(false) - , m_needsForcedRedrawAfterNextCommit(false) - , m_needsCommit(false) - , m_needsForcedCommit(false) - , m_mainThreadNeedsLayerTextures(false) - , m_updateMoreResourcesPending(false) - , m_insideVSync(false) - , m_visible(false) - , m_canBeginFrame(false) - , m_canDraw(false) - , m_drawIfPossibleFailed(false) - , m_textureState(LAYER_TEXTURE_STATE_UNLOCKED) - , m_contextState(CONTEXT_ACTIVE) -{ -} - -String CCSchedulerStateMachine::toString() -{ - TextStream ts; - ts << "m_commitState = " << m_commitState << "; "; - ts << "m_currentFrameNumber = " << m_currentFrameNumber << "; "; - ts << "m_lastFrameNumberWhereDrawWasCalled = " << m_lastFrameNumberWhereDrawWasCalled << "; "; - ts << "m_consecutiveFailedDraws = " << m_consecutiveFailedDraws << "; "; - ts << "m_maximumNumberOfFailedDrawsBeforeDrawIsForced = " << m_maximumNumberOfFailedDrawsBeforeDrawIsForced << "; "; - ts << "m_needsRedraw = " << m_needsRedraw << "; "; - ts << "m_needsForcedRedraw = " << m_needsForcedRedraw << "; "; - ts << "m_needsForcedRedrawAfterNextCommit = " << m_needsForcedRedrawAfterNextCommit << "; "; - ts << "m_needsCommit = " << m_needsCommit << "; "; - ts << "m_needsForcedCommit = " << m_needsForcedCommit << "; "; - ts << "m_mainThreadNeedsLayerTextures = " << m_mainThreadNeedsLayerTextures << "; "; - ts << "m_updateMoreResourcesPending = " << m_updateMoreResourcesPending << "; "; - ts << "m_insideVSync = " << m_insideVSync << "; "; - ts << "m_visible = " << m_visible << "; "; - ts << "m_canBeginFrame = " << m_canBeginFrame << "; "; - ts << "m_canDraw = " << m_canDraw << "; "; - ts << "m_drawIfPossibleFailed = " << m_drawIfPossibleFailed << "; "; - ts << "m_textureState = " << m_textureState << "; "; - ts << "m_contextState = " << m_contextState << "; "; - return ts.release(); -} - -bool CCSchedulerStateMachine::hasDrawnThisFrame() const -{ - return m_currentFrameNumber == m_lastFrameNumberWhereDrawWasCalled; -} - -bool CCSchedulerStateMachine::drawSuspendedUntilCommit() const -{ - if (!m_canDraw) - return true; - if (!m_visible) - return true; - if (m_textureState == LAYER_TEXTURE_STATE_ACQUIRED_BY_MAIN_THREAD) - return true; - return false; -} - -bool CCSchedulerStateMachine::scheduledToDraw() const -{ - if (!m_needsRedraw) - return false; - if (drawSuspendedUntilCommit()) - return false; - return true; -} - -bool CCSchedulerStateMachine::shouldDraw() const -{ - if (m_needsForcedRedraw) - return true; - - if (!scheduledToDraw()) - return false; - if (!m_insideVSync) - return false; - if (hasDrawnThisFrame()) - return false; - if (m_contextState != CONTEXT_ACTIVE) - return false; - return true; -} - -bool CCSchedulerStateMachine::shouldAcquireLayerTexturesForMainThread() const -{ - if (!m_mainThreadNeedsLayerTextures) - return false; - if (m_textureState == LAYER_TEXTURE_STATE_UNLOCKED) - return true; - ASSERT(m_textureState == LAYER_TEXTURE_STATE_ACQUIRED_BY_IMPL_THREAD); - // Transfer the lock from impl thread to main thread immediately if the - // impl thread is not even scheduled to draw. Guards against deadlocking. - if (!scheduledToDraw()) - return true; - if (!vsyncCallbackNeeded()) - return true; - return false; -} - -CCSchedulerStateMachine::Action CCSchedulerStateMachine::nextAction() const -{ - if (shouldAcquireLayerTexturesForMainThread()) - return ACTION_ACQUIRE_LAYER_TEXTURES_FOR_MAIN_THREAD; - switch (m_commitState) { - case COMMIT_STATE_IDLE: - if (m_contextState != CONTEXT_ACTIVE && m_needsForcedRedraw) - return ACTION_DRAW_FORCED; - if (m_contextState != CONTEXT_ACTIVE && m_needsForcedCommit) - return ACTION_BEGIN_FRAME; - if (m_contextState == CONTEXT_LOST) - return ACTION_BEGIN_CONTEXT_RECREATION; - if (m_contextState == CONTEXT_RECREATING) - return ACTION_NONE; - if (shouldDraw()) - return m_needsForcedRedraw ? ACTION_DRAW_FORCED : ACTION_DRAW_IF_POSSIBLE; - if (m_needsCommit && ((m_visible && m_canBeginFrame) || m_needsForcedCommit)) - return ACTION_BEGIN_FRAME; - return ACTION_NONE; - - case COMMIT_STATE_FRAME_IN_PROGRESS: - if (shouldDraw()) - return m_needsForcedRedraw ? ACTION_DRAW_FORCED : ACTION_DRAW_IF_POSSIBLE; - return ACTION_NONE; - - case COMMIT_STATE_UPDATING_RESOURCES: - if (shouldDraw()) - return m_needsForcedRedraw ? ACTION_DRAW_FORCED : ACTION_DRAW_IF_POSSIBLE; - if (!m_updateMoreResourcesPending) - return ACTION_BEGIN_UPDATE_MORE_RESOURCES; - return ACTION_NONE; - - case COMMIT_STATE_READY_TO_COMMIT: - return ACTION_COMMIT; - - case COMMIT_STATE_WAITING_FOR_FIRST_DRAW: - if (shouldDraw() || m_contextState == CONTEXT_LOST) - return m_needsForcedRedraw ? ACTION_DRAW_FORCED : ACTION_DRAW_IF_POSSIBLE; - // COMMIT_STATE_WAITING_FOR_FIRST_DRAW wants to enforce a draw. If m_canDraw is false - // or textures are not available, proceed to the next step (similar as in COMMIT_STATE_IDLE). - bool canCommit = m_visible || m_needsForcedCommit; - if (m_needsCommit && canCommit && drawSuspendedUntilCommit()) - return ACTION_BEGIN_FRAME; - return ACTION_NONE; - } - ASSERT_NOT_REACHED(); - return ACTION_NONE; -} - -void CCSchedulerStateMachine::updateState(Action action) -{ - switch (action) { - case ACTION_NONE: - return; - - case ACTION_BEGIN_FRAME: - ASSERT(m_visible || m_needsForcedCommit); - m_commitState = COMMIT_STATE_FRAME_IN_PROGRESS; - m_needsCommit = false; - m_needsForcedCommit = false; - return; - - case ACTION_BEGIN_UPDATE_MORE_RESOURCES: - ASSERT(m_commitState == COMMIT_STATE_UPDATING_RESOURCES); - m_updateMoreResourcesPending = true; - return; - - case ACTION_COMMIT: - m_commitState = COMMIT_STATE_WAITING_FOR_FIRST_DRAW; - m_needsRedraw = true; - if (m_drawIfPossibleFailed) - m_lastFrameNumberWhereDrawWasCalled = -1; - - if (m_needsForcedRedrawAfterNextCommit) { - m_needsForcedRedrawAfterNextCommit = false; - m_needsForcedRedraw = true; - } - - m_textureState = LAYER_TEXTURE_STATE_ACQUIRED_BY_IMPL_THREAD; - return; - - case ACTION_DRAW_FORCED: - case ACTION_DRAW_IF_POSSIBLE: - m_needsRedraw = false; - m_needsForcedRedraw = false; - m_drawIfPossibleFailed = false; - if (m_insideVSync) - m_lastFrameNumberWhereDrawWasCalled = m_currentFrameNumber; - if (m_commitState == COMMIT_STATE_WAITING_FOR_FIRST_DRAW) - m_commitState = COMMIT_STATE_IDLE; - if (m_textureState == LAYER_TEXTURE_STATE_ACQUIRED_BY_IMPL_THREAD) - m_textureState = LAYER_TEXTURE_STATE_UNLOCKED; - return; - - case ACTION_BEGIN_CONTEXT_RECREATION: - ASSERT(m_commitState == COMMIT_STATE_IDLE); - ASSERT(m_contextState == CONTEXT_LOST); - m_contextState = CONTEXT_RECREATING; - return; - - case ACTION_ACQUIRE_LAYER_TEXTURES_FOR_MAIN_THREAD: - m_textureState = LAYER_TEXTURE_STATE_ACQUIRED_BY_MAIN_THREAD; - m_mainThreadNeedsLayerTextures = false; - if (m_commitState != COMMIT_STATE_FRAME_IN_PROGRESS) - m_needsCommit = true; - return; - } -} - -void CCSchedulerStateMachine::setMainThreadNeedsLayerTextures() -{ - ASSERT(!m_mainThreadNeedsLayerTextures); - ASSERT(m_textureState != LAYER_TEXTURE_STATE_ACQUIRED_BY_MAIN_THREAD); - m_mainThreadNeedsLayerTextures = true; -} - -bool CCSchedulerStateMachine::vsyncCallbackNeeded() const -{ - // To prevent live-lock, we must always tick when updating resources. - if (m_updateMoreResourcesPending || m_commitState == COMMIT_STATE_UPDATING_RESOURCES) - return true; - - // If we can't draw, don't tick until we are notified that we can draw again. - if (!m_canDraw) - return false; - - if (m_needsForcedRedraw) - return true; - - return m_needsRedraw && m_visible && m_contextState == CONTEXT_ACTIVE; -} - -void CCSchedulerStateMachine::didEnterVSync() -{ - m_insideVSync = true; -} - -void CCSchedulerStateMachine::didLeaveVSync() -{ - m_currentFrameNumber++; - m_insideVSync = false; -} - -void CCSchedulerStateMachine::setVisible(bool visible) -{ - m_visible = visible; -} - -void CCSchedulerStateMachine::setNeedsRedraw() -{ - m_needsRedraw = true; -} - -void CCSchedulerStateMachine::setNeedsForcedRedraw() -{ - m_needsForcedRedraw = true; -} - -void CCSchedulerStateMachine::didDrawIfPossibleCompleted(bool success) -{ - m_drawIfPossibleFailed = !success; - if (m_drawIfPossibleFailed) { - m_needsRedraw = true; - m_needsCommit = true; - m_consecutiveFailedDraws++; - if (m_consecutiveFailedDraws >= m_maximumNumberOfFailedDrawsBeforeDrawIsForced) { - m_consecutiveFailedDraws = 0; - // We need to force a draw, but it doesn't make sense to do this until - // we've committed and have new textures. - m_needsForcedRedrawAfterNextCommit = true; - } - } else - m_consecutiveFailedDraws = 0; -} - -void CCSchedulerStateMachine::setNeedsCommit() -{ - m_needsCommit = true; -} - -void CCSchedulerStateMachine::setNeedsForcedCommit() -{ - m_needsForcedCommit = true; -} - -void CCSchedulerStateMachine::beginFrameComplete() -{ - ASSERT(m_commitState == COMMIT_STATE_FRAME_IN_PROGRESS); - m_commitState = COMMIT_STATE_UPDATING_RESOURCES; -} - -void CCSchedulerStateMachine::beginFrameAborted() -{ - ASSERT(m_commitState == COMMIT_STATE_FRAME_IN_PROGRESS); - m_commitState = COMMIT_STATE_IDLE; - setNeedsCommit(); -} - -void CCSchedulerStateMachine::beginUpdateMoreResourcesComplete(bool morePending) -{ - ASSERT(m_commitState == COMMIT_STATE_UPDATING_RESOURCES); - ASSERT(m_updateMoreResourcesPending); - m_updateMoreResourcesPending = false; - if (!morePending) - m_commitState = COMMIT_STATE_READY_TO_COMMIT; -} - -void CCSchedulerStateMachine::didLoseContext() -{ - if (m_contextState == CONTEXT_LOST || m_contextState == CONTEXT_RECREATING) - return; - m_contextState = CONTEXT_LOST; -} - -void CCSchedulerStateMachine::didRecreateContext() -{ - ASSERT(m_contextState == CONTEXT_RECREATING); - m_contextState = CONTEXT_ACTIVE; - setNeedsCommit(); -} - -void CCSchedulerStateMachine::setMaximumNumberOfFailedDrawsBeforeDrawIsForced(int numDraws) -{ - m_maximumNumberOfFailedDrawsBeforeDrawIsForced = numDraws; -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSchedulerStateMachine.h b/Source/WebCore/platform/graphics/chromium/cc/CCSchedulerStateMachine.h deleted file mode 100644 index 8babafab8..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSchedulerStateMachine.h +++ /dev/null @@ -1,186 +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 CCSchedulerStateMachine_h -#define CCSchedulerStateMachine_h - -#include <wtf/Noncopyable.h> -#include <wtf/text/WTFString.h> - -namespace WebCore { - -// The CCSchedulerStateMachine decides how to coordinate main thread activites -// like painting/running javascript with rendering and input activities on the -// impl thread. -// -// The state machine tracks internal state but is also influenced by external state. -// Internal state includes things like whether a frame has been requested, while -// external state includes things like the current time being near to the vblank time. -// -// The scheduler seperates "what to do next" from the updating of its internal state to -// make testing cleaner. -class CCSchedulerStateMachine { -public: - CCSchedulerStateMachine(); - - enum CommitState { - COMMIT_STATE_IDLE, - COMMIT_STATE_FRAME_IN_PROGRESS, - COMMIT_STATE_UPDATING_RESOURCES, - COMMIT_STATE_READY_TO_COMMIT, - COMMIT_STATE_WAITING_FOR_FIRST_DRAW, - }; - - enum TextureState { - LAYER_TEXTURE_STATE_UNLOCKED, - LAYER_TEXTURE_STATE_ACQUIRED_BY_MAIN_THREAD, - LAYER_TEXTURE_STATE_ACQUIRED_BY_IMPL_THREAD, - }; - - enum ContextState { - CONTEXT_ACTIVE, - CONTEXT_LOST, - CONTEXT_RECREATING, - }; - - bool commitPending() const - { - return m_commitState != COMMIT_STATE_IDLE; - } - - bool redrawPending() const { return m_needsRedraw; } - - enum Action { - ACTION_NONE, - ACTION_BEGIN_FRAME, - ACTION_BEGIN_UPDATE_MORE_RESOURCES, - ACTION_COMMIT, - ACTION_DRAW_IF_POSSIBLE, - ACTION_DRAW_FORCED, - ACTION_BEGIN_CONTEXT_RECREATION, - ACTION_ACQUIRE_LAYER_TEXTURES_FOR_MAIN_THREAD, - }; - Action nextAction() const; - void updateState(Action); - - // Indicates whether the scheduler needs a vsync callback in order to make - // progress. - bool vsyncCallbackNeeded() const; - - // Indicates that the system has entered and left a vsync callback. - // The scheduler will not draw more than once in a given vsync callback. - void didEnterVSync(); - void didLeaveVSync(); - - // Indicates whether the LayerTreeHostImpl is visible. - void setVisible(bool); - - // Indicates that a redraw is required, either due to the impl tree changing - // or the screen being damaged and simply needing redisplay. - void setNeedsRedraw(); - - // As setNeedsRedraw(), but ensures the draw will definitely happen even if - // we are not visible. - void setNeedsForcedRedraw(); - - // Indicates whether ACTION_DRAW_IF_POSSIBLE drew to the screen or not. - void didDrawIfPossibleCompleted(bool success); - - // Indicates that a new commit flow needs to be performed, either to pull - // updates from the main thread to the impl, or to push deltas from the impl - // thread to main. - void setNeedsCommit(); - - // As setNeedsCommit(), but ensures the beginFrame will definitely happen even if - // we are not visible. - void setNeedsForcedCommit(); - - // Call this only in response to receiving an ACTION_BEGIN_FRAME - // from nextState. Indicates that all painting is complete and that - // updating of compositor resources can begin. - void beginFrameComplete(); - - // Call this only in response to receiving an ACTION_BEGIN_FRAME - // from nextState if the client rejects the beginFrame message. - void beginFrameAborted(); - - // Call this only in response to receiving an ACTION_UPDATE_MORE_RESOURCES - // from nextState. Indicates that the specific update request completed. - void beginUpdateMoreResourcesComplete(bool morePending); - - // Request exclusive access to the textures that back single buffered - // layers on behalf of the main thread. Upon acqusition, - // ACTION_DRAW_IF_POSSIBLE will not draw until the main thread releases the - // textures to the impl thread by committing the layers. - void setMainThreadNeedsLayerTextures(); - - // Indicates whether we can successfully begin a frame at this time. - void setCanBeginFrame(bool can) { m_canBeginFrame = can; } - - // Indicates whether drawing would, at this time, make sense. - // canDraw can be used to supress flashes or checkerboarding - // when such behavior would be undesirable. - void setCanDraw(bool can) { m_canDraw = can; } - - void didLoseContext(); - void didRecreateContext(); - - // Exposed for testing purposes. - void setMaximumNumberOfFailedDrawsBeforeDrawIsForced(int); - - String toString(); - -protected: - bool shouldDrawForced() const; - bool drawSuspendedUntilCommit() const; - bool scheduledToDraw() const; - bool shouldDraw() const; - bool shouldAcquireLayerTexturesForMainThread() const; - bool hasDrawnThisFrame() const; - - CommitState m_commitState; - - int m_currentFrameNumber; - int m_lastFrameNumberWhereDrawWasCalled; - int m_consecutiveFailedDraws; - int m_maximumNumberOfFailedDrawsBeforeDrawIsForced; - bool m_needsRedraw; - bool m_needsForcedRedraw; - bool m_needsForcedRedrawAfterNextCommit; - bool m_needsCommit; - bool m_needsForcedCommit; - bool m_mainThreadNeedsLayerTextures; - bool m_updateMoreResourcesPending; - bool m_insideVSync; - bool m_visible; - bool m_canBeginFrame; - bool m_canDraw; - bool m_drawIfPossibleFailed; - TextureState m_textureState; - ContextState m_contextState; -}; - -} - -#endif // CCSchedulerStateMachine_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScopedTexture.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCScopedTexture.cpp deleted file mode 100644 index 774c2a488..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScopedTexture.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCScopedTexture.h" - -namespace WebCore { - -CCScopedTexture::CCScopedTexture(CCResourceProvider* resourceProvider) - : m_resourceProvider(resourceProvider) -{ - ASSERT(m_resourceProvider); -} - -CCScopedTexture::~CCScopedTexture() -{ - free(); -} - -bool CCScopedTexture::allocate(int pool, const IntSize& size, GC3Denum format, CCResourceProvider::TextureUsageHint hint) -{ - ASSERT(!id()); - ASSERT(!size.isEmpty()); - - setDimensions(size, format); - setId(m_resourceProvider->createResource(pool, size, format, hint)); - -#if !ASSERT_DISABLED - m_allocateThreadIdentifier = WTF::currentThread(); -#endif - - return id(); -} - -void CCScopedTexture::free() -{ - if (id()) { - ASSERT(m_allocateThreadIdentifier == WTF::currentThread()); - m_resourceProvider->deleteResource(id()); - } - setId(0); -} - -void CCScopedTexture::leak() -{ - setId(0); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScopedTexture.h b/Source/WebCore/platform/graphics/chromium/cc/CCScopedTexture.h deleted file mode 100644 index 2716d166e..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScopedTexture.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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CCScopedTexture_h -#define CCScopedTexture_h - -#include "CCTexture.h" - -#if !ASSERT_DISABLED -#include <wtf/MainThread.h> -#endif - -namespace WebCore { - -class CCScopedTexture : protected CCTexture { - WTF_MAKE_NONCOPYABLE(CCScopedTexture); -public: - static PassOwnPtr<CCScopedTexture> create(CCResourceProvider* resourceProvider) { return adoptPtr(new CCScopedTexture(resourceProvider)); } - virtual ~CCScopedTexture(); - - using CCTexture::id; - using CCTexture::size; - using CCTexture::format; - using CCTexture::bytes; - - bool allocate(int pool, const IntSize&, GC3Denum format, CCResourceProvider::TextureUsageHint); - void free(); - void leak(); - -protected: - explicit CCScopedTexture(CCResourceProvider*); - -private: - CCResourceProvider* m_resourceProvider; - -#if !ASSERT_DISABLED - ThreadIdentifier m_allocateThreadIdentifier; -#endif -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScopedThreadProxy.h b/Source/WebCore/platform/graphics/chromium/cc/CCScopedThreadProxy.h deleted file mode 100644 index 0e4530e1d..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScopedThreadProxy.h +++ /dev/null @@ -1,91 +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 CCScopedThreadProxy_h -#define CCScopedThreadProxy_h - -#include "CCThreadTask.h" -#include <wtf/ThreadSafeRefCounted.h> - -namespace WebCore { - -// This class is a proxy used to post tasks to an target thread from any other thread. The proxy may be shut down at -// any point from the target thread after which no more tasks posted to the proxy will run. In other words, all -// tasks posted via a proxy are scoped to the lifecycle of the proxy. Use this when posting tasks to an object that -// might die with tasks in flight. -// -// The proxy must be created and shut down from the target thread, tasks may be posted from any thread. -// -// Implementation note: Unlike ScopedRunnableMethodFactory in Chromium, pending tasks are not cancelled by actually -// destroying the proxy. Instead each pending task holds a reference to the proxy to avoid maintaining an explicit -// list of outstanding tasks. -class CCScopedThreadProxy : public ThreadSafeRefCounted<CCScopedThreadProxy> { -public: - static PassRefPtr<CCScopedThreadProxy> create(CCThread* targetThread) - { - ASSERT(currentThread() == targetThread->threadID()); - return adoptRef(new CCScopedThreadProxy(targetThread)); - } - - // Can be called from any thread. Posts a task to the target thread that runs unless - // shutdown() is called before it runs. - void postTask(PassOwnPtr<CCThread::Task> task) - { - ref(); - m_targetThread->postTask(createCCThreadTask(this, &CCScopedThreadProxy::runTaskIfNotShutdown, task)); - } - - void shutdown() - { - ASSERT(currentThread() == m_targetThread->threadID()); - ASSERT(!m_shutdown); - m_shutdown = true; - } - -private: - explicit CCScopedThreadProxy(CCThread* targetThread) - : m_targetThread(targetThread) - , m_shutdown(false) { } - - void runTaskIfNotShutdown(PassOwnPtr<CCThread::Task> popTask) - { - OwnPtr<CCThread::Task> task = popTask; - // If our shutdown flag is set, it's possible that m_targetThread has already been destroyed so don't - // touch it. - if (m_shutdown) { - deref(); - return; - } - ASSERT(currentThread() == m_targetThread->threadID()); - task->performTask(); - deref(); - } - - CCThread* m_targetThread; - bool m_shutdown; // Only accessed on the target thread -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationController.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationController.cpp deleted file mode 100644 index bb15f6cc2..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationController.cpp +++ /dev/null @@ -1,112 +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 "CCScrollbarAnimationController.h" - -#include "CCScrollbarLayerImpl.h" -#include <wtf/CurrentTime.h> - -#if OS(ANDROID) -#include "CCScrollbarAnimationControllerLinearFade.h" -#endif - -namespace WebCore { - -#if OS(ANDROID) -PassOwnPtr<CCScrollbarAnimationController> CCScrollbarAnimationController::create(CCLayerImpl* scrollLayer) -{ - static const double fadeoutDelay = 0.3; - static const double fadeoutLength = 0.3; - return CCScrollbarAnimationControllerLinearFade::create(scrollLayer, fadeoutDelay, fadeoutLength); -} -#else -PassOwnPtr<CCScrollbarAnimationController> CCScrollbarAnimationController::create(CCLayerImpl* scrollLayer) -{ - return adoptPtr(new CCScrollbarAnimationController(scrollLayer)); -} -#endif - -CCScrollbarAnimationController::CCScrollbarAnimationController(CCLayerImpl* scrollLayer) - : m_horizontalScrollbarLayer(0) - , m_verticalScrollbarLayer(0) -{ - CCScrollbarAnimationController::updateScrollOffsetAtTime(scrollLayer, 0); -} - -CCScrollbarAnimationController::~CCScrollbarAnimationController() -{ -} - -void CCScrollbarAnimationController::didPinchGestureBegin() -{ - didPinchGestureBeginAtTime(monotonicallyIncreasingTime()); -} - -void CCScrollbarAnimationController::didPinchGestureUpdate() -{ - didPinchGestureUpdateAtTime(monotonicallyIncreasingTime()); -} - -void CCScrollbarAnimationController::didPinchGestureEnd() -{ - didPinchGestureEndAtTime(monotonicallyIncreasingTime()); -} - -void CCScrollbarAnimationController::updateScrollOffset(CCLayerImpl* scrollLayer) -{ - updateScrollOffsetAtTime(scrollLayer, monotonicallyIncreasingTime()); -} - -IntSize CCScrollbarAnimationController::getScrollLayerBounds(const CCLayerImpl* scrollLayer) -{ - if (!scrollLayer->children().size()) - return IntSize(); - // Copy & paste from CCLayerTreeHostImpl... - // FIXME: Hardcoding the first child here is weird. Think of - // a cleaner way to get the contentBounds on the Impl side. - return scrollLayer->children()[0]->bounds(); -} - -void CCScrollbarAnimationController::updateScrollOffsetAtTime(CCLayerImpl* scrollLayer, double) -{ - m_currentPos = scrollLayer->scrollPosition() + scrollLayer->scrollDelta(); - m_totalSize = getScrollLayerBounds(scrollLayer); - m_maximum = scrollLayer->maxScrollPosition(); - - if (m_horizontalScrollbarLayer) { - m_horizontalScrollbarLayer->setCurrentPos(m_currentPos.x()); - m_horizontalScrollbarLayer->setTotalSize(m_totalSize.width()); - m_horizontalScrollbarLayer->setMaximum(m_maximum.width()); - } - - if (m_verticalScrollbarLayer) { - m_verticalScrollbarLayer->setCurrentPos(m_currentPos.y()); - m_verticalScrollbarLayer->setTotalSize(m_totalSize.height()); - m_verticalScrollbarLayer->setMaximum(m_maximum.height()); - } -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationController.h b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationController.h deleted file mode 100644 index c081fe7f9..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationController.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 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 CCScrollbarAnimationController_h -#define CCScrollbarAnimationController_h - -#include "FloatPoint.h" -#include "IntSize.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCLayerImpl; -class CCScrollbarLayerImpl; - -// This abstract class represents the compositor-side analogy of ScrollbarAnimator. -// Individual platforms should subclass it to provide specialized implementation. -class CCScrollbarAnimationController { -public: - // Implemented by subclass. - static PassOwnPtr<CCScrollbarAnimationController> create(CCLayerImpl* scrollLayer); - - virtual ~CCScrollbarAnimationController(); - - virtual bool animate(double monotonicTime) { return false; } - void didPinchGestureBegin(); - void didPinchGestureUpdate(); - void didPinchGestureEnd(); - void updateScrollOffset(CCLayerImpl* scrollLayer); - - void setHorizontalScrollbarLayer(CCScrollbarLayerImpl* layer) { m_horizontalScrollbarLayer = layer; } - CCScrollbarLayerImpl* horizontalScrollbarLayer() const { return m_horizontalScrollbarLayer; } - - void setVerticalScrollbarLayer(CCScrollbarLayerImpl* layer) { m_verticalScrollbarLayer = layer; } - CCScrollbarLayerImpl* verticalScrollbarLayer() const { return m_verticalScrollbarLayer; } - - FloatPoint currentPos() const { return m_currentPos; } - IntSize totalSize() const { return m_totalSize; } - IntSize maximum() const { return m_maximum; } - - virtual void didPinchGestureBeginAtTime(double monotonicTime) { } - virtual void didPinchGestureUpdateAtTime(double monotonicTime) { } - virtual void didPinchGestureEndAtTime(double monotonicTime) { } - virtual void updateScrollOffsetAtTime(CCLayerImpl* scrollLayer, double monotonicTime); - -protected: - explicit CCScrollbarAnimationController(CCLayerImpl* scrollLayer); - -private: - static IntSize getScrollLayerBounds(const CCLayerImpl*); - - // Beware of dangling pointer. Always update these during tree synchronization. - CCScrollbarLayerImpl* m_horizontalScrollbarLayer; - CCScrollbarLayerImpl* m_verticalScrollbarLayer; - - FloatPoint m_currentPos; - IntSize m_totalSize; - IntSize m_maximum; -}; - -} // namespace WebCore - -#endif // CCScrollbarAnimationController_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.cpp deleted file mode 100644 index ea97b1372..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.cpp +++ /dev/null @@ -1,98 +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 "CCScrollbarAnimationControllerLinearFade.h" - -#include "CCScrollbarLayerImpl.h" - -namespace WebCore { - -PassOwnPtr<CCScrollbarAnimationControllerLinearFade> CCScrollbarAnimationControllerLinearFade::create(CCLayerImpl* scrollLayer, double fadeoutDelay, double fadeoutLength) -{ - return adoptPtr(new CCScrollbarAnimationControllerLinearFade(scrollLayer, fadeoutDelay, fadeoutLength)); -} - -CCScrollbarAnimationControllerLinearFade::CCScrollbarAnimationControllerLinearFade(CCLayerImpl* scrollLayer, double fadeoutDelay, double fadeoutLength) - : CCScrollbarAnimationController(scrollLayer) - , m_lastAwakenTime(-100000000) // arbitrary invalid timestamp - , m_pinchGestureInEffect(false) - , m_fadeoutDelay(fadeoutDelay) - , m_fadeoutLength(fadeoutLength) -{ -} - -CCScrollbarAnimationControllerLinearFade::~CCScrollbarAnimationControllerLinearFade() -{ -} - -bool CCScrollbarAnimationControllerLinearFade::animate(double monotonicTime) -{ - float opacity = opacityAtTime(monotonicTime); - if (horizontalScrollbarLayer()) - horizontalScrollbarLayer()->setOpacity(opacity); - if (verticalScrollbarLayer()) - verticalScrollbarLayer()->setOpacity(opacity); - return opacity; -} - -void CCScrollbarAnimationControllerLinearFade::didPinchGestureUpdateAtTime(double) -{ - m_pinchGestureInEffect = true; -} - -void CCScrollbarAnimationControllerLinearFade::didPinchGestureEndAtTime(double monotonicTime) -{ - m_pinchGestureInEffect = false; - m_lastAwakenTime = monotonicTime; -} - -void CCScrollbarAnimationControllerLinearFade::updateScrollOffsetAtTime(CCLayerImpl* scrollLayer, double monotonicTime) -{ - FloatPoint previousPos = currentPos(); - CCScrollbarAnimationController::updateScrollOffsetAtTime(scrollLayer, monotonicTime); - - if (previousPos == currentPos()) - return; - - m_lastAwakenTime = monotonicTime; -} - -float CCScrollbarAnimationControllerLinearFade::opacityAtTime(double monotonicTime) -{ - if (m_pinchGestureInEffect) - return 1; - - double delta = monotonicTime - m_lastAwakenTime; - - if (delta <= m_fadeoutDelay) - return 1; - if (delta < m_fadeoutDelay + m_fadeoutLength) - return (m_fadeoutDelay + m_fadeoutLength - delta) / m_fadeoutLength; - return 0; -} - -} // namespace WebCore - diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.h b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.h deleted file mode 100644 index cd9e0f3c9..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarAnimationControllerLinearFade.h +++ /dev/null @@ -1,59 +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 CCScrollbarAnimationControllerLinearFade_h -#define CCScrollbarAnimationControllerLinearFade_h - -#include "CCScrollbarAnimationController.h" - -namespace WebCore { - -class CCScrollbarAnimationControllerLinearFade : public CCScrollbarAnimationController { -public: - static PassOwnPtr<CCScrollbarAnimationControllerLinearFade> create(CCLayerImpl* scrollLayer, double fadeoutDelay, double fadeoutLength); - - virtual ~CCScrollbarAnimationControllerLinearFade(); - - virtual bool animate(double monotonicTime) OVERRIDE; - - virtual void didPinchGestureUpdateAtTime(double monotonicTime) OVERRIDE; - virtual void didPinchGestureEndAtTime(double monotonicTime) OVERRIDE; - virtual void updateScrollOffsetAtTime(CCLayerImpl* scrollLayer, double monotonicTime) OVERRIDE; - -protected: - CCScrollbarAnimationControllerLinearFade(CCLayerImpl* scrollLayer, double fadeoutDelay, double fadeoutLength); - -private: - float opacityAtTime(double monotonicTime); - - double m_lastAwakenTime; - bool m_pinchGestureInEffect; - - double m_fadeoutDelay; - double m_fadeoutLength; -}; - -} // namespace WebCore - -#endif // CCScrollbarAnimationControllerLinearFade_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.cpp deleted file mode 100644 index 2ad23ae9e..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.cpp +++ /dev/null @@ -1,115 +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 "CCScrollbarGeometryFixedThumb.h" - -#include <cmath> -#include <public/WebRect.h> -#include <public/WebScrollbar.h> - -using WebKit::WebRect; -using WebKit::WebScrollbar; -using WebKit::WebScrollbarThemeGeometry; - -namespace WebCore { - -PassOwnPtr<CCScrollbarGeometryFixedThumb> CCScrollbarGeometryFixedThumb::create(PassOwnPtr<WebScrollbarThemeGeometry> geometry) -{ - return adoptPtr(new CCScrollbarGeometryFixedThumb(geometry)); -} - -CCScrollbarGeometryFixedThumb::~CCScrollbarGeometryFixedThumb() -{ -} - -void CCScrollbarGeometryFixedThumb::update(WebScrollbar* scrollbar) -{ - int length = CCScrollbarGeometryStub::thumbLength(scrollbar); - - if (scrollbar->orientation() == WebScrollbar::Horizontal) - m_thumbSize = IntSize(length, scrollbar->size().height); - else - m_thumbSize = IntSize(scrollbar->size().width, length); -} - -WebScrollbarThemeGeometry* CCScrollbarGeometryFixedThumb::clone() const -{ - CCScrollbarGeometryFixedThumb* geometry = new CCScrollbarGeometryFixedThumb(adoptPtr(CCScrollbarGeometryStub::clone())); - geometry->m_thumbSize = m_thumbSize; - return geometry; -} - -int CCScrollbarGeometryFixedThumb::thumbLength(WebScrollbar* scrollbar) -{ - if (scrollbar->orientation() == WebScrollbar::Horizontal) - return m_thumbSize.width(); - return m_thumbSize.height(); -} - -int CCScrollbarGeometryFixedThumb::thumbPosition(WebScrollbar* scrollbar) -{ - if (scrollbar->enabled()) { - float size = scrollbar->maximum(); - if (!size) - return 1; - int value = std::min(std::max(0, scrollbar->value()), scrollbar->maximum()); - float pos = (trackLength(scrollbar) - thumbLength(scrollbar)) * value / size; - return static_cast<int>(floorf((pos < 1 && pos > 0) ? 1 : pos)); - } - return 0; -} -void CCScrollbarGeometryFixedThumb::splitTrack(WebScrollbar* scrollbar, const WebRect& unconstrainedTrackRect, WebRect& beforeThumbRect, WebRect& thumbRect, WebRect& afterThumbRect) -{ - // This is a reimplementation of ScrollbarThemeComposite::splitTrack. - // Because the WebScrollbarThemeGeometry functions call down to native - // ScrollbarThemeComposite code which uses ScrollbarThemeComposite virtual - // helpers, there's no way to override a helper like thumbLength from - // the WebScrollbarThemeGeometry level. So, these three functions - // (splitTrack, thumbPosition, thumbLength) are copied here so that the - // WebScrollbarThemeGeometry helper functions are used instead and - // a fixed size thumbLength can be used. - - WebRect trackRect = constrainTrackRectToTrackPieces(scrollbar, unconstrainedTrackRect); - int thickness = scrollbar->orientation() == WebScrollbar::Horizontal ? scrollbar->size().height : scrollbar->size().width; - int thumbPos = thumbPosition(scrollbar); - if (scrollbar->orientation() == WebScrollbar::Horizontal) { - thumbRect = WebRect(trackRect.x + thumbPos, trackRect.y + (trackRect.height - thickness) / 2, thumbLength(scrollbar), thickness); - beforeThumbRect = WebRect(trackRect.x, trackRect.y, thumbPos + thumbRect.width / 2, trackRect.height); - afterThumbRect = WebRect(trackRect.x + beforeThumbRect.width, trackRect.y, trackRect.x + trackRect.width - beforeThumbRect.x - beforeThumbRect.width, trackRect.height); - } else { - thumbRect = WebRect(trackRect.x + (trackRect.width - thickness) / 2, trackRect.y + thumbPos, thickness, thumbLength(scrollbar)); - beforeThumbRect = WebRect(trackRect.x, trackRect.y, trackRect.width, thumbPos + thumbRect.height / 2); - afterThumbRect = WebRect(trackRect.x, trackRect.y + beforeThumbRect.height, trackRect.width, trackRect.y + trackRect.height - beforeThumbRect.y - beforeThumbRect.height); - } -} - -CCScrollbarGeometryFixedThumb::CCScrollbarGeometryFixedThumb(PassOwnPtr<WebScrollbarThemeGeometry> geometry) - : CCScrollbarGeometryStub(geometry) -{ -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.h b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.h deleted file mode 100644 index 049fb93ea..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryFixedThumb.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCScrollbarGeometryFixedThumb_h -#define CCScrollbarGeometryFixedThumb_h - -#include "CCScrollbarGeometryStub.h" -#include "IntSize.h" - -namespace WebCore { - -// This scrollbar geometry class behaves exactly like a normal geometry except -// it always returns a fixed thumb length. This allows a page to zoom (changing -// the total size of the scrollable area, changing the thumb length) while not -// requiring the thumb resource to be repainted. -class CCScrollbarGeometryFixedThumb : public CCScrollbarGeometryStub { -public: - static PassOwnPtr<CCScrollbarGeometryFixedThumb> create(PassOwnPtr<WebKit::WebScrollbarThemeGeometry>); - virtual ~CCScrollbarGeometryFixedThumb(); - - // Update thumb length from scrollbar - void update(WebKit::WebScrollbar*); - - // WebScrollbarThemeGeometry interface - virtual WebKit::WebScrollbarThemeGeometry* clone() const OVERRIDE; - virtual int thumbLength(WebKit::WebScrollbar*) OVERRIDE; - virtual int thumbPosition(WebKit::WebScrollbar*) OVERRIDE; - virtual void splitTrack(WebKit::WebScrollbar*, const WebKit::WebRect& track, WebKit::WebRect& startTrack, WebKit::WebRect& thumb, WebKit::WebRect& endTrack) OVERRIDE; - -private: - explicit CCScrollbarGeometryFixedThumb(PassOwnPtr<WebKit::WebScrollbarThemeGeometry>); - - IntSize m_thumbSize; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryStub.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryStub.cpp deleted file mode 100644 index 8e4f6bf80..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryStub.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 "CCScrollbarGeometryStub.h" - -using WebKit::WebRect; -using WebKit::WebScrollbar; -using WebKit::WebScrollbarThemeGeometry; - -namespace WebCore { - -CCScrollbarGeometryStub::CCScrollbarGeometryStub(PassOwnPtr<WebScrollbarThemeGeometry> geometry) - : m_geometry(geometry) -{ -} - -CCScrollbarGeometryStub::~CCScrollbarGeometryStub() -{ -} - -WebScrollbarThemeGeometry* CCScrollbarGeometryStub::clone() const -{ - return m_geometry->clone(); -} - -int CCScrollbarGeometryStub::thumbPosition(WebScrollbar* scrollbar) -{ - return m_geometry->thumbPosition(scrollbar); -} - -int CCScrollbarGeometryStub::thumbLength(WebScrollbar* scrollbar) -{ - return m_geometry->thumbLength(scrollbar); -} - -int CCScrollbarGeometryStub::trackPosition(WebScrollbar* scrollbar) -{ - return m_geometry->trackPosition(scrollbar); -} - -int CCScrollbarGeometryStub::trackLength(WebScrollbar* scrollbar) -{ - return m_geometry->trackLength(scrollbar); -} - -bool CCScrollbarGeometryStub::hasButtons(WebScrollbar* scrollbar) -{ - return m_geometry->hasButtons(scrollbar); -} - -bool CCScrollbarGeometryStub::hasThumb(WebScrollbar* scrollbar) -{ - return m_geometry->hasThumb(scrollbar); -} - -WebRect CCScrollbarGeometryStub::trackRect(WebScrollbar* scrollbar) -{ - return m_geometry->trackRect(scrollbar); -} - -WebRect CCScrollbarGeometryStub::thumbRect(WebScrollbar* scrollbar) -{ - return m_geometry->thumbRect(scrollbar); -} - -int CCScrollbarGeometryStub::minimumThumbLength(WebScrollbar* scrollbar) -{ - return m_geometry->minimumThumbLength(scrollbar); -} - -int CCScrollbarGeometryStub::scrollbarThickness(WebScrollbar* scrollbar) -{ - return m_geometry->scrollbarThickness(scrollbar); -} - -WebRect CCScrollbarGeometryStub::backButtonStartRect(WebScrollbar* scrollbar) -{ - return m_geometry->backButtonStartRect(scrollbar); -} - -WebRect CCScrollbarGeometryStub::backButtonEndRect(WebScrollbar* scrollbar) -{ - return m_geometry->backButtonEndRect(scrollbar); -} - -WebRect CCScrollbarGeometryStub::forwardButtonStartRect(WebScrollbar* scrollbar) -{ - return m_geometry->forwardButtonStartRect(scrollbar); -} - -WebRect CCScrollbarGeometryStub::forwardButtonEndRect(WebScrollbar* scrollbar) -{ - return m_geometry->forwardButtonEndRect(scrollbar); -} - -WebRect CCScrollbarGeometryStub::constrainTrackRectToTrackPieces(WebScrollbar* scrollbar, const WebRect& rect) -{ - return m_geometry->constrainTrackRectToTrackPieces(scrollbar, rect); -} - -void CCScrollbarGeometryStub::splitTrack(WebScrollbar* scrollbar, const WebRect& unconstrainedTrackRect, WebRect& beforeThumbRect, WebRect& thumbRect, WebRect& afterThumbRect) -{ - m_geometry->splitTrack(scrollbar, unconstrainedTrackRect, beforeThumbRect, thumbRect, afterThumbRect); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryStub.h b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryStub.h deleted file mode 100644 index f10b28191..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarGeometryStub.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 CCScrollbarGeometryStub_h -#define CCScrollbarGeometryStub_h - -#include <public/WebScrollbarThemeGeometry.h> -#include <wtf/OwnPtr.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -// This subclass wraps an existing scrollbar geometry class so that -// another class can derive from it and override specific functions, while -// passing through the remaining ones. -class CCScrollbarGeometryStub : public WebKit::WebScrollbarThemeGeometry { -public: - virtual ~CCScrollbarGeometryStub(); - - // Allow derived classes to update themselves from a scrollbar. - void update(WebKit::WebScrollbar*) { } - - // WebScrollbarThemeGeometry interface - virtual WebKit::WebScrollbarThemeGeometry* clone() const OVERRIDE; - virtual int thumbPosition(WebKit::WebScrollbar*) OVERRIDE; - virtual int thumbLength(WebKit::WebScrollbar*) OVERRIDE; - virtual int trackPosition(WebKit::WebScrollbar*) OVERRIDE; - virtual int trackLength(WebKit::WebScrollbar*) OVERRIDE; - virtual bool hasButtons(WebKit::WebScrollbar*) OVERRIDE; - virtual bool hasThumb(WebKit::WebScrollbar*) OVERRIDE; - virtual WebKit::WebRect trackRect(WebKit::WebScrollbar*) OVERRIDE; - virtual WebKit::WebRect thumbRect(WebKit::WebScrollbar*) OVERRIDE; - virtual int minimumThumbLength(WebKit::WebScrollbar*) OVERRIDE; - virtual int scrollbarThickness(WebKit::WebScrollbar*) OVERRIDE; - virtual WebKit::WebRect backButtonStartRect(WebKit::WebScrollbar*) OVERRIDE; - virtual WebKit::WebRect backButtonEndRect(WebKit::WebScrollbar*) OVERRIDE; - virtual WebKit::WebRect forwardButtonStartRect(WebKit::WebScrollbar*) OVERRIDE; - virtual WebKit::WebRect forwardButtonEndRect(WebKit::WebScrollbar*) OVERRIDE; - virtual WebKit::WebRect constrainTrackRectToTrackPieces(WebKit::WebScrollbar*, const WebKit::WebRect&) OVERRIDE; - virtual void splitTrack(WebKit::WebScrollbar*, const WebKit::WebRect& track, WebKit::WebRect& startTrack, WebKit::WebRect& thumb, WebKit::WebRect& endTrack) OVERRIDE; - -protected: - explicit CCScrollbarGeometryStub(PassOwnPtr<WebKit::WebScrollbarThemeGeometry>); - -private: - OwnPtr<WebKit::WebScrollbarThemeGeometry> m_geometry; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarLayerImpl.cpp deleted file mode 100644 index 9f375b8df..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarLayerImpl.cpp +++ /dev/null @@ -1,227 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCScrollbarLayerImpl.h" - -#include "CCQuadSink.h" -#include "CCScrollbarAnimationController.h" -#include "CCTextureDrawQuad.h" - -using WebKit::WebRect; -using WebKit::WebScrollbar; - -namespace WebCore { - -PassOwnPtr<CCScrollbarLayerImpl> CCScrollbarLayerImpl::create(int id) -{ - return adoptPtr(new CCScrollbarLayerImpl(id)); -} - -CCScrollbarLayerImpl::CCScrollbarLayerImpl(int id) - : CCLayerImpl(id) - , m_scrollbar(this) - , m_backTrackResourceId(0) - , m_foreTrackResourceId(0) - , m_thumbResourceId(0) - , m_scrollbarOverlayStyle(WebScrollbar::ScrollbarOverlayStyleDefault) - , m_orientation(WebScrollbar::Horizontal) - , m_controlSize(WebScrollbar::RegularScrollbar) - , m_pressedPart(WebScrollbar::NoPart) - , m_hoveredPart(WebScrollbar::NoPart) - , m_isScrollableAreaActive(false) - , m_isScrollViewScrollbar(false) - , m_enabled(false) - , m_isCustomScrollbar(false) - , m_isOverlayScrollbar(false) - , m_isAlphaLocked(false) -{ -} - -void CCScrollbarLayerImpl::setScrollbarGeometry(PassOwnPtr<CCScrollbarGeometryFixedThumb> geometry) -{ - m_geometry = geometry; -} - -void CCScrollbarLayerImpl::setScrollbarData(WebScrollbar* scrollbar) -{ - m_scrollbarOverlayStyle = scrollbar->scrollbarOverlayStyle(); - m_orientation = scrollbar->orientation(); - m_controlSize = scrollbar->controlSize(); - m_pressedPart = scrollbar->pressedPart(); - m_hoveredPart = scrollbar->hoveredPart(); - m_isScrollableAreaActive = scrollbar->isScrollableAreaActive(); - m_isScrollViewScrollbar = scrollbar->isScrollViewScrollbar(); - m_enabled = scrollbar->enabled(); - m_isCustomScrollbar = scrollbar->isCustomScrollbar(); - m_isOverlayScrollbar = scrollbar->isOverlay(); - - scrollbar->getTickmarks(m_tickmarks); - - m_geometry->update(scrollbar); -} - -static FloatRect toUVRect(const WebRect& r, const IntRect& bounds) -{ - return FloatRect(static_cast<float>(r.x) / bounds.width(), static_cast<float>(r.y) / bounds.height(), - static_cast<float>(r.width) / bounds.width(), static_cast<float>(r.height) / bounds.height()); -} - -void CCScrollbarLayerImpl::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData) -{ - bool premultipledAlpha = false; - bool flipped = false; - FloatRect uvRect(0, 0, 1, 1); - IntRect boundsRect(IntPoint(), contentBounds()); - - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState()); - appendDebugBorderQuad(quadSink, sharedQuadState, appendQuadsData); - - WebRect thumbRect, backTrackRect, foreTrackRect; - m_geometry->splitTrack(&m_scrollbar, m_geometry->trackRect(&m_scrollbar), backTrackRect, thumbRect, foreTrackRect); - if (!m_geometry->hasThumb(&m_scrollbar)) - thumbRect = WebRect(); - - if (m_thumbResourceId && !thumbRect.isEmpty()) { - OwnPtr<CCTextureDrawQuad> quad = CCTextureDrawQuad::create(sharedQuadState, IntRect(thumbRect.x, thumbRect.y, thumbRect.width, thumbRect.height), m_thumbResourceId, premultipledAlpha, uvRect, flipped); - quad->setNeedsBlending(); - quadSink.append(quad.release(), appendQuadsData); - } - - if (!m_backTrackResourceId) - return; - - // We only paint the track in two parts if we were given a texture for the forward track part. - if (m_foreTrackResourceId && !foreTrackRect.isEmpty()) - quadSink.append(CCTextureDrawQuad::create(sharedQuadState, IntRect(foreTrackRect.x, foreTrackRect.y, foreTrackRect.width, foreTrackRect.height), m_foreTrackResourceId, premultipledAlpha, toUVRect(foreTrackRect, boundsRect), flipped), appendQuadsData); - - // Order matters here: since the back track texture is being drawn to the entire contents rect, we must append it after the thumb and - // fore track quads. The back track texture contains (and displays) the buttons. - if (!boundsRect.isEmpty()) - quadSink.append(CCTextureDrawQuad::create(sharedQuadState, IntRect(boundsRect), m_backTrackResourceId, premultipledAlpha, uvRect, flipped), appendQuadsData); -} - -void CCScrollbarLayerImpl::didLoseContext() -{ - m_backTrackResourceId = 0; - m_foreTrackResourceId = 0; - m_thumbResourceId = 0; -} - -bool CCScrollbarLayerImpl::CCScrollbar::isOverlay() const -{ - return m_owner->m_isOverlayScrollbar; -} - -int CCScrollbarLayerImpl::CCScrollbar::value() const -{ - return m_owner->m_currentPos; -} - -WebKit::WebPoint CCScrollbarLayerImpl::CCScrollbar::location() const -{ - return WebKit::WebPoint(); -} - -WebKit::WebSize CCScrollbarLayerImpl::CCScrollbar::size() const -{ - return WebKit::WebSize(m_owner->contentBounds().width(), m_owner->contentBounds().height()); -} - -bool CCScrollbarLayerImpl::CCScrollbar::enabled() const -{ - return m_owner->m_enabled; -} - -int CCScrollbarLayerImpl::CCScrollbar::maximum() const -{ - return m_owner->m_maximum; -} - -int CCScrollbarLayerImpl::CCScrollbar::totalSize() const -{ - return m_owner->m_totalSize; -} - -bool CCScrollbarLayerImpl::CCScrollbar::isScrollViewScrollbar() const -{ - return m_owner->m_isScrollViewScrollbar; -} - -bool CCScrollbarLayerImpl::CCScrollbar::isScrollableAreaActive() const -{ - return m_owner->m_isScrollableAreaActive; -} - -void CCScrollbarLayerImpl::CCScrollbar::getTickmarks(WebKit::WebVector<WebRect>& tickmarks) const -{ - tickmarks = m_owner->m_tickmarks; -} - -WebScrollbar::ScrollbarControlSize CCScrollbarLayerImpl::CCScrollbar::controlSize() const -{ - return m_owner->m_controlSize; -} - -WebScrollbar::ScrollbarPart CCScrollbarLayerImpl::CCScrollbar::pressedPart() const -{ - return m_owner->m_pressedPart; -} - -WebScrollbar::ScrollbarPart CCScrollbarLayerImpl::CCScrollbar::hoveredPart() const -{ - return m_owner->m_hoveredPart; -} - -WebScrollbar::ScrollbarOverlayStyle CCScrollbarLayerImpl::CCScrollbar::scrollbarOverlayStyle() const -{ - return m_owner->m_scrollbarOverlayStyle; -} - -WebScrollbar::Orientation CCScrollbarLayerImpl::CCScrollbar::orientation() const -{ - return m_owner->m_orientation; -} - -bool CCScrollbarLayerImpl::CCScrollbar::isCustomScrollbar() const -{ - return m_owner->m_isCustomScrollbar; -} - -bool CCScrollbarLayerImpl::CCScrollbar::isAlphaLocked() const -{ - return m_owner->m_isAlphaLocked; -} - -void CCScrollbarLayerImpl::CCScrollbar::setIsAlphaLocked(bool flag) -{ - m_owner->m_isAlphaLocked = flag; -} - -} -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarLayerImpl.h deleted file mode 100644 index 9923ce4cb..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCScrollbarLayerImpl.h +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 CCScrollbarLayerImpl_h -#define CCScrollbarLayerImpl_h - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCLayerImpl.h" -#include "CCScrollbarGeometryFixedThumb.h" -#include <public/WebRect.h> -#include <public/WebScrollbar.h> -#include <public/WebVector.h> - -namespace WebCore { - -class ScrollView; - -class CCScrollbarLayerImpl : public CCLayerImpl { -public: - static PassOwnPtr<CCScrollbarLayerImpl> create(int id); - - CCScrollbarGeometryFixedThumb* scrollbarGeometry() const { return m_geometry.get(); } - void setScrollbarGeometry(PassOwnPtr<CCScrollbarGeometryFixedThumb>); - void setScrollbarData(WebKit::WebScrollbar*); - - void setBackTrackResourceId(CCResourceProvider::ResourceId id) { m_backTrackResourceId = id; } - void setForeTrackResourceId(CCResourceProvider::ResourceId id) { m_foreTrackResourceId = id; } - void setThumbResourceId(CCResourceProvider::ResourceId id) { m_thumbResourceId = id; } - - float currentPos() const { return m_currentPos; } - void setCurrentPos(float currentPos) { m_currentPos = currentPos; } - - int totalSize() const { return m_totalSize; } - void setTotalSize(int totalSize) { m_totalSize = totalSize; } - - int maximum() const { return m_maximum; } - void setMaximum(int maximum) { m_maximum = maximum; } - - WebKit::WebScrollbar::Orientation orientation() const { return m_orientation; } - - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) OVERRIDE; - - virtual void didLoseContext() OVERRIDE; - -protected: - explicit CCScrollbarLayerImpl(int id); - -private: - // nested class only to avoid namespace problem - class CCScrollbar : public WebKit::WebScrollbar { - public: - explicit CCScrollbar(CCScrollbarLayerImpl* owner) : m_owner(owner) { } - - // WebScrollbar implementation - virtual bool isOverlay() const; - virtual int value() const; - virtual WebKit::WebPoint location() const; - virtual WebKit::WebSize size() const; - virtual bool enabled() const; - virtual int maximum() const; - virtual int totalSize() const; - virtual bool isScrollViewScrollbar() const; - virtual bool isScrollableAreaActive() const; - virtual void getTickmarks(WebKit::WebVector<WebKit::WebRect>& tickmarks) const; - virtual WebScrollbar::ScrollbarControlSize controlSize() const; - virtual WebScrollbar::ScrollbarPart pressedPart() const; - virtual WebScrollbar::ScrollbarPart hoveredPart() const; - virtual WebScrollbar::ScrollbarOverlayStyle scrollbarOverlayStyle() const; - virtual WebScrollbar::Orientation orientation() const; - virtual bool isCustomScrollbar() const; - virtual bool isAlphaLocked() const OVERRIDE; - virtual void setIsAlphaLocked(bool) OVERRIDE; - - private: - CCScrollbarLayerImpl* m_owner; - - }; - - CCScrollbar m_scrollbar; - - CCResourceProvider::ResourceId m_backTrackResourceId; - CCResourceProvider::ResourceId m_foreTrackResourceId; - CCResourceProvider::ResourceId m_thumbResourceId; - - OwnPtr<CCScrollbarGeometryFixedThumb> m_geometry; - - // Data to implement CCScrollbar - WebKit::WebScrollbar::ScrollbarOverlayStyle m_scrollbarOverlayStyle; - WebKit::WebVector<WebKit::WebRect> m_tickmarks; - WebKit::WebScrollbar::Orientation m_orientation; - WebKit::WebScrollbar::ScrollbarControlSize m_controlSize; - WebKit::WebScrollbar::ScrollbarPart m_pressedPart; - WebKit::WebScrollbar::ScrollbarPart m_hoveredPart; - - float m_currentPos; - int m_totalSize; - int m_maximum; - - bool m_isScrollableAreaActive; - bool m_isScrollViewScrollbar; - bool m_enabled; - bool m_isCustomScrollbar; - bool m_isOverlayScrollbar; - bool m_isAlphaLocked; -}; - -} -#endif // USE(ACCELERATED_COMPOSITING) - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSettings.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCSettings.cpp deleted file mode 100644 index 1bcab7460..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSettings.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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCSettings.h" - -namespace { -static bool s_perTilePaintingEnabled = false; -static bool s_partialSwapEnabled = false; -static bool s_acceleratedAnimationEnabled = false; -} // namespace - -namespace WebCore { - -bool CCSettings::perTilePaintingEnabled() { return s_perTilePaintingEnabled; } -void CCSettings::setPerTilePaintingEnabled(bool enabled) { s_perTilePaintingEnabled = enabled; } - -bool CCSettings::partialSwapEnabled() { return s_partialSwapEnabled; } -void CCSettings::setPartialSwapEnabled(bool enabled) { s_partialSwapEnabled = enabled; } - -bool CCSettings::acceleratedAnimationEnabled() { return s_acceleratedAnimationEnabled; } -void CCSettings::setAcceleratedAnimationEnabled(bool enabled) { s_acceleratedAnimationEnabled = enabled; } - -void CCSettings::reset() -{ - s_perTilePaintingEnabled = false; - s_partialSwapEnabled = false; - s_acceleratedAnimationEnabled = false; -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSettings.h b/Source/WebCore/platform/graphics/chromium/cc/CCSettings.h deleted file mode 100644 index 88f8c2ffd..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSettings.h +++ /dev/null @@ -1,51 +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 CCSettings_h -#define CCSettings_h - -#include "IntSize.h" - -namespace WebCore { - -class CCSettings { -public: - static bool perTilePaintingEnabled(); - static bool partialSwapEnabled(); - static bool acceleratedAnimationEnabled(); - - // These setters should only be used on the main thread before the layer - // renderer is initialized. - static void setPerTilePaintingEnabled(bool); - static void setPartialSwapEnabled(bool); - static void setAcceleratedAnimationEnabled(bool); - - // These settings are meant to be set only once, and only read thereafter. - // This function is only for resetting settings in tests. - static void reset(); -}; - -} // namespace WebCore - -#endif // CCSettings_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSharedQuadState.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCSharedQuadState.cpp deleted file mode 100644 index b6d433e52..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSharedQuadState.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCSharedQuadState.h" - -#include "FloatQuad.h" - -namespace WebCore { - -PassOwnPtr<CCSharedQuadState> CCSharedQuadState::create(const WebKit::WebTransformationMatrix& quadTransform, const IntRect& visibleContentRect, const IntRect& clippedRectInTarget, float opacity, bool opaque) -{ - return adoptPtr(new CCSharedQuadState(quadTransform, visibleContentRect, clippedRectInTarget, opacity, opaque)); -} - -CCSharedQuadState::CCSharedQuadState(const WebKit::WebTransformationMatrix& quadTransform, const IntRect& visibleContentRect, const IntRect& clippedRectInTarget, float opacity, bool opaque) - : id(-1) - , quadTransform(quadTransform) - , visibleContentRect(visibleContentRect) - , clippedRectInTarget(clippedRectInTarget) - , opacity(opacity) - , opaque(opaque) -{ -} - -PassOwnPtr<CCSharedQuadState> CCSharedQuadState::copy() const -{ - OwnPtr<CCSharedQuadState> copiedState(create(quadTransform, visibleContentRect, clippedRectInTarget, opacity, opaque)); - copiedState->id = id; - return copiedState.release(); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSharedQuadState.h b/Source/WebCore/platform/graphics/chromium/cc/CCSharedQuadState.h deleted file mode 100644 index b2ae63d39..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSharedQuadState.h +++ /dev/null @@ -1,54 +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 CCSharedQuadState_h -#define CCSharedQuadState_h - -#include "IntRect.h" -#include <public/WebTransformationMatrix.h> -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -struct CCSharedQuadState { - int id; - - // Transforms from quad's original content space to its target content space. - WebKit::WebTransformationMatrix quadTransform; - // This rect lives in the content space for the quad's originating layer. - IntRect visibleContentRect; - IntRect clippedRectInTarget; - float opacity; - bool opaque; - - static PassOwnPtr<CCSharedQuadState> create(const WebKit::WebTransformationMatrix& quadTransform, const IntRect& visibleContentRect, const IntRect& clippedRectInTarget, float opacity, bool opaque); - CCSharedQuadState(const WebKit::WebTransformationMatrix& quadTransform, const IntRect& visibleContentRect, const IntRect& clippedRectInTarget, float opacity, bool opaque); - - PassOwnPtr<CCSharedQuadState> copy() const; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSingleThreadProxy.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCSingleThreadProxy.cpp deleted file mode 100644 index e2e8f6956..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSingleThreadProxy.cpp +++ /dev/null @@ -1,376 +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 "CCSingleThreadProxy.h" - -#include "CCDrawQuad.h" -#include "CCGraphicsContext.h" -#include "CCLayerTreeHost.h" -#include "CCTextureUpdateController.h" -#include "CCTimer.h" -#include "TraceEvent.h" -#include <wtf/CurrentTime.h> - -using namespace WTF; - -namespace WebCore { - -PassOwnPtr<CCProxy> CCSingleThreadProxy::create(CCLayerTreeHost* layerTreeHost) -{ - return adoptPtr(new CCSingleThreadProxy(layerTreeHost)); -} - -CCSingleThreadProxy::CCSingleThreadProxy(CCLayerTreeHost* layerTreeHost) - : m_layerTreeHost(layerTreeHost) - , m_contextLost(false) - , m_rendererInitialized(false) - , m_nextFrameIsNewlyCommittedFrame(false) -{ - TRACE_EVENT0("cc", "CCSingleThreadProxy::CCSingleThreadProxy"); - ASSERT(CCProxy::isMainThread()); -} - -void CCSingleThreadProxy::start() -{ - DebugScopedSetImplThread impl; - m_layerTreeHostImpl = m_layerTreeHost->createLayerTreeHostImpl(this); -} - -CCSingleThreadProxy::~CCSingleThreadProxy() -{ - TRACE_EVENT0("cc", "CCSingleThreadProxy::~CCSingleThreadProxy"); - ASSERT(CCProxy::isMainThread()); - ASSERT(!m_layerTreeHostImpl && !m_layerTreeHost); // make sure stop() got called. -} - -bool CCSingleThreadProxy::compositeAndReadback(void *pixels, const IntRect& rect) -{ - TRACE_EVENT0("cc", "CCSingleThreadProxy::compositeAndReadback"); - ASSERT(CCProxy::isMainThread()); - - if (!commitAndComposite()) - return false; - - m_layerTreeHostImpl->readback(pixels, rect); - - if (m_layerTreeHostImpl->isContextLost()) - return false; - - m_layerTreeHostImpl->swapBuffers(); - didSwapFrame(); - - return true; -} - -void CCSingleThreadProxy::startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, double duration) -{ - m_layerTreeHostImpl->startPageScaleAnimation(targetPosition, useAnchor, scale, monotonicallyIncreasingTime(), duration); -} - -void CCSingleThreadProxy::finishAllRendering() -{ - ASSERT(CCProxy::isMainThread()); - { - DebugScopedSetImplThread impl; - m_layerTreeHostImpl->finishAllRendering(); - } -} - -bool CCSingleThreadProxy::isStarted() const -{ - ASSERT(CCProxy::isMainThread()); - return m_layerTreeHostImpl; -} - -bool CCSingleThreadProxy::initializeContext() -{ - ASSERT(CCProxy::isMainThread()); - OwnPtr<CCGraphicsContext> context = m_layerTreeHost->createContext(); - if (!context) - return false; - m_contextBeforeInitialization = context.release(); - return true; -} - -void CCSingleThreadProxy::setSurfaceReady() -{ - // Scheduling is controlled by the embedder in the single thread case, so nothing to do. -} - -void CCSingleThreadProxy::setVisible(bool visible) -{ - DebugScopedSetImplThread impl; - m_layerTreeHostImpl->setVisible(visible); -} - -bool CCSingleThreadProxy::initializeRenderer() -{ - ASSERT(CCProxy::isMainThread()); - ASSERT(m_contextBeforeInitialization); - { - DebugScopedSetImplThread impl; - bool ok = m_layerTreeHostImpl->initializeRenderer(m_contextBeforeInitialization.release(), UnthrottledUploader); - if (ok) { - m_rendererInitialized = true; - m_RendererCapabilitiesForMainThread = m_layerTreeHostImpl->rendererCapabilities(); - } - - return ok; - } -} - -bool CCSingleThreadProxy::recreateContext() -{ - TRACE_EVENT0("cc", "CCSingleThreadProxy::recreateContext"); - ASSERT(CCProxy::isMainThread()); - ASSERT(m_contextLost); - - OwnPtr<CCGraphicsContext> context = m_layerTreeHost->createContext(); - if (!context) - return false; - - bool initialized; - { - DebugScopedSetMainThreadBlocked mainThreadBlocked; - DebugScopedSetImplThread impl; - if (!m_layerTreeHostImpl->contentsTexturesPurged()) - m_layerTreeHost->deleteContentsTexturesOnImplThread(m_layerTreeHostImpl->resourceProvider()); - initialized = m_layerTreeHostImpl->initializeRenderer(context.release(), UnthrottledUploader); - if (initialized) { - m_RendererCapabilitiesForMainThread = m_layerTreeHostImpl->rendererCapabilities(); - } - } - - if (initialized) - m_contextLost = false; - - return initialized; -} - -void CCSingleThreadProxy::implSideRenderingStats(CCRenderingStats& stats) -{ - m_layerTreeHostImpl->renderingStats(stats); -} - -const RendererCapabilities& CCSingleThreadProxy::rendererCapabilities() const -{ - ASSERT(m_rendererInitialized); - // Note: this gets called during the commit by the "impl" thread - return m_RendererCapabilitiesForMainThread; -} - -void CCSingleThreadProxy::loseContext() -{ - ASSERT(CCProxy::isMainThread()); - m_layerTreeHost->didLoseContext(); - m_contextLost = true; -} - -void CCSingleThreadProxy::setNeedsAnimate() -{ - // CCThread-only feature - ASSERT_NOT_REACHED(); -} - -void CCSingleThreadProxy::doCommit(CCTextureUpdateQueue& queue) -{ - ASSERT(CCProxy::isMainThread()); - // Commit immediately - { - DebugScopedSetMainThreadBlocked mainThreadBlocked; - DebugScopedSetImplThread impl; - - m_layerTreeHostImpl->beginCommit(); - - m_layerTreeHost->beginCommitOnImplThread(m_layerTreeHostImpl.get()); - - // CCTextureUpdateController::updateTextures is non-blocking and will - // return without updating any textures if the uploader is busy. This - // shouldn't be a problem here as the throttled uploader isn't used in - // single thread mode. For correctness, loop until no more updates are - // pending. - while (queue.hasMoreUpdates()) - CCTextureUpdateController::updateTextures(m_layerTreeHostImpl->resourceProvider(), m_layerTreeHostImpl->renderer()->textureCopier(), m_layerTreeHostImpl->renderer()->textureUploader(), &queue, maxPartialTextureUpdates()); - - m_layerTreeHost->finishCommitOnImplThread(m_layerTreeHostImpl.get()); - - m_layerTreeHostImpl->commitComplete(); - -#if !ASSERT_DISABLED - // In the single-threaded case, the scroll deltas should never be - // touched on the impl layer tree. - OwnPtr<CCScrollAndScaleSet> scrollInfo = m_layerTreeHostImpl->processScrollDeltas(); - ASSERT(!scrollInfo->scrolls.size()); -#endif - } - m_layerTreeHost->commitComplete(); - m_nextFrameIsNewlyCommittedFrame = true; -} - -void CCSingleThreadProxy::setNeedsCommit() -{ - ASSERT(CCProxy::isMainThread()); - m_layerTreeHost->scheduleComposite(); -} - -void CCSingleThreadProxy::setNeedsRedraw() -{ - // FIXME: Once we move render_widget scheduling into this class, we can - // treat redraw requests more efficiently than commitAndRedraw requests. - m_layerTreeHostImpl->setFullRootLayerDamage(); - setNeedsCommit(); -} - -bool CCSingleThreadProxy::commitRequested() const -{ - return false; -} - -void CCSingleThreadProxy::didAddAnimation() -{ -} - -void CCSingleThreadProxy::stop() -{ - TRACE_EVENT0("cc", "CCSingleThreadProxy::stop"); - ASSERT(CCProxy::isMainThread()); - { - DebugScopedSetMainThreadBlocked mainThreadBlocked; - DebugScopedSetImplThread impl; - - if (!m_layerTreeHostImpl->contentsTexturesPurged()) - m_layerTreeHost->deleteContentsTexturesOnImplThread(m_layerTreeHostImpl->resourceProvider()); - m_layerTreeHostImpl.clear(); - } - m_layerTreeHost = 0; -} - -void CCSingleThreadProxy::postAnimationEventsToMainThreadOnImplThread(PassOwnPtr<CCAnimationEventsVector> events, double wallClockTime) -{ - ASSERT(CCProxy::isImplThread()); - DebugScopedSetMainThread main; - m_layerTreeHost->setAnimationEvents(events, wallClockTime); -} - -void CCSingleThreadProxy::releaseContentsTexturesOnImplThread() -{ - ASSERT(isImplThread()); - m_layerTreeHost->reduceContentsTexturesMemoryOnImplThread(0, m_layerTreeHostImpl->resourceProvider()); -} - -// Called by the legacy scheduling path (e.g. where render_widget does the scheduling) -void CCSingleThreadProxy::compositeImmediately() -{ - if (commitAndComposite()) { - m_layerTreeHostImpl->swapBuffers(); - didSwapFrame(); - } -} - -void CCSingleThreadProxy::forceSerializeOnSwapBuffers() -{ - { - DebugScopedSetImplThread impl; - if (m_rendererInitialized) - m_layerTreeHostImpl->renderer()->doNoOp(); - } -} - -bool CCSingleThreadProxy::commitAndComposite() -{ - ASSERT(CCProxy::isMainThread()); - - if (!m_layerTreeHost->initializeRendererIfNeeded()) - return false; - - // Unlink any texture backings that were deleted - CCPrioritizedTextureManager::BackingVector evictedContentsTexturesBackings; - { - DebugScopedSetImplThread implThread; - m_layerTreeHost->getEvictedContentTexturesBackings(evictedContentsTexturesBackings); - } - m_layerTreeHost->unlinkEvictedContentTexturesBackings(evictedContentsTexturesBackings); - { - DebugScopedSetImplThreadAndMainThreadBlocked implAndMainBlocked; - m_layerTreeHost->deleteEvictedContentTexturesBackings(); - } - - CCTextureUpdateQueue queue; - m_layerTreeHost->updateLayers(queue, m_layerTreeHostImpl->memoryAllocationLimitBytes()); - - if (m_layerTreeHostImpl->contentsTexturesPurged()) - m_layerTreeHostImpl->resetContentsTexturesPurged(); - - m_layerTreeHost->willCommit(); - doCommit(queue); - bool result = doComposite(); - m_layerTreeHost->didBeginFrame(); - return result; -} - -bool CCSingleThreadProxy::doComposite() -{ - ASSERT(!m_contextLost); - { - DebugScopedSetImplThread impl; - - if (!m_layerTreeHostImpl->visible()) - return false; - - double monotonicTime = monotonicallyIncreasingTime(); - double wallClockTime = currentTime(); - m_layerTreeHostImpl->animate(monotonicTime, wallClockTime); - - // We guard prepareToDraw() with canDraw() because it always returns a valid frame, so can only - // be used when such a frame is possible. Since drawLayers() depends on the result of - // prepareToDraw(), it is guarded on canDraw() as well. - if (!m_layerTreeHostImpl->canDraw()) - return false; - - CCLayerTreeHostImpl::FrameData frame; - m_layerTreeHostImpl->prepareToDraw(frame); - m_layerTreeHostImpl->drawLayers(frame); - m_layerTreeHostImpl->didDrawAllLayers(frame); - } - - if (m_layerTreeHostImpl->isContextLost()) { - m_contextLost = true; - m_layerTreeHost->didLoseContext(); - return false; - } - - return true; -} - -void CCSingleThreadProxy::didSwapFrame() -{ - if (m_nextFrameIsNewlyCommittedFrame) { - m_nextFrameIsNewlyCommittedFrame = false; - m_layerTreeHost->didCommitAndDrawFrame(); - } -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSingleThreadProxy.h b/Source/WebCore/platform/graphics/chromium/cc/CCSingleThreadProxy.h deleted file mode 100644 index cecd671a6..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSingleThreadProxy.h +++ /dev/null @@ -1,151 +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 CCSingleThreadProxy_h -#define CCSingleThreadProxy_h - -#include "CCAnimationEvents.h" -#include "CCLayerTreeHostImpl.h" -#include "CCProxy.h" -#include <limits> -#include <wtf/OwnPtr.h> - -namespace WebCore { - -class CCLayerTreeHost; - -class CCSingleThreadProxy : public CCProxy, CCLayerTreeHostImplClient { -public: - static PassOwnPtr<CCProxy> create(CCLayerTreeHost*); - virtual ~CCSingleThreadProxy(); - - // CCProxy implementation - virtual bool compositeAndReadback(void *pixels, const IntRect&) OVERRIDE; - virtual void startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, double duration) OVERRIDE; - virtual void finishAllRendering() OVERRIDE; - virtual bool isStarted() const OVERRIDE; - virtual bool initializeContext() OVERRIDE; - virtual void setSurfaceReady() OVERRIDE; - virtual void setVisible(bool) OVERRIDE; - virtual bool initializeRenderer() OVERRIDE; - virtual bool recreateContext() OVERRIDE; - virtual void implSideRenderingStats(CCRenderingStats&) OVERRIDE; - virtual const RendererCapabilities& rendererCapabilities() const OVERRIDE; - virtual void loseContext() OVERRIDE; - virtual void setNeedsAnimate() OVERRIDE; - virtual void setNeedsCommit() OVERRIDE; - virtual void setNeedsRedraw() OVERRIDE; - virtual bool commitRequested() const OVERRIDE; - virtual void didAddAnimation() OVERRIDE; - virtual void start() OVERRIDE; - virtual void stop() OVERRIDE; - virtual size_t maxPartialTextureUpdates() const OVERRIDE { return std::numeric_limits<size_t>::max(); } - virtual void acquireLayerTextures() OVERRIDE { } - virtual void forceSerializeOnSwapBuffers() OVERRIDE; - - // CCLayerTreeHostImplClient implementation - virtual void didLoseContextOnImplThread() OVERRIDE { } - virtual void onSwapBuffersCompleteOnImplThread() OVERRIDE { ASSERT_NOT_REACHED(); } - virtual void onVSyncParametersChanged(double monotonicTimebase, double intervalInSeconds) OVERRIDE { } - virtual void onCanDrawStateChanged(bool canDraw) OVERRIDE { } - virtual void setNeedsRedrawOnImplThread() OVERRIDE { m_layerTreeHost->scheduleComposite(); } - virtual void setNeedsCommitOnImplThread() OVERRIDE { m_layerTreeHost->scheduleComposite(); } - virtual void postAnimationEventsToMainThreadOnImplThread(PassOwnPtr<CCAnimationEventsVector>, double wallClockTime) OVERRIDE; - virtual void releaseContentsTexturesOnImplThread() OVERRIDE; - - // Called by the legacy path where RenderWidget does the scheduling. - void compositeImmediately(); - -private: - explicit CCSingleThreadProxy(CCLayerTreeHost*); - - bool commitAndComposite(); - void doCommit(CCTextureUpdateQueue&); - bool doComposite(); - void didSwapFrame(); - - // Accessed on main thread only. - CCLayerTreeHost* m_layerTreeHost; - bool m_contextLost; - - // Holds on to the context between initializeContext() and initializeRenderer() calls. Shouldn't - // be used for anything else. - OwnPtr<CCGraphicsContext> m_contextBeforeInitialization; - - // Used on the CCThread, but checked on main thread during initialization/shutdown. - OwnPtr<CCLayerTreeHostImpl> m_layerTreeHostImpl; - bool m_rendererInitialized; - RendererCapabilities m_RendererCapabilitiesForMainThread; - - bool m_nextFrameIsNewlyCommittedFrame; -}; - -// For use in the single-threaded case. In debug builds, it pretends that the -// code is running on the impl thread to satisfy assertion checks. -class DebugScopedSetImplThread { -public: - DebugScopedSetImplThread() - { -#if !ASSERT_DISABLED - CCProxy::setCurrentThreadIsImplThread(true); -#endif - } - ~DebugScopedSetImplThread() - { -#if !ASSERT_DISABLED - CCProxy::setCurrentThreadIsImplThread(false); -#endif - } -}; - -// For use in the single-threaded case. In debug builds, it pretends that the -// code is running on the main thread to satisfy assertion checks. -class DebugScopedSetMainThread { -public: - DebugScopedSetMainThread() - { -#if !ASSERT_DISABLED - CCProxy::setCurrentThreadIsImplThread(false); -#endif - } - ~DebugScopedSetMainThread() - { -#if !ASSERT_DISABLED - CCProxy::setCurrentThreadIsImplThread(true); -#endif - } -}; - -// For use in the single-threaded case. In debug builds, it pretends that the -// code is running on the impl thread and that the main thread is blocked to -// satisfy assertion checks -class DebugScopedSetImplThreadAndMainThreadBlocked { -private: - DebugScopedSetImplThread m_implThread; - DebugScopedSetMainThreadBlocked m_mainThreadBlocked; -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorDrawQuad.cpp deleted file mode 100644 index 7d525083f..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorDrawQuad.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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCSolidColorDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCSolidColorDrawQuad> CCSolidColorDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, SkColor color) -{ - return adoptPtr(new CCSolidColorDrawQuad(sharedQuadState, quadRect, color)); -} - -CCSolidColorDrawQuad::CCSolidColorDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, SkColor color) - : CCDrawQuad(sharedQuadState, CCDrawQuad::SolidColor, quadRect) - , m_color(color) -{ - if (SkColorGetA(m_color) < 255) - m_quadOpaque = false; - else - m_opaqueRect = quadRect; -} - -const CCSolidColorDrawQuad* CCSolidColorDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::SolidColor); - return static_cast<const CCSolidColorDrawQuad*>(quad); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorDrawQuad.h deleted file mode 100644 index 2d9c6e590..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorDrawQuad.h +++ /dev/null @@ -1,54 +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 CCSolidColorDrawQuad_h -#define CCSolidColorDrawQuad_h - -#include "CCDrawQuad.h" -#include "SkColor.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -#pragma pack(push, 4) - -class CCSolidColorDrawQuad : public CCDrawQuad { -public: - static PassOwnPtr<CCSolidColorDrawQuad> create(const CCSharedQuadState*, const IntRect&, SkColor); - - SkColor color() const { return m_color; }; - - static const CCSolidColorDrawQuad* materialCast(const CCDrawQuad*); -private: - CCSolidColorDrawQuad(const CCSharedQuadState*, const IntRect&, SkColor); - - SkColor m_color; -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorLayerImpl.cpp deleted file mode 100644 index f31c853c1..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorLayerImpl.cpp +++ /dev/null @@ -1,70 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCSolidColorLayerImpl.h" - -#include "CCQuadSink.h" -#include "CCSolidColorDrawQuad.h" -#include <wtf/MathExtras.h> -#include <wtf/text/WTFString.h> - -using namespace std; -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -CCSolidColorLayerImpl::CCSolidColorLayerImpl(int id) - : CCLayerImpl(id) - , m_tileSize(256) -{ -} - -CCSolidColorLayerImpl::~CCSolidColorLayerImpl() -{ -} - -void CCSolidColorLayerImpl::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData) -{ - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState()); - appendDebugBorderQuad(quadSink, sharedQuadState, appendQuadsData); - - // We create a series of smaller quads instead of just one large one so that the - // culler can reduce the total pixels drawn. - int width = contentBounds().width(); - int height = contentBounds().height(); - for (int x = 0; x < width; x += m_tileSize) { - for (int y = 0; y < height; y += m_tileSize) { - IntRect solidTileRect(x, y, min(width - x, m_tileSize), min(height - y, m_tileSize)); - quadSink.append(CCSolidColorDrawQuad::create(sharedQuadState, solidTileRect, backgroundColor()), appendQuadsData); - } - } -} - -} // namespace WebCore -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorLayerImpl.h deleted file mode 100644 index c700671aa..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCSolidColorLayerImpl.h +++ /dev/null @@ -1,55 +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 CCSolidColorLayerImpl_h -#define CCSolidColorLayerImpl_h - -#include "CCLayerImpl.h" -#include <public/WebTransformationMatrix.h> - -namespace WebCore { - -class CCSolidColorLayerImpl : public CCLayerImpl { -public: - static PassOwnPtr<CCSolidColorLayerImpl> create(int id) - { - return adoptPtr(new CCSolidColorLayerImpl(id)); - } - virtual ~CCSolidColorLayerImpl(); - - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) OVERRIDE; - -protected: - explicit CCSolidColorLayerImpl(int id); - -private: - virtual const char* layerTypeAsString() const OVERRIDE { return "SolidColorLayer"; } - - const int m_tileSize; -}; - -} - -#endif // CCSolidColorLayerImpl_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCStreamVideoDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCStreamVideoDrawQuad.cpp deleted file mode 100644 index 87e372ff5..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCStreamVideoDrawQuad.cpp +++ /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 AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#include "CCStreamVideoDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCStreamVideoDrawQuad> CCStreamVideoDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, unsigned textureId, const WebKit::WebTransformationMatrix& matrix) -{ - return adoptPtr(new CCStreamVideoDrawQuad(sharedQuadState, quadRect, textureId, matrix)); -} - -CCStreamVideoDrawQuad::CCStreamVideoDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, unsigned textureId, const WebKit::WebTransformationMatrix& matrix) - : CCDrawQuad(sharedQuadState, CCDrawQuad::StreamVideoContent, quadRect) - , m_textureId(textureId) - , m_matrix(matrix) -{ -} - -const CCStreamVideoDrawQuad* CCStreamVideoDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::StreamVideoContent); - return static_cast<const CCStreamVideoDrawQuad*>(quad); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCStreamVideoDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCStreamVideoDrawQuad.h deleted file mode 100644 index 477995b40..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCStreamVideoDrawQuad.h +++ /dev/null @@ -1,57 +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 CCStreamVideoDrawQuad_h -#define CCStreamVideoDrawQuad_h - -#include "CCDrawQuad.h" -#include <public/WebTransformationMatrix.h> - -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -#pragma pack(push, 4) - -class CCStreamVideoDrawQuad : public CCDrawQuad { -public: - static PassOwnPtr<CCStreamVideoDrawQuad> create(const CCSharedQuadState*, const IntRect&, unsigned textureId, const WebKit::WebTransformationMatrix&); - - unsigned textureId() const { return m_textureId; } - const WebKit::WebTransformationMatrix& matrix() const { return m_matrix; } - - static const CCStreamVideoDrawQuad* materialCast(const CCDrawQuad*); -private: - CCStreamVideoDrawQuad(const CCSharedQuadState*, const IntRect&, unsigned textureId, const WebKit::WebTransformationMatrix&); - - unsigned m_textureId; - WebKit::WebTransformationMatrix m_matrix; -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTexture.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTexture.cpp deleted file mode 100644 index de80c9994..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTexture.cpp +++ /dev/null @@ -1,57 +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 "CCTexture.h" - -namespace WebCore { - -void CCTexture::setDimensions(const IntSize& size, GC3Denum format) -{ - m_size = size; - m_format = format; -} - -size_t CCTexture::bytes() const -{ - if (m_size.isEmpty()) - return 0u; - - return memorySizeBytes(m_size, m_format); -} - -size_t CCTexture::memorySizeBytes(const IntSize& size, GC3Denum format) -{ - unsigned int componentsPerPixel; - unsigned int bytesPerComponent; - if (!GraphicsContext3D::computeFormatAndTypeParameters(format, GraphicsContext3D::UNSIGNED_BYTE, &componentsPerPixel, &bytesPerComponent)) { - ASSERT_NOT_REACHED(); - return 0u; - } - return componentsPerPixel * bytesPerComponent * size.width() * size.height(); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTexture.h b/Source/WebCore/platform/graphics/chromium/cc/CCTexture.h deleted file mode 100644 index f7ba07f32..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTexture.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 CCTexture_h -#define CCTexture_h - -#include "CCResourceProvider.h" -#include "CCTexture.h" -#include "GraphicsContext3D.h" -#include "IntSize.h" - -namespace WebCore { - -class CCTexture { -public: - CCTexture() : m_id(0) { } - CCTexture(unsigned id, IntSize size, GC3Denum format) - : m_id(id) - , m_size(size) - , m_format(format) { } - - CCResourceProvider::ResourceId id() const { return m_id; } - const IntSize& size() const { return m_size; } - GC3Denum format() const { return m_format; } - - void setId(CCResourceProvider::ResourceId id) { m_id = id; } - void setDimensions(const IntSize&, GC3Denum format); - - size_t bytes() const; - - static size_t memorySizeBytes(const IntSize&, GC3Denum format); - -private: - CCResourceProvider::ResourceId m_id; - IntSize m_size; - GC3Denum m_format; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTextureDrawQuad.cpp deleted file mode 100644 index 807fccf1c..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureDrawQuad.cpp +++ /dev/null @@ -1,57 +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 "CCTextureDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCTextureDrawQuad> CCTextureDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, unsigned resourceId, bool premultipliedAlpha, const FloatRect& uvRect, bool flipped) -{ - return adoptPtr(new CCTextureDrawQuad(sharedQuadState, quadRect, resourceId, premultipliedAlpha, uvRect, flipped)); -} - -CCTextureDrawQuad::CCTextureDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, unsigned resourceId, bool premultipliedAlpha, const FloatRect& uvRect, bool flipped) - : CCDrawQuad(sharedQuadState, CCDrawQuad::TextureContent, quadRect) - , m_resourceId(resourceId) - , m_premultipliedAlpha(premultipliedAlpha) - , m_uvRect(uvRect) - , m_flipped(flipped) -{ -} - -void CCTextureDrawQuad::setNeedsBlending() -{ - m_needsBlending = true; -} - -const CCTextureDrawQuad* CCTextureDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::TextureContent); - return static_cast<const CCTextureDrawQuad*>(quad); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCTextureDrawQuad.h deleted file mode 100644 index 01418930c..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureDrawQuad.h +++ /dev/null @@ -1,62 +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 CCTextureDrawQuad_h -#define CCTextureDrawQuad_h - -#include "CCDrawQuad.h" -#include "FloatRect.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -#pragma pack(push, 4) - -class CCTextureDrawQuad : public CCDrawQuad { -public: - static PassOwnPtr<CCTextureDrawQuad> create(const CCSharedQuadState*, const IntRect&, unsigned resourceId, bool premultipliedAlpha, const FloatRect& uvRect, bool flipped); - FloatRect uvRect() const { return m_uvRect; } - - unsigned resourceId() const { return m_resourceId; } - bool premultipliedAlpha() const { return m_premultipliedAlpha; } - bool flipped() const { return m_flipped; } - - void setNeedsBlending(); - - static const CCTextureDrawQuad* materialCast(const CCDrawQuad*); -private: - CCTextureDrawQuad(const CCSharedQuadState*, const IntRect&, unsigned resourceId, bool premultipliedAlpha, const FloatRect& uvRect, bool flipped); - - unsigned m_resourceId; - bool m_premultipliedAlpha; - FloatRect m_uvRect; - bool m_flipped; -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTextureLayerImpl.cpp deleted file mode 100644 index ebe24f8b7..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureLayerImpl.cpp +++ /dev/null @@ -1,100 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCTextureLayerImpl.h" - -#include "CCQuadSink.h" -#include "CCRenderer.h" -#include "CCTextureDrawQuad.h" -#include "TextStream.h" - -namespace WebCore { - -CCTextureLayerImpl::CCTextureLayerImpl(int id) - : CCLayerImpl(id) - , m_textureId(0) - , m_externalTextureResource(0) - , m_premultipliedAlpha(true) - , m_flipped(true) - , m_uvRect(0, 0, 1, 1) -{ -} - -CCTextureLayerImpl::~CCTextureLayerImpl() -{ -} - -void CCTextureLayerImpl::willDraw(CCResourceProvider* resourceProvider) -{ - if (!m_textureId) - return; - ASSERT(!m_externalTextureResource); - m_externalTextureResource = resourceProvider->createResourceFromExternalTexture(m_textureId); -} - -void CCTextureLayerImpl::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData) -{ - if (!m_externalTextureResource) - return; - - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState()); - appendDebugBorderQuad(quadSink, sharedQuadState, appendQuadsData); - - IntRect quadRect(IntPoint(), contentBounds()); - quadSink.append(CCTextureDrawQuad::create(sharedQuadState, quadRect, m_externalTextureResource, m_premultipliedAlpha, m_uvRect, m_flipped), appendQuadsData); -} - -void CCTextureLayerImpl::didDraw(CCResourceProvider* resourceProvider) -{ - if (!m_externalTextureResource) - return; - // FIXME: the following assert will not be true when sending resources to a - // parent compositor. A synchronization scheme (double-buffering or - // pipelining of updates) for the client will need to exist to solve this. - ASSERT(!resourceProvider->inUseByConsumer(m_externalTextureResource)); - resourceProvider->deleteResource(m_externalTextureResource); - m_externalTextureResource = 0; -} - -void CCTextureLayerImpl::dumpLayerProperties(TextStream& ts, int indent) const -{ - writeIndent(ts, indent); - ts << "texture layer texture id: " << m_textureId << " premultiplied: " << m_premultipliedAlpha << "\n"; - CCLayerImpl::dumpLayerProperties(ts, indent); -} - -void CCTextureLayerImpl::didLoseContext() -{ - m_textureId = 0; - m_externalTextureResource = 0; -} - -} - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCTextureLayerImpl.h deleted file mode 100644 index befa255e1..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureLayerImpl.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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CCTextureLayerImpl_h -#define CCTextureLayerImpl_h - -#include "CCLayerImpl.h" - -namespace WebCore { - -class CCTextureLayerImpl : public CCLayerImpl { -public: - static PassOwnPtr<CCTextureLayerImpl> create(int id) - { - return adoptPtr(new CCTextureLayerImpl(id)); - } - virtual ~CCTextureLayerImpl(); - - virtual void willDraw(CCResourceProvider*) OVERRIDE; - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) OVERRIDE; - virtual void didDraw(CCResourceProvider*) OVERRIDE; - - virtual void didLoseContext() OVERRIDE; - - virtual void dumpLayerProperties(TextStream&, int indent) const OVERRIDE; - - unsigned textureId() const { return m_textureId; } - void setTextureId(unsigned id) { m_textureId = id; } - void setPremultipliedAlpha(bool premultipliedAlpha) { m_premultipliedAlpha = premultipliedAlpha; } - void setFlipped(bool flipped) { m_flipped = flipped; } - void setUVRect(const FloatRect& rect) { m_uvRect = rect; } - -private: - explicit CCTextureLayerImpl(int); - - virtual const char* layerTypeAsString() const OVERRIDE { return "TextureLayer"; } - - unsigned m_textureId; - CCResourceProvider::ResourceId m_externalTextureResource; - bool m_premultipliedAlpha; - bool m_flipped; - FloatRect m_uvRect; -}; - -} - -#endif // CCTextureLayerImpl_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateController.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateController.cpp deleted file mode 100644 index 6fc771e95..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateController.cpp +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCTextureUpdateController.h" - -#include "GraphicsContext3D.h" -#include "TextureCopier.h" -#include "TextureUploader.h" -#include <wtf/CurrentTime.h> - -namespace { - -// Number of textures to update with each call to updateMoreTexturesIfEnoughTimeRemaining(). -static const size_t textureUpdatesPerTick = 12; - -// Measured in seconds. -static const double textureUpdateTickRate = 0.004; - -// Flush interval when performing texture uploads. -static const int textureUploadFlushPeriod = 4; - -} // anonymous namespace - -namespace WebCore { - -size_t CCTextureUpdateController::maxPartialTextureUpdates() -{ - return textureUpdatesPerTick; -} - -void CCTextureUpdateController::updateTextures(CCResourceProvider* resourceProvider, TextureCopier* copier, TextureUploader* uploader, CCTextureUpdateQueue* queue, size_t count) -{ - if (queue->fullUploadSize() || queue->partialUploadSize()) { - if (uploader->isBusy()) - return; - - uploader->beginUploads(); - - size_t fullUploadCount = 0; - while (queue->fullUploadSize() && fullUploadCount < count) { - uploader->uploadTexture(resourceProvider, queue->takeFirstFullUpload()); - fullUploadCount++; - if (!(fullUploadCount % textureUploadFlushPeriod)) - resourceProvider->shallowFlushIfSupported(); - } - - // Make sure there are no dangling uploads without a flush. - if (fullUploadCount % textureUploadFlushPeriod) - resourceProvider->shallowFlushIfSupported(); - - bool moreUploads = queue->fullUploadSize(); - - ASSERT(queue->partialUploadSize() <= count); - // We need another update batch if the number of updates remaining - // in |count| is greater than the remaining partial entries. - if ((count - fullUploadCount) < queue->partialUploadSize()) - moreUploads = true; - - if (moreUploads) { - uploader->endUploads(); - return; - } - - size_t partialUploadCount = 0; - while (queue->partialUploadSize()) { - uploader->uploadTexture(resourceProvider, queue->takeFirstPartialUpload()); - partialUploadCount++; - if (!(partialUploadCount % textureUploadFlushPeriod)) - resourceProvider->shallowFlushIfSupported(); - } - - // Make sure there are no dangling partial uploads without a flush. - if (partialUploadCount % textureUploadFlushPeriod) - resourceProvider->shallowFlushIfSupported(); - - uploader->endUploads(); - } - - size_t copyCount = 0; - while (queue->copySize()) { - copier->copyTexture(queue->takeFirstCopy()); - copyCount++; - } - - // If we've performed any texture copies, we need to insert a flush here into the compositor context - // before letting the main thread proceed as it may make draw calls to the source texture of one of - // our copy operations. - if (copyCount) - copier->flush(); -} - -CCTextureUpdateController::CCTextureUpdateController(CCThread* thread, PassOwnPtr<CCTextureUpdateQueue> queue, CCResourceProvider* resourceProvider, TextureCopier* copier, TextureUploader* uploader) - : m_timer(adoptPtr(new CCTimer(thread, this))) - , m_queue(queue) - , m_resourceProvider(resourceProvider) - , m_copier(copier) - , m_uploader(uploader) - , m_monotonicTimeLimit(0) - , m_firstUpdateAttempt(true) -{ -} - -CCTextureUpdateController::~CCTextureUpdateController() -{ -} - -bool CCTextureUpdateController::hasMoreUpdates() const -{ - return m_queue->hasMoreUpdates(); -} - -void CCTextureUpdateController::updateMoreTextures(double monotonicTimeLimit) -{ - m_monotonicTimeLimit = monotonicTimeLimit; - - if (!m_queue->hasMoreUpdates()) - return; - - // Call updateMoreTexturesNow() directly unless it's the first update - // attempt. This ensures that we empty the update queue in a finite - // amount of time. - if (m_firstUpdateAttempt) { - updateMoreTexturesIfEnoughTimeRemaining(); - m_firstUpdateAttempt = false; - } else - updateMoreTexturesNow(); -} - -void CCTextureUpdateController::onTimerFired() -{ - if (!m_queue->hasMoreUpdates()) - return; - - updateMoreTexturesIfEnoughTimeRemaining(); -} - -double CCTextureUpdateController::monotonicTimeNow() const -{ - return monotonicallyIncreasingTime(); -} - -double CCTextureUpdateController::updateMoreTexturesTime() const -{ - return textureUpdateTickRate; -} - -size_t CCTextureUpdateController::updateMoreTexturesSize() const -{ - return textureUpdatesPerTick; -} - -void CCTextureUpdateController::updateMoreTexturesIfEnoughTimeRemaining() -{ - bool hasTimeRemaining = monotonicTimeNow() < m_monotonicTimeLimit - updateMoreTexturesTime(); - if (hasTimeRemaining) - updateMoreTexturesNow(); -} - -void CCTextureUpdateController::updateMoreTexturesNow() -{ - m_timer->startOneShot(updateMoreTexturesTime()); - updateTextures(m_resourceProvider, m_copier, m_uploader, m_queue.get(), updateMoreTexturesSize()); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateController.h b/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateController.h deleted file mode 100644 index dd758beb4..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateController.h +++ /dev/null @@ -1,80 +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 CCTextureUpdateController_h -#define CCTextureUpdateController_h - -#include "CCTextureUpdateQueue.h" -#include "CCTimer.h" -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> - -namespace WebCore { - -class TextureCopier; -class TextureUploader; - -class CCTextureUpdateController : public CCTimerClient { - WTF_MAKE_NONCOPYABLE(CCTextureUpdateController); -public: - static PassOwnPtr<CCTextureUpdateController> create(CCThread* thread, PassOwnPtr<CCTextureUpdateQueue> queue, CCResourceProvider* resourceProvider, TextureCopier* copier, TextureUploader* uploader) - { - return adoptPtr(new CCTextureUpdateController(thread, queue, resourceProvider, copier, uploader)); - } - static size_t maxPartialTextureUpdates(); - static void updateTextures(CCResourceProvider*, TextureCopier*, TextureUploader*, CCTextureUpdateQueue*, size_t count); - - virtual ~CCTextureUpdateController(); - - bool hasMoreUpdates() const; - void updateMoreTextures(double monotonicTimeLimit); - - // CCTimerClient implementation. - virtual void onTimerFired() OVERRIDE; - - // Virtual for testing. - virtual double monotonicTimeNow() const; - virtual double updateMoreTexturesTime() const; - virtual size_t updateMoreTexturesSize() const; - -protected: - CCTextureUpdateController(CCThread*, PassOwnPtr<CCTextureUpdateQueue>, CCResourceProvider*, TextureCopier*, TextureUploader*); - - void updateMoreTexturesIfEnoughTimeRemaining(); - void updateMoreTexturesNow(); - - OwnPtr<CCTimer> m_timer; - OwnPtr<CCTextureUpdateQueue> m_queue; - bool m_contentsTexturesPurged; - CCResourceProvider* m_resourceProvider; - TextureCopier* m_copier; - TextureUploader* m_uploader; - double m_monotonicTimeLimit; - bool m_firstUpdateAttempt; -}; - -} - -#endif // CCTextureUpdateController_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateQueue.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateQueue.cpp deleted file mode 100644 index 8f58fcbcb..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateQueue.cpp +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 USE(ACCELERATED_COMPOSITING) - -#include "CCTextureUpdateQueue.h" - -namespace WebCore { - -CCTextureUpdateQueue::CCTextureUpdateQueue() -{ -} - -CCTextureUpdateQueue::~CCTextureUpdateQueue() -{ -} - -void CCTextureUpdateQueue::appendFullUpload(TextureUploader::Parameters upload) -{ - m_fullEntries.append(upload); -} - -void CCTextureUpdateQueue::appendPartialUpload(TextureUploader::Parameters upload) -{ - m_partialEntries.append(upload); -} - -void CCTextureUpdateQueue::appendCopy(TextureCopier::Parameters copy) -{ - m_copyEntries.append(copy); -} - -void CCTextureUpdateQueue::clearUploads() -{ - m_fullEntries.clear(); - m_partialEntries.clear(); -} - -TextureUploader::Parameters CCTextureUpdateQueue::takeFirstFullUpload() -{ - return m_fullEntries.takeFirst(); -} - -TextureUploader::Parameters CCTextureUpdateQueue::takeFirstPartialUpload() -{ - return m_partialEntries.takeFirst(); -} - -TextureCopier::Parameters CCTextureUpdateQueue::takeFirstCopy() -{ - return m_copyEntries.takeFirst(); -} - -bool CCTextureUpdateQueue::hasMoreUpdates() const -{ - return m_fullEntries.size() || m_partialEntries.size() || m_copyEntries.size(); -} - -} - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateQueue.h b/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateQueue.h deleted file mode 100644 index de6373821..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTextureUpdateQueue.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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CCTextureUpdateQueue_h -#define CCTextureUpdateQueue_h - -#include "TextureCopier.h" -#include "TextureUploader.h" -#include <wtf/Deque.h> -#include <wtf/Noncopyable.h> - -namespace WebCore { - -class CCTextureUpdateQueue { - WTF_MAKE_NONCOPYABLE(CCTextureUpdateQueue); -public: - CCTextureUpdateQueue(); - virtual ~CCTextureUpdateQueue(); - - void appendFullUpload(TextureUploader::Parameters); - void appendPartialUpload(TextureUploader::Parameters); - void appendCopy(TextureCopier::Parameters); - - void clearUploads(); - - TextureUploader::Parameters takeFirstFullUpload(); - TextureUploader::Parameters takeFirstPartialUpload(); - TextureCopier::Parameters takeFirstCopy(); - - size_t fullUploadSize() const { return m_fullEntries.size(); } - size_t partialUploadSize() const { return m_partialEntries.size(); } - size_t copySize() const { return m_copyEntries.size(); } - - bool hasMoreUpdates() const; - -private: - Deque<TextureUploader::Parameters> m_fullEntries; - Deque<TextureUploader::Parameters> m_partialEntries; - Deque<TextureCopier::Parameters> m_copyEntries; -}; - -} - -#endif // CCTextureUpdateQueue_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCThread.h b/Source/WebCore/platform/graphics/chromium/cc/CCThread.h deleted file mode 100644 index d06dad3e9..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCThread.h +++ /dev/null @@ -1,61 +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 CCThread_h -#define CCThread_h - -#include <wtf/PassOwnPtr.h> -#include <wtf/Threading.h> - -namespace WebCore { - -// CCThread provides basic infrastructure for messaging with the compositor in a -// platform-neutral way. -class CCThread { -public: - virtual ~CCThread() { } - - class Task { - WTF_MAKE_NONCOPYABLE(Task); - public: - virtual ~Task() { } - virtual void performTask() = 0; - void* instance() const { return m_instance; } - protected: - Task(void* instance) : m_instance(instance) { } - void* m_instance; - }; - - // Executes the task on context's thread asynchronously. - virtual void postTask(PassOwnPtr<Task>) = 0; - - // Executes the task after the specified delay. - virtual void postDelayedTask(PassOwnPtr<Task>, long long delayMs) = 0; - - virtual WTF::ThreadIdentifier threadID() const = 0; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCThreadProxy.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCThreadProxy.cpp deleted file mode 100644 index 280bcdaf8..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCThreadProxy.cpp +++ /dev/null @@ -1,953 +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 "CCThreadProxy.h" - -#include "CCDelayBasedTimeSource.h" -#include "CCDrawQuad.h" -#include "CCFrameRateController.h" -#include "CCGraphicsContext.h" -#include "CCInputHandler.h" -#include "CCLayerTreeHost.h" -#include "CCScheduler.h" -#include "CCScopedThreadProxy.h" -#include "CCTextureUpdateController.h" -#include "CCThreadTask.h" -#include "TraceEvent.h" -#include <public/WebSharedGraphicsContext3D.h> -#include <wtf/CurrentTime.h> -#include <wtf/MainThread.h> - -using namespace WTF; - -using WebKit::WebSharedGraphicsContext3D; -namespace { - -// Measured in seconds. -static const double contextRecreationTickRate = 0.03; - -} // anonymous namespace - -namespace WebCore { - -namespace { - -// Type of texture uploader to use for texture updates. -static TextureUploaderOption textureUploader = ThrottledUploader; - -} // anonymous namespace - -PassOwnPtr<CCProxy> CCThreadProxy::create(CCLayerTreeHost* layerTreeHost) -{ - return adoptPtr(new CCThreadProxy(layerTreeHost)); -} - -CCThreadProxy::CCThreadProxy(CCLayerTreeHost* layerTreeHost) - : m_animateRequested(false) - , m_commitRequested(false) - , m_commitRequestSentToImplThread(false) - , m_forcedCommitRequested(false) - , m_layerTreeHost(layerTreeHost) - , m_rendererInitialized(false) - , m_started(false) - , m_texturesAcquired(true) - , m_inCompositeAndReadback(false) - , m_mainThreadProxy(CCScopedThreadProxy::create(CCProxy::mainThread())) - , m_beginFrameCompletionEventOnImplThread(0) - , m_readbackRequestOnImplThread(0) - , m_commitCompletionEventOnImplThread(0) - , m_textureAcquisitionCompletionEventOnImplThread(0) - , m_resetContentsTexturesPurgedAfterCommitOnImplThread(false) - , m_nextFrameIsNewlyCommittedFrameOnImplThread(false) - , m_renderVSyncEnabled(layerTreeHost->settings().renderVSyncEnabled) -{ - TRACE_EVENT0("cc", "CCThreadProxy::CCThreadProxy"); - ASSERT(isMainThread()); -} - -CCThreadProxy::~CCThreadProxy() -{ - TRACE_EVENT0("cc", "CCThreadProxy::~CCThreadProxy"); - ASSERT(isMainThread()); - ASSERT(!m_started); -} - -bool CCThreadProxy::compositeAndReadback(void *pixels, const IntRect& rect) -{ - TRACE_EVENT0("cc", "CCThreadPRoxy::compositeAndReadback"); - ASSERT(isMainThread()); - ASSERT(m_layerTreeHost); - - if (!m_layerTreeHost->initializeRendererIfNeeded()) { - TRACE_EVENT0("cc", "compositeAndReadback_EarlyOut_LR_Uninitialized"); - return false; - } - - - // Perform a synchronous commit. - { - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCCompletionEvent beginFrameCompletion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::forceBeginFrameOnImplThread, &beginFrameCompletion)); - beginFrameCompletion.wait(); - } - m_inCompositeAndReadback = true; - beginFrame(); - m_inCompositeAndReadback = false; - - // Perform a synchronous readback. - ReadbackRequest request; - request.rect = rect; - request.pixels = pixels; - { - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::requestReadbackOnImplThread, &request)); - request.completion.wait(); - } - return request.success; -} - -void CCThreadProxy::requestReadbackOnImplThread(ReadbackRequest* request) -{ - ASSERT(CCProxy::isImplThread()); - ASSERT(!m_readbackRequestOnImplThread); - if (!m_layerTreeHostImpl) { - request->success = false; - request->completion.signal(); - return; - } - - m_readbackRequestOnImplThread = request; - m_schedulerOnImplThread->setNeedsRedraw(); - m_schedulerOnImplThread->setNeedsForcedRedraw(); -} - -void CCThreadProxy::startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, double duration) -{ - ASSERT(CCProxy::isMainThread()); - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::requestStartPageScaleAnimationOnImplThread, targetPosition, useAnchor, scale, duration)); -} - -void CCThreadProxy::requestStartPageScaleAnimationOnImplThread(IntSize targetPosition, bool useAnchor, float scale, double duration) -{ - ASSERT(CCProxy::isImplThread()); - if (m_layerTreeHostImpl) - m_layerTreeHostImpl->startPageScaleAnimation(targetPosition, useAnchor, scale, monotonicallyIncreasingTime(), duration); -} - -void CCThreadProxy::finishAllRendering() -{ - ASSERT(CCProxy::isMainThread()); - - // Make sure all GL drawing is finished on the impl thread. - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCCompletionEvent completion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::finishAllRenderingOnImplThread, &completion)); - completion.wait(); -} - -bool CCThreadProxy::isStarted() const -{ - ASSERT(CCProxy::isMainThread()); - return m_started; -} - -bool CCThreadProxy::initializeContext() -{ - TRACE_EVENT0("cc", "CCThreadProxy::initializeContext"); - OwnPtr<CCGraphicsContext> context = m_layerTreeHost->createContext(); - if (!context) - return false; - - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::initializeContextOnImplThread, - context.leakPtr())); - return true; -} - -void CCThreadProxy::setSurfaceReady() -{ - TRACE_EVENT0("cc", "CCThreadProxy::setSurfaceReady"); - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::setSurfaceReadyOnImplThread)); -} - -void CCThreadProxy::setSurfaceReadyOnImplThread() -{ - TRACE_EVENT0("cc", "CCThreadProxy::setSurfaceReadyOnImplThread"); - m_schedulerOnImplThread->setCanBeginFrame(true); -} - -void CCThreadProxy::setVisible(bool visible) -{ - TRACE_EVENT0("cc", "CCThreadProxy::setVisible"); - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCCompletionEvent completion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::setVisibleOnImplThread, &completion, visible)); - completion.wait(); -} - -void CCThreadProxy::setVisibleOnImplThread(CCCompletionEvent* completion, bool visible) -{ - TRACE_EVENT0("cc", "CCThreadProxy::setVisibleOnImplThread"); - m_layerTreeHostImpl->setVisible(visible); - m_schedulerOnImplThread->setVisible(visible); - completion->signal(); -} - -bool CCThreadProxy::initializeRenderer() -{ - TRACE_EVENT0("cc", "CCThreadProxy::initializeRenderer"); - // Make a blocking call to initializeRendererOnImplThread. The results of that call - // are pushed into the initializeSucceeded and capabilities local variables. - CCCompletionEvent completion; - bool initializeSucceeded = false; - RendererCapabilities capabilities; - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::initializeRendererOnImplThread, - &completion, - &initializeSucceeded, - &capabilities)); - completion.wait(); - - if (initializeSucceeded) { - m_rendererInitialized = true; - m_RendererCapabilitiesMainThreadCopy = capabilities; - } - return initializeSucceeded; -} - -bool CCThreadProxy::recreateContext() -{ - TRACE_EVENT0("cc", "CCThreadProxy::recreateContext"); - ASSERT(isMainThread()); - - // Try to create the context. - OwnPtr<CCGraphicsContext> context = m_layerTreeHost->createContext(); - if (!context) - return false; - if (m_layerTreeHost->needsSharedContext()) - if (!WebSharedGraphicsContext3D::createCompositorThreadContext()) - return false; - - // Make a blocking call to recreateContextOnImplThread. The results of that - // call are pushed into the recreateSucceeded and capabilities local - // variables. - CCCompletionEvent completion; - bool recreateSucceeded = false; - RendererCapabilities capabilities; - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::recreateContextOnImplThread, - &completion, - context.leakPtr(), - &recreateSucceeded, - &capabilities)); - completion.wait(); - - if (recreateSucceeded) - m_RendererCapabilitiesMainThreadCopy = capabilities; - return recreateSucceeded; -} - -void CCThreadProxy::implSideRenderingStats(CCRenderingStats& stats) -{ - ASSERT(isMainThread()); - - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCCompletionEvent completion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::implSideRenderingStatsOnImplThread, - &completion, - &stats)); - completion.wait(); -} - -const RendererCapabilities& CCThreadProxy::rendererCapabilities() const -{ - ASSERT(m_rendererInitialized); - return m_RendererCapabilitiesMainThreadCopy; -} - -void CCThreadProxy::loseContext() -{ - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::didLoseContextOnImplThread)); -} - -void CCThreadProxy::setNeedsAnimate() -{ - ASSERT(isMainThread()); - if (m_animateRequested) - return; - - TRACE_EVENT0("cc", "CCThreadProxy::setNeedsAnimate"); - m_animateRequested = true; - - if (m_commitRequestSentToImplThread) - return; - m_commitRequestSentToImplThread = true; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::setNeedsCommitOnImplThread)); -} - -void CCThreadProxy::setNeedsCommit() -{ - ASSERT(isMainThread()); - if (m_commitRequested) - return; - TRACE_EVENT0("cc", "CCThreadProxy::setNeedsCommit"); - m_commitRequested = true; - - if (m_commitRequestSentToImplThread) - return; - m_commitRequestSentToImplThread = true; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::setNeedsCommitOnImplThread)); -} - -void CCThreadProxy::didLoseContextOnImplThread() -{ - ASSERT(isImplThread()); - TRACE_EVENT0("cc", "CCThreadProxy::didLoseContextOnImplThread"); - m_currentTextureUpdateControllerOnImplThread.clear(); - m_schedulerOnImplThread->didLoseContext(); -} - -void CCThreadProxy::onSwapBuffersCompleteOnImplThread() -{ - ASSERT(isImplThread()); - TRACE_EVENT0("cc", "CCThreadProxy::onSwapBuffersCompleteOnImplThread"); - m_schedulerOnImplThread->didSwapBuffersComplete(); - m_mainThreadProxy->postTask(createCCThreadTask(this, &CCThreadProxy::didCompleteSwapBuffers)); -} - -void CCThreadProxy::onVSyncParametersChanged(double monotonicTimebase, double intervalInSeconds) -{ - ASSERT(isImplThread()); - TRACE_EVENT2("cc", "CCThreadProxy::onVSyncParametersChanged", "monotonicTimebase", monotonicTimebase, "intervalInSeconds", intervalInSeconds); - m_schedulerOnImplThread->setTimebaseAndInterval(monotonicTimebase, intervalInSeconds); -} - -void CCThreadProxy::onCanDrawStateChanged(bool canDraw) -{ - ASSERT(isImplThread()); - TRACE_EVENT1("cc", "CCThreadProxy::onCanDrawStateChanged", "canDraw", canDraw); - m_schedulerOnImplThread->setCanDraw(canDraw); -} - -void CCThreadProxy::setNeedsCommitOnImplThread() -{ - ASSERT(isImplThread()); - TRACE_EVENT0("cc", "CCThreadProxy::setNeedsCommitOnImplThread"); - m_schedulerOnImplThread->setNeedsCommit(); -} - -void CCThreadProxy::setNeedsForcedCommitOnImplThread() -{ - ASSERT(isImplThread()); - TRACE_EVENT0("cc", "CCThreadProxy::setNeedsForcedCommitOnImplThread"); - m_schedulerOnImplThread->setNeedsCommit(); - m_schedulerOnImplThread->setNeedsForcedCommit(); -} - -void CCThreadProxy::postAnimationEventsToMainThreadOnImplThread(PassOwnPtr<CCAnimationEventsVector> events, double wallClockTime) -{ - ASSERT(isImplThread()); - TRACE_EVENT0("cc", "CCThreadProxy::postAnimationEventsToMainThreadOnImplThread"); - m_mainThreadProxy->postTask(createCCThreadTask(this, &CCThreadProxy::setAnimationEvents, events, wallClockTime)); -} - -void CCThreadProxy::releaseContentsTexturesOnImplThread() -{ - ASSERT(isImplThread()); - m_layerTreeHost->reduceContentsTexturesMemoryOnImplThread(0, m_layerTreeHostImpl->resourceProvider()); - // Make sure that we get a new commit before drawing again. - m_resetContentsTexturesPurgedAfterCommitOnImplThread = false; - // The texture upload queue may reference textures that were just purged, so clear it. - m_currentTextureUpdateControllerOnImplThread.clear(); -} - -void CCThreadProxy::setNeedsRedraw() -{ - ASSERT(isMainThread()); - TRACE_EVENT0("cc", "CCThreadProxy::setNeedsRedraw"); - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::setFullRootLayerDamageOnImplThread)); - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::setNeedsRedrawOnImplThread)); -} - -bool CCThreadProxy::commitRequested() const -{ - ASSERT(isMainThread()); - return m_commitRequested; -} - -void CCThreadProxy::setNeedsRedrawOnImplThread() -{ - ASSERT(isImplThread()); - TRACE_EVENT0("cc", "CCThreadProxy::setNeedsRedrawOnImplThread"); - m_schedulerOnImplThread->setNeedsRedraw(); -} - -void CCThreadProxy::start() -{ - ASSERT(isMainThread()); - ASSERT(CCProxy::implThread()); - // Create LayerTreeHostImpl. - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCCompletionEvent completion; - OwnPtr<CCInputHandler> handler = m_layerTreeHost->createInputHandler(); - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::initializeImplOnImplThread, &completion, handler.release())); - completion.wait(); - - m_started = true; -} - -void CCThreadProxy::stop() -{ - TRACE_EVENT0("cc", "CCThreadProxy::stop"); - ASSERT(isMainThread()); - ASSERT(m_started); - - // Synchronously deletes the impl. - { - DebugScopedSetMainThreadBlocked mainThreadBlocked; - - CCCompletionEvent completion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::layerTreeHostClosedOnImplThread, &completion)); - completion.wait(); - } - - m_mainThreadProxy->shutdown(); // Stop running tasks posted to us. - - ASSERT(!m_layerTreeHostImpl); // verify that the impl deleted. - m_layerTreeHost = 0; - m_started = false; -} - -void CCThreadProxy::forceSerializeOnSwapBuffers() -{ - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCCompletionEvent completion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::forceSerializeOnSwapBuffersOnImplThread, &completion)); - completion.wait(); -} - -void CCThreadProxy::forceSerializeOnSwapBuffersOnImplThread(CCCompletionEvent* completion) -{ - if (m_rendererInitialized) - m_layerTreeHostImpl->renderer()->doNoOp(); - completion->signal(); -} - - -void CCThreadProxy::finishAllRenderingOnImplThread(CCCompletionEvent* completion) -{ - TRACE_EVENT0("cc", "CCThreadProxy::finishAllRenderingOnImplThread"); - ASSERT(isImplThread()); - m_layerTreeHostImpl->finishAllRendering(); - completion->signal(); -} - -void CCThreadProxy::forceBeginFrameOnImplThread(CCCompletionEvent* completion) -{ - TRACE_EVENT0("cc", "CCThreadProxy::forceBeginFrameOnImplThread"); - ASSERT(!m_beginFrameCompletionEventOnImplThread); - - if (m_schedulerOnImplThread->commitPending()) { - completion->signal(); - return; - } - - m_beginFrameCompletionEventOnImplThread = completion; - setNeedsForcedCommitOnImplThread(); -} - -void CCThreadProxy::scheduledActionBeginFrame() -{ - TRACE_EVENT0("cc", "CCThreadProxy::scheduledActionBeginFrame"); - ASSERT(!m_pendingBeginFrameRequest); - m_pendingBeginFrameRequest = adoptPtr(new BeginFrameAndCommitState()); - m_pendingBeginFrameRequest->monotonicFrameBeginTime = monotonicallyIncreasingTime(); - m_pendingBeginFrameRequest->scrollInfo = m_layerTreeHostImpl->processScrollDeltas(); - m_pendingBeginFrameRequest->memoryAllocationLimitBytes = m_layerTreeHostImpl->memoryAllocationLimitBytes(); - m_layerTreeHost->getEvictedContentTexturesBackings(m_pendingBeginFrameRequest->evictedContentsTexturesBackings); - - m_mainThreadProxy->postTask(createCCThreadTask(this, &CCThreadProxy::beginFrame)); - - if (m_beginFrameCompletionEventOnImplThread) { - m_beginFrameCompletionEventOnImplThread->signal(); - m_beginFrameCompletionEventOnImplThread = 0; - } -} - -void CCThreadProxy::beginFrame() -{ - TRACE_EVENT0("cc", "CCThreadProxy::beginFrame"); - ASSERT(isMainThread()); - if (!m_layerTreeHost) - return; - - if (!m_pendingBeginFrameRequest) { - TRACE_EVENT0("cc", "EarlyOut_StaleBeginFrameMessage"); - return; - } - - if (m_layerTreeHost->needsSharedContext() && !WebSharedGraphicsContext3D::haveCompositorThreadContext()) - WebSharedGraphicsContext3D::createCompositorThreadContext(); - - OwnPtr<BeginFrameAndCommitState> request(m_pendingBeginFrameRequest.release()); - - // Do not notify the impl thread of commit requests that occur during - // the apply/animate/layout part of the beginFrameAndCommit process since - // those commit requests will get painted immediately. Once we have done - // the paint, m_commitRequested will be set to false to allow new commit - // requests to be scheduled. - m_commitRequested = true; - m_commitRequestSentToImplThread = true; - - // On the other hand, the animationRequested flag needs to be cleared - // here so that any animation requests generated by the apply or animate - // callbacks will trigger another frame. - m_animateRequested = false; - - // FIXME: technically, scroll deltas need to be applied for dropped commits as well. - // Re-do the commit flow so that we don't send the scrollInfo on the BFAC message. - m_layerTreeHost->applyScrollAndScale(*request->scrollInfo); - - if (!m_inCompositeAndReadback && !m_layerTreeHost->visible()) { - m_commitRequested = false; - m_commitRequestSentToImplThread = false; - m_forcedCommitRequested = false; - - TRACE_EVENT0("cc", "EarlyOut_NotVisible"); - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::beginFrameAbortedOnImplThread)); - return; - } - - m_layerTreeHost->willBeginFrame(); - - m_layerTreeHost->updateAnimations(request->monotonicFrameBeginTime); - m_layerTreeHost->layout(); - - // Clear the commit flag after updating animations and layout here --- objects that only - // layout when painted will trigger another setNeedsCommit inside - // updateLayers. - m_commitRequested = false; - m_commitRequestSentToImplThread = false; - m_forcedCommitRequested = false; - - if (!m_layerTreeHost->initializeRendererIfNeeded()) { - TRACE_EVENT0("cc", "EarlyOut_InitializeFailed"); - return; - } - - m_layerTreeHost->unlinkEvictedContentTexturesBackings(request->evictedContentsTexturesBackings); - - OwnPtr<CCTextureUpdateQueue> queue = adoptPtr(new CCTextureUpdateQueue); - m_layerTreeHost->updateLayers(*(queue.get()), request->memoryAllocationLimitBytes); - - // Once single buffered layers are committed, they cannot be modified until - // they are drawn by the impl thread. - m_texturesAcquired = false; - - m_layerTreeHost->willCommit(); - // Before applying scrolls and calling animate, we set m_animateRequested to - // false. If it is true now, it means setNeedAnimate was called again, but - // during a state when m_commitRequestSentToImplThread = true. We need to - // force that call to happen again now so that the commit request is sent to - // the impl thread. - if (m_animateRequested) { - // Forces setNeedsAnimate to consider posting a commit task. - m_animateRequested = false; - setNeedsAnimate(); - } - - // Notify the impl thread that the beginFrame has completed. This will - // begin the commit process, which is blocking from the main thread's - // point of view, but asynchronously performed on the impl thread, - // coordinated by the CCScheduler. - { - TRACE_EVENT0("cc", "commit"); - DebugScopedSetMainThreadBlocked mainThreadBlocked; - - CCCompletionEvent completion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::beginFrameCompleteOnImplThread, &completion, queue.release())); - completion.wait(); - } - - m_layerTreeHost->commitComplete(); - m_layerTreeHost->didBeginFrame(); -} - -void CCThreadProxy::beginFrameCompleteOnImplThread(CCCompletionEvent* completion, PassOwnPtr<CCTextureUpdateQueue> queue) -{ - TRACE_EVENT0("cc", "CCThreadProxy::beginFrameCompleteOnImplThread"); - ASSERT(!m_commitCompletionEventOnImplThread); - ASSERT(isImplThread() && isMainThreadBlocked()); - ASSERT(m_schedulerOnImplThread); - ASSERT(m_schedulerOnImplThread->commitPending()); - - if (!m_layerTreeHostImpl) { - TRACE_EVENT0("cc", "EarlyOut_NoLayerTree"); - completion->signal(); - return; - } - - // If we unlinked evicted textures on the main thread, delete them now. - if (m_layerTreeHost->deleteEvictedContentTexturesBackings()) { - - // Deleting the evicted textures' backings resulted in some textures in the - // layer tree being invalidated (unliked from their backings). The upload queue - // may contain references to these textures, so clear the queue and kick off - // another commit to fill them again. - queue->clearUploads(); - setNeedsCommitOnImplThread(); - } else { - // The layer tree does not reference evicted textures, so mark that we - // can draw this tree once this commit is complete. - if (m_layerTreeHostImpl->contentsTexturesPurged()) - m_resetContentsTexturesPurgedAfterCommitOnImplThread = true; - } - - m_currentTextureUpdateControllerOnImplThread = CCTextureUpdateController::create(CCProxy::implThread(), queue, m_layerTreeHostImpl->resourceProvider(), m_layerTreeHostImpl->renderer()->textureCopier(), m_layerTreeHostImpl->renderer()->textureUploader()); - m_commitCompletionEventOnImplThread = completion; - - m_schedulerOnImplThread->beginFrameComplete(); -} - -void CCThreadProxy::beginFrameAbortedOnImplThread() -{ - TRACE_EVENT0("cc", "CCThreadProxy::beginFrameAbortedOnImplThread"); - ASSERT(isImplThread()); - ASSERT(m_schedulerOnImplThread); - ASSERT(m_schedulerOnImplThread->commitPending()); - - m_schedulerOnImplThread->beginFrameAborted(); -} - -bool CCThreadProxy::hasMoreResourceUpdates() const -{ - if (!m_currentTextureUpdateControllerOnImplThread) - return false; - return m_currentTextureUpdateControllerOnImplThread->hasMoreUpdates(); -} - -void CCThreadProxy::scheduledActionUpdateMoreResources(double monotonicTimeLimit) -{ - TRACE_EVENT0("cc", "CCThreadProxy::scheduledActionUpdateMoreResources"); - ASSERT(m_currentTextureUpdateControllerOnImplThread); - m_currentTextureUpdateControllerOnImplThread->updateMoreTextures(monotonicTimeLimit); -} - -void CCThreadProxy::scheduledActionCommit() -{ - TRACE_EVENT0("cc", "CCThreadProxy::scheduledActionCommit"); - ASSERT(isImplThread()); - ASSERT(!hasMoreResourceUpdates()); - ASSERT(m_commitCompletionEventOnImplThread); - - m_currentTextureUpdateControllerOnImplThread.clear(); - - m_layerTreeHostImpl->beginCommit(); - - m_layerTreeHost->beginCommitOnImplThread(m_layerTreeHostImpl.get()); - m_layerTreeHost->finishCommitOnImplThread(m_layerTreeHostImpl.get()); - - if (m_resetContentsTexturesPurgedAfterCommitOnImplThread) { - m_resetContentsTexturesPurgedAfterCommitOnImplThread = false; - m_layerTreeHostImpl->resetContentsTexturesPurged(); - } - - m_layerTreeHostImpl->commitComplete(); - - m_nextFrameIsNewlyCommittedFrameOnImplThread = true; - - m_commitCompletionEventOnImplThread->signal(); - m_commitCompletionEventOnImplThread = 0; - - // SetVisible kicks off the next scheduler action, so this must be last. - m_schedulerOnImplThread->setVisible(m_layerTreeHostImpl->visible()); -} - -void CCThreadProxy::scheduledActionBeginContextRecreation() -{ - ASSERT(isImplThread()); - m_mainThreadProxy->postTask(createCCThreadTask(this, &CCThreadProxy::beginContextRecreation)); -} - -CCScheduledActionDrawAndSwapResult CCThreadProxy::scheduledActionDrawAndSwapInternal(bool forcedDraw) -{ - TRACE_EVENT0("cc", "CCThreadProxy::scheduledActionDrawAndSwap"); - CCScheduledActionDrawAndSwapResult result; - result.didDraw = false; - result.didSwap = false; - ASSERT(isImplThread()); - ASSERT(m_layerTreeHostImpl); - if (!m_layerTreeHostImpl) - return result; - - ASSERT(m_layerTreeHostImpl->renderer()); - if (!m_layerTreeHostImpl->renderer()) - return result; - - // FIXME: compute the frame display time more intelligently - double monotonicTime = monotonicallyIncreasingTime(); - double wallClockTime = currentTime(); - - if (m_inputHandlerOnImplThread) - m_inputHandlerOnImplThread->animate(monotonicTime); - m_layerTreeHostImpl->animate(monotonicTime, wallClockTime); - - // This method is called on a forced draw, regardless of whether we are able to produce a frame, - // as the calling site on main thread is blocked until its request completes, and we signal - // completion here. If canDraw() is false, we will indicate success=false to the caller, but we - // must still signal completion to avoid deadlock. - - // We guard prepareToDraw() with canDraw() because it always returns a valid frame, so can only - // be used when such a frame is possible. Since drawLayers() depends on the result of - // prepareToDraw(), it is guarded on canDraw() as well. - - CCLayerTreeHostImpl::FrameData frame; - bool drawFrame = m_layerTreeHostImpl->canDraw() && (m_layerTreeHostImpl->prepareToDraw(frame) || forcedDraw); - if (drawFrame) { - m_layerTreeHostImpl->drawLayers(frame); - result.didDraw = true; - } - m_layerTreeHostImpl->didDrawAllLayers(frame); - - // Check for a pending compositeAndReadback. - if (m_readbackRequestOnImplThread) { - m_readbackRequestOnImplThread->success = false; - if (drawFrame) { - m_layerTreeHostImpl->readback(m_readbackRequestOnImplThread->pixels, m_readbackRequestOnImplThread->rect); - m_readbackRequestOnImplThread->success = !m_layerTreeHostImpl->isContextLost(); - } - m_readbackRequestOnImplThread->completion.signal(); - m_readbackRequestOnImplThread = 0; - } else if (drawFrame) - result.didSwap = m_layerTreeHostImpl->swapBuffers(); - - // Tell the main thread that the the newly-commited frame was drawn. - if (m_nextFrameIsNewlyCommittedFrameOnImplThread) { - m_nextFrameIsNewlyCommittedFrameOnImplThread = false; - m_mainThreadProxy->postTask(createCCThreadTask(this, &CCThreadProxy::didCommitAndDrawFrame)); - } - - return result; -} - -void CCThreadProxy::acquireLayerTextures() -{ - // Called when the main thread needs to modify a layer texture that is used - // directly by the compositor. - // This method will block until the next compositor draw if there is a - // previously committed frame that is still undrawn. This is necessary to - // ensure that the main thread does not monopolize access to the textures. - ASSERT(isMainThread()); - - if (m_texturesAcquired) - return; - - TRACE_EVENT0("cc", "CCThreadProxy::acquireLayerTextures"); - DebugScopedSetMainThreadBlocked mainThreadBlocked; - CCCompletionEvent completion; - CCProxy::implThread()->postTask(createCCThreadTask(this, &CCThreadProxy::acquireLayerTexturesForMainThreadOnImplThread, &completion)); - completion.wait(); // Block until it is safe to write to layer textures from the main thread. - - m_texturesAcquired = true; -} - -void CCThreadProxy::acquireLayerTexturesForMainThreadOnImplThread(CCCompletionEvent* completion) -{ - ASSERT(isImplThread()); - ASSERT(!m_textureAcquisitionCompletionEventOnImplThread); - - m_textureAcquisitionCompletionEventOnImplThread = completion; - m_schedulerOnImplThread->setMainThreadNeedsLayerTextures(); -} - -void CCThreadProxy::scheduledActionAcquireLayerTexturesForMainThread() -{ - ASSERT(m_textureAcquisitionCompletionEventOnImplThread); - m_textureAcquisitionCompletionEventOnImplThread->signal(); - m_textureAcquisitionCompletionEventOnImplThread = 0; -} - -CCScheduledActionDrawAndSwapResult CCThreadProxy::scheduledActionDrawAndSwapIfPossible() -{ - return scheduledActionDrawAndSwapInternal(false); -} - -CCScheduledActionDrawAndSwapResult CCThreadProxy::scheduledActionDrawAndSwapForced() -{ - return scheduledActionDrawAndSwapInternal(true); -} - -void CCThreadProxy::didCommitAndDrawFrame() -{ - ASSERT(isMainThread()); - if (!m_layerTreeHost) - return; - m_layerTreeHost->didCommitAndDrawFrame(); -} - -void CCThreadProxy::didCompleteSwapBuffers() -{ - ASSERT(isMainThread()); - if (!m_layerTreeHost) - return; - m_layerTreeHost->didCompleteSwapBuffers(); -} - -void CCThreadProxy::setAnimationEvents(PassOwnPtr<CCAnimationEventsVector> events, double wallClockTime) -{ - TRACE_EVENT0("cc", "CCThreadProxy::setAnimationEvents"); - ASSERT(isMainThread()); - if (!m_layerTreeHost) - return; - m_layerTreeHost->setAnimationEvents(events, wallClockTime); -} - -class CCThreadProxyContextRecreationTimer : public CCTimer, CCTimerClient { -public: - static PassOwnPtr<CCThreadProxyContextRecreationTimer> create(CCThreadProxy* proxy) { return adoptPtr(new CCThreadProxyContextRecreationTimer(proxy)); } - - virtual void onTimerFired() OVERRIDE - { - m_proxy->tryToRecreateContext(); - } - -private: - explicit CCThreadProxyContextRecreationTimer(CCThreadProxy* proxy) - : CCTimer(CCProxy::mainThread(), this) - , m_proxy(proxy) - { - } - - CCThreadProxy* m_proxy; -}; - -void CCThreadProxy::beginContextRecreation() -{ - TRACE_EVENT0("cc", "CCThreadProxy::beginContextRecreation"); - ASSERT(isMainThread()); - ASSERT(!m_contextRecreationTimer); - m_contextRecreationTimer = CCThreadProxyContextRecreationTimer::create(this); - m_layerTreeHost->didLoseContext(); - m_contextRecreationTimer->startOneShot(contextRecreationTickRate); -} - -void CCThreadProxy::tryToRecreateContext() -{ - ASSERT(isMainThread()); - ASSERT(m_layerTreeHost); - CCLayerTreeHost::RecreateResult result = m_layerTreeHost->recreateContext(); - if (result == CCLayerTreeHost::RecreateFailedButTryAgain) - m_contextRecreationTimer->startOneShot(contextRecreationTickRate); - else if (result == CCLayerTreeHost::RecreateSucceeded) - m_contextRecreationTimer.clear(); -} - -void CCThreadProxy::initializeImplOnImplThread(CCCompletionEvent* completion, PassOwnPtr<CCInputHandler> popHandler) -{ - TRACE_EVENT0("cc", "CCThreadProxy::initializeImplOnImplThread"); - ASSERT(isImplThread()); - m_layerTreeHostImpl = m_layerTreeHost->createLayerTreeHostImpl(this); - const double displayRefreshInterval = 1.0 / 60.0; - OwnPtr<CCFrameRateController> frameRateController; - if (m_renderVSyncEnabled) - frameRateController = adoptPtr(new CCFrameRateController(CCDelayBasedTimeSource::create(displayRefreshInterval, CCProxy::implThread()))); - else - frameRateController = adoptPtr(new CCFrameRateController(CCProxy::implThread())); - m_schedulerOnImplThread = CCScheduler::create(this, frameRateController.release()); - m_schedulerOnImplThread->setVisible(m_layerTreeHostImpl->visible()); - - m_inputHandlerOnImplThread = popHandler; - if (m_inputHandlerOnImplThread) - m_inputHandlerOnImplThread->bindToClient(m_layerTreeHostImpl.get()); - - completion->signal(); -} - -void CCThreadProxy::initializeContextOnImplThread(CCGraphicsContext* context) -{ - TRACE_EVENT0("cc", "CCThreadProxy::initializeContextOnImplThread"); - ASSERT(isImplThread()); - m_contextBeforeInitializationOnImplThread = adoptPtr(context); -} - -void CCThreadProxy::initializeRendererOnImplThread(CCCompletionEvent* completion, bool* initializeSucceeded, RendererCapabilities* capabilities) -{ - TRACE_EVENT0("cc", "CCThreadProxy::initializeRendererOnImplThread"); - ASSERT(isImplThread()); - ASSERT(m_contextBeforeInitializationOnImplThread); - *initializeSucceeded = m_layerTreeHostImpl->initializeRenderer(m_contextBeforeInitializationOnImplThread.release(), textureUploader); - if (*initializeSucceeded) { - *capabilities = m_layerTreeHostImpl->rendererCapabilities(); - m_schedulerOnImplThread->setSwapBuffersCompleteSupported( - capabilities->usingSwapCompleteCallback); - } - - completion->signal(); -} - -void CCThreadProxy::layerTreeHostClosedOnImplThread(CCCompletionEvent* completion) -{ - TRACE_EVENT0("cc", "CCThreadProxy::layerTreeHostClosedOnImplThread"); - ASSERT(isImplThread()); - m_layerTreeHost->deleteContentsTexturesOnImplThread(m_layerTreeHostImpl->resourceProvider()); - m_inputHandlerOnImplThread.clear(); - m_layerTreeHostImpl.clear(); - m_schedulerOnImplThread.clear(); - completion->signal(); -} - -void CCThreadProxy::setFullRootLayerDamageOnImplThread() -{ - ASSERT(isImplThread()); - m_layerTreeHostImpl->setFullRootLayerDamage(); -} - -size_t CCThreadProxy::maxPartialTextureUpdates() const -{ - return CCTextureUpdateController::maxPartialTextureUpdates(); -} - -void CCThreadProxy::recreateContextOnImplThread(CCCompletionEvent* completion, CCGraphicsContext* contextPtr, bool* recreateSucceeded, RendererCapabilities* capabilities) -{ - TRACE_EVENT0("cc", "CCThreadProxy::recreateContextOnImplThread"); - ASSERT(isImplThread()); - m_layerTreeHost->deleteContentsTexturesOnImplThread(m_layerTreeHostImpl->resourceProvider()); - *recreateSucceeded = m_layerTreeHostImpl->initializeRenderer(adoptPtr(contextPtr), textureUploader); - if (*recreateSucceeded) { - *capabilities = m_layerTreeHostImpl->rendererCapabilities(); - m_schedulerOnImplThread->didRecreateContext(); - } - completion->signal(); -} - -void CCThreadProxy::implSideRenderingStatsOnImplThread(CCCompletionEvent* completion, CCRenderingStats* stats) -{ - ASSERT(isImplThread()); - m_layerTreeHostImpl->renderingStats(*stats); - completion->signal(); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCThreadProxy.h b/Source/WebCore/platform/graphics/chromium/cc/CCThreadProxy.h deleted file mode 100644 index b8e9af90a..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCThreadProxy.h +++ /dev/null @@ -1,201 +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 CCThreadProxy_h -#define CCThreadProxy_h - -#include "CCAnimationEvents.h" -#include "CCCompletionEvent.h" -#include "CCLayerTreeHostImpl.h" -#include "CCProxy.h" -#include "CCScheduler.h" -#include <wtf/OwnPtr.h> - -namespace WebCore { - -class CCInputHandler; -class CCLayerTreeHost; -class CCScheduler; -class CCScopedThreadProxy; -class CCTextureUpdateQueue; -class CCTextureUpdateController; -class CCThread; -class CCThreadProxyContextRecreationTimer; - -class CCThreadProxy : public CCProxy, CCLayerTreeHostImplClient, CCSchedulerClient { -public: - static PassOwnPtr<CCProxy> create(CCLayerTreeHost*); - - virtual ~CCThreadProxy(); - - // CCProxy implementation - virtual bool compositeAndReadback(void *pixels, const IntRect&) OVERRIDE; - virtual void startPageScaleAnimation(const IntSize& targetPosition, bool useAnchor, float scale, double duration) OVERRIDE; - virtual void finishAllRendering() OVERRIDE; - virtual bool isStarted() const OVERRIDE; - virtual bool initializeContext() OVERRIDE; - virtual void setSurfaceReady() OVERRIDE; - virtual void setVisible(bool) OVERRIDE; - virtual bool initializeRenderer() OVERRIDE; - virtual bool recreateContext() OVERRIDE; - virtual void implSideRenderingStats(CCRenderingStats&) OVERRIDE; - virtual const RendererCapabilities& rendererCapabilities() const OVERRIDE; - virtual void loseContext() OVERRIDE; - virtual void setNeedsAnimate() OVERRIDE; - virtual void setNeedsCommit() OVERRIDE; - virtual void setNeedsRedraw() OVERRIDE; - virtual bool commitRequested() const OVERRIDE; - virtual void didAddAnimation() OVERRIDE { } - virtual void start() OVERRIDE; - virtual void stop() OVERRIDE; - virtual size_t maxPartialTextureUpdates() const OVERRIDE; - virtual void acquireLayerTextures() OVERRIDE; - virtual void forceSerializeOnSwapBuffers() OVERRIDE; - - // CCLayerTreeHostImplClient implementation - virtual void didLoseContextOnImplThread() OVERRIDE; - virtual void onSwapBuffersCompleteOnImplThread() OVERRIDE; - virtual void onVSyncParametersChanged(double monotonicTimebase, double intervalInSeconds) OVERRIDE; - virtual void onCanDrawStateChanged(bool canDraw) OVERRIDE; - virtual void setNeedsRedrawOnImplThread() OVERRIDE; - virtual void setNeedsCommitOnImplThread() OVERRIDE; - virtual void postAnimationEventsToMainThreadOnImplThread(PassOwnPtr<CCAnimationEventsVector>, double wallClockTime) OVERRIDE; - virtual void releaseContentsTexturesOnImplThread() OVERRIDE; - - // CCSchedulerClient implementation - virtual bool hasMoreResourceUpdates() const OVERRIDE; - - virtual void scheduledActionBeginFrame() OVERRIDE; - virtual CCScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapIfPossible() OVERRIDE; - virtual CCScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapForced() OVERRIDE; - virtual void scheduledActionUpdateMoreResources(double monotonicTimeLimit) OVERRIDE; - virtual void scheduledActionCommit() OVERRIDE; - virtual void scheduledActionBeginContextRecreation() OVERRIDE; - virtual void scheduledActionAcquireLayerTexturesForMainThread() OVERRIDE; - -private: - explicit CCThreadProxy(CCLayerTreeHost*); - friend class CCThreadProxyContextRecreationTimer; - - // Set on impl thread, read on main thread. - struct BeginFrameAndCommitState { - BeginFrameAndCommitState() - : monotonicFrameBeginTime(0) - { - } - - double monotonicFrameBeginTime; - OwnPtr<CCScrollAndScaleSet> scrollInfo; - CCPrioritizedTextureManager::BackingVector evictedContentsTexturesBackings; - size_t memoryAllocationLimitBytes; - }; - OwnPtr<BeginFrameAndCommitState> m_pendingBeginFrameRequest; - - // Called on main thread - void beginFrame(); - void didCommitAndDrawFrame(); - void didCompleteSwapBuffers(); - void setAnimationEvents(PassOwnPtr<CCAnimationEventsVector>, double wallClockTime); - void beginContextRecreation(); - void tryToRecreateContext(); - - // Called on impl thread - struct ReadbackRequest { - CCCompletionEvent completion; - bool success; - void* pixels; - IntRect rect; - }; - void forceBeginFrameOnImplThread(CCCompletionEvent*); - void beginFrameCompleteOnImplThread(CCCompletionEvent*, PassOwnPtr<CCTextureUpdateQueue>); - void beginFrameAbortedOnImplThread(); - void requestReadbackOnImplThread(ReadbackRequest*); - void requestStartPageScaleAnimationOnImplThread(IntSize targetPosition, bool useAnchor, float scale, double durationSec); - void finishAllRenderingOnImplThread(CCCompletionEvent*); - void initializeImplOnImplThread(CCCompletionEvent*, PassOwnPtr<CCInputHandler>); - void setSurfaceReadyOnImplThread(); - void setVisibleOnImplThread(CCCompletionEvent*, bool); - void initializeContextOnImplThread(CCGraphicsContext*); - void initializeRendererOnImplThread(CCCompletionEvent*, bool* initializeSucceeded, RendererCapabilities*); - void layerTreeHostClosedOnImplThread(CCCompletionEvent*); - void setFullRootLayerDamageOnImplThread(); - void acquireLayerTexturesForMainThreadOnImplThread(CCCompletionEvent*); - void recreateContextOnImplThread(CCCompletionEvent*, CCGraphicsContext*, bool* recreateSucceeded, RendererCapabilities*); - void implSideRenderingStatsOnImplThread(CCCompletionEvent*, CCRenderingStats*); - CCScheduledActionDrawAndSwapResult scheduledActionDrawAndSwapInternal(bool forcedDraw); - void forceSerializeOnSwapBuffersOnImplThread(CCCompletionEvent*); - void setNeedsForcedCommitOnImplThread(); - - // Accessed on main thread only. - bool m_animateRequested; // Set only when setNeedsAnimate is called. - bool m_commitRequested; // Set only when setNeedsCommit is called. - bool m_commitRequestSentToImplThread; // Set by setNeedsCommit and setNeedsAnimate. - bool m_forcedCommitRequested; - OwnPtr<CCThreadProxyContextRecreationTimer> m_contextRecreationTimer; - CCLayerTreeHost* m_layerTreeHost; - bool m_rendererInitialized; - RendererCapabilities m_RendererCapabilitiesMainThreadCopy; - bool m_started; - bool m_texturesAcquired; - bool m_inCompositeAndReadback; - - OwnPtr<CCLayerTreeHostImpl> m_layerTreeHostImpl; - - OwnPtr<CCInputHandler> m_inputHandlerOnImplThread; - - OwnPtr<CCScheduler> m_schedulerOnImplThread; - - RefPtr<CCScopedThreadProxy> m_mainThreadProxy; - - // Holds on to the context we might use for compositing in between initializeContext() - // and initializeRenderer() calls. - OwnPtr<CCGraphicsContext> m_contextBeforeInitializationOnImplThread; - - // Set when the main thread is waiting on a scheduledActionBeginFrame to be issued. - CCCompletionEvent* m_beginFrameCompletionEventOnImplThread; - - // Set when the main thread is waiting on a readback. - ReadbackRequest* m_readbackRequestOnImplThread; - - // Set when the main thread is waiting on a commit to complete. - CCCompletionEvent* m_commitCompletionEventOnImplThread; - - // Set when the main thread is waiting on layers to be drawn. - CCCompletionEvent* m_textureAcquisitionCompletionEventOnImplThread; - - OwnPtr<CCTextureUpdateController> m_currentTextureUpdateControllerOnImplThread; - - // Set when we need to reset the contentsTexturesPurged flag after the - // commit. - bool m_resetContentsTexturesPurgedAfterCommitOnImplThread; - - // Set when the next draw should post didCommitAndDrawFrame to the main thread. - bool m_nextFrameIsNewlyCommittedFrameOnImplThread; - - bool m_renderVSyncEnabled; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCThreadTask.h b/Source/WebCore/platform/graphics/chromium/cc/CCThreadTask.h deleted file mode 100644 index bd520d224..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCThreadTask.h +++ /dev/null @@ -1,325 +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 CCThreadTask_h -#define CCThreadTask_h - -#include "CCThread.h" -#include <wtf/PassOwnPtr.h> -#include <wtf/PassRefPtr.h> - -namespace WebCore { - -template<typename T> -class CCThreadTask0 : public CCThread::Task { -public: - typedef void (T::*Method)(); - typedef CCThreadTask0<T> CCThreadTaskImpl; - - static PassOwnPtr<CCThreadTaskImpl> create(T* instance, Method method) - { - return adoptPtr(new CCThreadTaskImpl(instance, method)); - } - -private: - CCThreadTask0(T* instance, Method method) - : CCThread::Task(instance) - , m_method(method) - { - } - - virtual void performTask() OVERRIDE - { - (*static_cast<T*>(instance()).*m_method)(); - } - -private: - Method m_method; -}; - -template<typename T, typename P1, typename MP1> -class CCThreadTask1 : public CCThread::Task { -public: - typedef void (T::*Method)(MP1); - typedef CCThreadTask1<T, P1, MP1> CCThreadTaskImpl; - - static PassOwnPtr<CCThreadTaskImpl> create(T* instance, Method method, P1 parameter1) - { - return adoptPtr(new CCThreadTaskImpl(instance, method, parameter1)); - } - -private: - CCThreadTask1(T* instance, Method method, P1 parameter1) - : CCThread::Task(instance) - , m_method(method) - , m_parameter1(parameter1) - { - } - - virtual void performTask() OVERRIDE - { - (*static_cast<T*>(instance()).*m_method)(m_parameter1); - } - -private: - Method m_method; - P1 m_parameter1; -}; - -template<typename T, typename P1, typename MP1, typename P2, typename MP2> -class CCThreadTask2 : public CCThread::Task { -public: - typedef void (T::*Method)(MP1, MP2); - typedef CCThreadTask2<T, P1, MP1, P2, MP2> CCThreadTaskImpl; - - static PassOwnPtr<CCThreadTaskImpl> create(T* instance, Method method, P1 parameter1, P2 parameter2) - { - return adoptPtr(new CCThreadTaskImpl(instance, method, parameter1, parameter2)); - } - -private: - CCThreadTask2(T* instance, Method method, P1 parameter1, P2 parameter2) - : CCThread::Task(instance) - , m_method(method) - , m_parameter1(parameter1) - , m_parameter2(parameter2) - { - } - - virtual void performTask() OVERRIDE - { - (*static_cast<T*>(instance()).*m_method)(m_parameter1, m_parameter2); - } - -private: - Method m_method; - P1 m_parameter1; - P2 m_parameter2; -}; - -template<typename T, typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3> -class CCThreadTask3 : public CCThread::Task { -public: - typedef void (T::*Method)(MP1, MP2, MP3); - typedef CCThreadTask3<T, P1, MP1, P2, MP2, P3, MP3> CCThreadTaskImpl; - - static PassOwnPtr<CCThreadTaskImpl> create(T* instance, Method method, P1 parameter1, P2 parameter2, P3 parameter3) - { - return adoptPtr(new CCThreadTaskImpl(instance, method, parameter1, parameter2, parameter3)); - } - -private: - CCThreadTask3(T* instance, Method method, P1 parameter1, P2 parameter2, P3 parameter3) - : CCThread::Task(instance) - , m_method(method) - , m_parameter1(parameter1) - , m_parameter2(parameter2) - , m_parameter3(parameter3) - { - } - - virtual void performTask() OVERRIDE - { - (*static_cast<T*>(instance()).*m_method)(m_parameter1, m_parameter2, m_parameter3); - } - -private: - Method m_method; - P1 m_parameter1; - P2 m_parameter2; - P3 m_parameter3; -}; - - -template<typename T, typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4> -class CCThreadTask4 : public CCThread::Task { -public: - typedef void (T::*Method)(MP1, MP2, MP3, MP4); - typedef CCThreadTask4<T, P1, MP1, P2, MP2, P3, MP3, P4, MP4> CCThreadTaskImpl; - - static PassOwnPtr<CCThreadTaskImpl> create(T* instance, Method method, P1 parameter1, P2 parameter2, P3 parameter3, P4 parameter4) - { - return adoptPtr(new CCThreadTaskImpl(instance, method, parameter1, parameter2, parameter3, parameter4)); - } - -private: - CCThreadTask4(T* instance, Method method, P1 parameter1, P2 parameter2, P3 parameter3, P4 parameter4) - : CCThread::Task(instance) - , m_method(method) - , m_parameter1(parameter1) - , m_parameter2(parameter2) - , m_parameter3(parameter3) - , m_parameter4(parameter4) - { - } - - virtual void performTask() OVERRIDE - { - (*static_cast<T*>(instance()).*m_method)(m_parameter1, m_parameter2, m_parameter3, m_parameter4); - } - -private: - Method m_method; - P1 m_parameter1; - P2 m_parameter2; - P3 m_parameter3; - P4 m_parameter4; -}; - -template<typename T, typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5> -class CCThreadTask5 : public CCThread::Task { -public: - typedef void (T::*Method)(MP1, MP2, MP3, MP4, MP5); - typedef CCThreadTask5<T, P1, MP1, P2, MP2, P3, MP3, P4, MP4, P5, MP5> CCThreadTaskImpl; - - static PassOwnPtr<CCThreadTaskImpl> create(T* instance, Method method, P1 parameter1, P2 parameter2, P3 parameter3, P4 parameter4, P5 parameter5) - { - return adoptPtr(new CCThreadTaskImpl(instance, method, parameter1, parameter2, parameter3, parameter4, parameter5)); - } - -private: - CCThreadTask5(T* instance, Method method, P1 parameter1, P2 parameter2, P3 parameter3, P4 parameter4, P5 parameter5) - : CCThread::Task(instance) - , m_method(method) - , m_parameter1(parameter1) - , m_parameter2(parameter2) - , m_parameter3(parameter3) - , m_parameter4(parameter4) - , m_parameter5(parameter5) - { - } - - virtual void performTask() OVERRIDE - { - (*static_cast<T*>(instance()).*m_method)(m_parameter1, m_parameter2, m_parameter3, m_parameter4, m_parameter5); - } - -private: - Method m_method; - P1 m_parameter1; - P2 m_parameter2; - P3 m_parameter3; - P4 m_parameter4; - P5 m_parameter5; -}; - -template<typename T> -PassOwnPtr<CCThread::Task> createCCThreadTask( - T* const callee, - void (T::*method)()); - -template<typename T> -PassOwnPtr<CCThread::Task> createCCThreadTask( - T* const callee, - void (T::*method)()) -{ - return CCThreadTask0<T>::create( - callee, - method); -} - -template<typename T, typename P1, typename MP1> -PassOwnPtr<CCThread::Task> createCCThreadTask( - T* const callee, - void (T::*method)(MP1), - const P1& parameter1) -{ - return CCThreadTask1<T, P1, MP1>::create( - callee, - method, - parameter1); -} - -template<typename T, typename P1, typename MP1, typename P2, typename MP2> -PassOwnPtr<CCThread::Task> createCCThreadTask( - T* const callee, - void (T::*method)(MP1, MP2), - const P1& parameter1, - const P2& parameter2) -{ - return CCThreadTask2<T, P1, MP1, P2, MP2>::create( - callee, - method, - parameter1, - parameter2); -} - -template<typename T, typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3> -PassOwnPtr<CCThread::Task> createCCThreadTask( - T* const callee, - void (T::*method)(MP1, MP2, MP3), - const P1& parameter1, - const P2& parameter2, - const P3& parameter3) -{ - return CCThreadTask3<T, P1, MP1, P2, MP2, P3, MP3>::create( - callee, - method, - parameter1, - parameter2, - parameter3); -} - -template<typename T, typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4> -PassOwnPtr<CCThread::Task> createCCThreadTask( - T* const callee, - void (T::*method)(MP1, MP2, MP3, MP4), - const P1& parameter1, - const P2& parameter2, - const P3& parameter3, - const P4& parameter4) -{ - return CCThreadTask4<T, P1, MP1, P2, MP2, P3, MP3, P4, MP4>::create( - callee, - method, - parameter1, - parameter2, - parameter3, - parameter4); - -} - -template<typename T, typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5> -PassOwnPtr<CCThread::Task> createCCThreadTask( - T* const callee, - void (T::*method)(MP1, MP2, MP3, MP4, MP5), - const P1& parameter1, - const P2& parameter2, - const P3& parameter3, - const P4& parameter4, - const P5& parameter5) -{ - return CCThreadTask5<T, P1, MP1, P2, MP2, P3, MP3, P4, MP4, P5, MP5>::create( - callee, - method, - parameter1, - parameter2, - parameter3, - parameter4, - parameter5); - -} - -} // namespace WebCore - -#endif // CCThreadTask_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTileDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTileDrawQuad.cpp deleted file mode 100644 index 730835c39..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTileDrawQuad.cpp +++ /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: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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 "CCTileDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCTileDrawQuad> CCTileDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, const IntRect& opaqueRect, unsigned resourceId, const IntPoint& textureOffset, const IntSize& textureSize, GC3Dint textureFilter, bool swizzleContents, bool leftEdgeAA, bool topEdgeAA, bool rightEdgeAA, bool bottomEdgeAA) -{ - return adoptPtr(new CCTileDrawQuad(sharedQuadState, quadRect, opaqueRect, resourceId, textureOffset, textureSize, textureFilter, swizzleContents, leftEdgeAA, topEdgeAA, rightEdgeAA, bottomEdgeAA)); -} - -CCTileDrawQuad::CCTileDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, const IntRect& opaqueRect, unsigned resourceId, const IntPoint& textureOffset, const IntSize& textureSize, GC3Dint textureFilter, bool swizzleContents, bool leftEdgeAA, bool topEdgeAA, bool rightEdgeAA, bool bottomEdgeAA) - : CCDrawQuad(sharedQuadState, CCDrawQuad::TiledContent, quadRect) - , m_resourceId(resourceId) - , m_textureOffset(textureOffset) - , m_textureSize(textureSize) - , m_textureFilter(textureFilter) - , m_swizzleContents(swizzleContents) - , m_leftEdgeAA(leftEdgeAA) - , m_topEdgeAA(topEdgeAA) - , m_rightEdgeAA(rightEdgeAA) - , m_bottomEdgeAA(bottomEdgeAA) -{ - if (isAntialiased()) - m_needsBlending = true; - m_opaqueRect = opaqueRect; -} - -const CCTileDrawQuad* CCTileDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::TiledContent); - return static_cast<const CCTileDrawQuad*>(quad); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTileDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCTileDrawQuad.h deleted file mode 100644 index 53f2c8816..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTileDrawQuad.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 CCTileDrawQuad_h -#define CCTileDrawQuad_h - -#include "CCDrawQuad.h" -#include "GraphicsTypes3D.h" -#include "IntPoint.h" -#include "IntSize.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -#pragma pack(push, 4) - -class CCTileDrawQuad : public CCDrawQuad { -public: - static PassOwnPtr<CCTileDrawQuad> create(const CCSharedQuadState*, const IntRect& quadRect, const IntRect& opaqueRect, unsigned resourceId, const IntPoint& textureOffset, const IntSize& textureSize, GC3Dint textureFilter, bool swizzleContents, bool leftEdgeAA, bool topEdgeAA, bool rightEdgeAA, bool bottomEdgeAA); - - unsigned resourceId() const { return m_resourceId; } - IntPoint textureOffset() const { return m_textureOffset; } - IntSize textureSize() const { return m_textureSize; } - GC3Dint textureFilter() const { return m_textureFilter; } - bool swizzleContents() const { return m_swizzleContents; } - - bool leftEdgeAA() const { return m_leftEdgeAA; } - bool topEdgeAA() const { return m_topEdgeAA; } - bool rightEdgeAA() const { return m_rightEdgeAA; } - bool bottomEdgeAA() const { return m_bottomEdgeAA; } - - bool isAntialiased() const { return leftEdgeAA() || topEdgeAA() || rightEdgeAA() || bottomEdgeAA(); } - - static const CCTileDrawQuad* materialCast(const CCDrawQuad*); -private: - CCTileDrawQuad(const CCSharedQuadState*, const IntRect& quadRect, const IntRect& opaqueRect, unsigned resourceId, const IntPoint& textureOffset, const IntSize& textureSize, GC3Dint textureFilter, bool swizzleContents, bool leftEdgeAA, bool topEdgeAA, bool rightEdgeAA, bool bottomEdgeAA); - - unsigned m_resourceId; - IntPoint m_textureOffset; - IntSize m_textureSize; - GC3Dint m_textureFilter; - bool m_swizzleContents; - bool m_leftEdgeAA; - bool m_topEdgeAA; - bool m_rightEdgeAA; - bool m_bottomEdgeAA; -}; - -#pragma pack(pop) - -} - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.cpp deleted file mode 100644 index 6e00bf48c..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.cpp +++ /dev/null @@ -1,241 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCTiledLayerImpl.h" - -#include "CCAppendQuadsData.h" -#include "CCCheckerboardDrawQuad.h" -#include "CCDebugBorderDrawQuad.h" -#include "CCLayerTilingData.h" -#include "CCMathUtil.h" -#include "CCQuadSink.h" -#include "CCSolidColorDrawQuad.h" -#include "CCTileDrawQuad.h" -#include "FloatQuad.h" -#include "GraphicsContext3D.h" -#include "SkColor.h" -#include "TextStream.h" -#include <wtf/text/WTFString.h> - -using namespace std; -using WebKit::WebTransformationMatrix; - -namespace WebCore { - -static const int debugTileBorderWidth = 1; -static const int debugTileBorderAlpha = 100; -static const int debugTileBorderColorRed = 80; -static const int debugTileBorderColorGreen = 200; -static const int debugTileBorderColorBlue = 200; -static const int debugTileBorderMissingTileColorRed = 255; -static const int debugTileBorderMissingTileColorGreen = 0; -static const int debugTileBorderMissingTileColorBlue = 0; - -class DrawableTile : public CCLayerTilingData::Tile { - WTF_MAKE_NONCOPYABLE(DrawableTile); -public: - static PassOwnPtr<DrawableTile> create() { return adoptPtr(new DrawableTile()); } - - CCResourceProvider::ResourceId resourceId() const { return m_resourceId; } - void setResourceId(CCResourceProvider::ResourceId resourceId) { m_resourceId = resourceId; } - -private: - DrawableTile() : m_resourceId(0) { } - - CCResourceProvider::ResourceId m_resourceId; -}; - -CCTiledLayerImpl::CCTiledLayerImpl(int id) - : CCLayerImpl(id) - , m_skipsDraw(true) - , m_contentsSwizzled(false) -{ -} - -CCTiledLayerImpl::~CCTiledLayerImpl() -{ -} - -CCResourceProvider::ResourceId CCTiledLayerImpl::contentsResourceId() const -{ - // This function is only valid for single texture layers, e.g. masks. - ASSERT(m_tiler); - ASSERT(m_tiler->numTilesX() == 1); - ASSERT(m_tiler->numTilesY() == 1); - - DrawableTile* tile = tileAt(0, 0); - CCResourceProvider::ResourceId resourceId = tile ? tile->resourceId() : 0; - ASSERT(resourceId); - - return resourceId; -} - -void CCTiledLayerImpl::dumpLayerProperties(TextStream& ts, int indent) const -{ - CCLayerImpl::dumpLayerProperties(ts, indent); - writeIndent(ts, indent); - ts << "skipsDraw: " << (!m_tiler || m_skipsDraw) << "\n"; -} - -bool CCTiledLayerImpl::hasTileAt(int i, int j) const -{ - return m_tiler->tileAt(i, j); -} - -bool CCTiledLayerImpl::hasTextureIdForTileAt(int i, int j) const -{ - return hasTileAt(i, j) && tileAt(i, j)->resourceId(); -} - -DrawableTile* CCTiledLayerImpl::tileAt(int i, int j) const -{ - return static_cast<DrawableTile*>(m_tiler->tileAt(i, j)); -} - -DrawableTile* CCTiledLayerImpl::createTile(int i, int j) -{ - OwnPtr<DrawableTile> tile(DrawableTile::create()); - DrawableTile* addedTile = tile.get(); - m_tiler->addTile(tile.release(), i, j); - return addedTile; -} - -void CCTiledLayerImpl::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData) -{ - const IntRect& contentRect = visibleContentRect(); - - if (!m_tiler || m_tiler->hasEmptyBounds() || contentRect.isEmpty()) - return; - - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState()); - appendDebugBorderQuad(quadSink, sharedQuadState, appendQuadsData); - - int left, top, right, bottom; - m_tiler->contentRectToTileIndices(contentRect, left, top, right, bottom); - - if (hasDebugBorders()) { - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - DrawableTile* tile = tileAt(i, j); - IntRect tileRect = m_tiler->tileBounds(i, j); - SkColor borderColor; - - if (m_skipsDraw || !tile || !tile->resourceId()) - borderColor = SkColorSetARGB(debugTileBorderAlpha, debugTileBorderMissingTileColorRed, debugTileBorderMissingTileColorGreen, debugTileBorderMissingTileColorBlue); - else - borderColor = SkColorSetARGB(debugTileBorderAlpha, debugTileBorderColorRed, debugTileBorderColorGreen, debugTileBorderColorBlue); - quadSink.append(CCDebugBorderDrawQuad::create(sharedQuadState, tileRect, borderColor, debugTileBorderWidth), appendQuadsData); - } - } - } - - if (m_skipsDraw) - return; - - for (int j = top; j <= bottom; ++j) { - for (int i = left; i <= right; ++i) { - DrawableTile* tile = tileAt(i, j); - IntRect tileRect = m_tiler->tileBounds(i, j); - IntRect displayRect = tileRect; - tileRect.intersect(contentRect); - - // Skip empty tiles. - if (tileRect.isEmpty()) - continue; - - if (!tile || !tile->resourceId()) { - if (drawCheckerboardForMissingTiles()) - appendQuadsData.hadMissingTiles |= quadSink.append(CCCheckerboardDrawQuad::create(sharedQuadState, tileRect), appendQuadsData); - else - appendQuadsData.hadMissingTiles |= quadSink.append(CCSolidColorDrawQuad::create(sharedQuadState, tileRect, backgroundColor()), appendQuadsData); - continue; - } - - IntRect tileOpaqueRect = tile->opaqueRect(); - tileOpaqueRect.intersect(contentRect); - - // Keep track of how the top left has moved, so the texture can be - // offset the same amount. - IntSize displayOffset = tileRect.minXMinYCorner() - displayRect.minXMinYCorner(); - IntPoint textureOffset = m_tiler->textureOffset(i, j) + displayOffset; - float tileWidth = static_cast<float>(m_tiler->tileSize().width()); - float tileHeight = static_cast<float>(m_tiler->tileSize().height()); - IntSize textureSize(tileWidth, tileHeight); - - bool clipped = false; - FloatQuad visibleContentInTargetQuad = CCMathUtil::mapQuad(drawTransform(), FloatQuad(visibleContentRect()), clipped); - bool isAxisAlignedInTarget = !clipped && visibleContentInTargetQuad.isRectilinear(); - bool useAA = m_tiler->hasBorderTexels() && !isAxisAlignedInTarget; - - bool leftEdgeAA = !i && useAA; - bool topEdgeAA = !j && useAA; - bool rightEdgeAA = i == m_tiler->numTilesX() - 1 && useAA; - bool bottomEdgeAA = j == m_tiler->numTilesY() - 1 && useAA; - - const GC3Dint textureFilter = m_tiler->hasBorderTexels() ? GraphicsContext3D::LINEAR : GraphicsContext3D::NEAREST; - quadSink.append(CCTileDrawQuad::create(sharedQuadState, tileRect, tileOpaqueRect, tile->resourceId(), textureOffset, textureSize, textureFilter, contentsSwizzled(), leftEdgeAA, topEdgeAA, rightEdgeAA, bottomEdgeAA), appendQuadsData); - } - } -} - -void CCTiledLayerImpl::setTilingData(const CCLayerTilingData& tiler) -{ - if (m_tiler) - m_tiler->reset(); - else - m_tiler = CCLayerTilingData::create(tiler.tileSize(), tiler.hasBorderTexels() ? CCLayerTilingData::HasBorderTexels : CCLayerTilingData::NoBorderTexels); - *m_tiler = tiler; -} - -void CCTiledLayerImpl::pushTileProperties(int i, int j, CCResourceProvider::ResourceId resourceId, const IntRect& opaqueRect) -{ - DrawableTile* tile = tileAt(i, j); - if (!tile) - tile = createTile(i, j); - tile->setResourceId(resourceId); - tile->setOpaqueRect(opaqueRect); -} - -Region CCTiledLayerImpl::visibleContentOpaqueRegion() const -{ - if (m_skipsDraw) - return Region(); - if (opaque()) - return visibleContentRect(); - return m_tiler->opaqueRegionInContentRect(visibleContentRect()); -} - -void CCTiledLayerImpl::didLoseContext() -{ - m_tiler->reset(); -} - -} // namespace WebCore - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.h deleted file mode 100644 index 6456e4c0b..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTiledLayerImpl.h +++ /dev/null @@ -1,82 +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 CCTiledLayerImpl_h -#define CCTiledLayerImpl_h - -#include "CCLayerImpl.h" -#include <public/WebTransformationMatrix.h> - -namespace WebCore { - -class CCLayerTilingData; -class DrawableTile; - -class CCTiledLayerImpl : public CCLayerImpl { -public: - static PassOwnPtr<CCTiledLayerImpl> create(int id) - { - return adoptPtr(new CCTiledLayerImpl(id)); - } - virtual ~CCTiledLayerImpl(); - - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) OVERRIDE; - - virtual CCResourceProvider::ResourceId contentsResourceId() const OVERRIDE; - - virtual void dumpLayerProperties(TextStream&, int indent) const OVERRIDE; - - void setSkipsDraw(bool skipsDraw) { m_skipsDraw = skipsDraw; } - void setTilingData(const CCLayerTilingData& tiler); - void pushTileProperties(int, int, CCResourceProvider::ResourceId, const IntRect& opaqueRect); - - void setContentsSwizzled(bool contentsSwizzled) { m_contentsSwizzled = contentsSwizzled; } - bool contentsSwizzled() const { return m_contentsSwizzled; } - - virtual Region visibleContentOpaqueRegion() const OVERRIDE; - virtual void didLoseContext() OVERRIDE; - -protected: - explicit CCTiledLayerImpl(int id); - // Exposed for testing. - bool hasTileAt(int, int) const; - bool hasTextureIdForTileAt(int, int) const; - -private: - - virtual const char* layerTypeAsString() const OVERRIDE { return "ContentLayer"; } - - DrawableTile* tileAt(int, int) const; - DrawableTile* createTile(int, int); - - bool m_skipsDraw; - bool m_contentsSwizzled; - - OwnPtr<CCLayerTilingData> m_tiler; -}; - -} - -#endif // CCTiledLayerImpl_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTimeSource.h b/Source/WebCore/platform/graphics/chromium/cc/CCTimeSource.h deleted file mode 100644 index 426a25364..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTimeSource.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. - * - * 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 CCTimeSource_h -#define CCTimeSource_h - -#include <wtf/RefCounted.h> - -namespace WebCore { - -class CCThread; - -class CCTimeSourceClient { -public: - virtual void onTimerTick() = 0; - -protected: - virtual ~CCTimeSourceClient() { } -}; - -// An generic interface for getting a reliably-ticking timesource of -// a specified rate. -// -// Be sure to call setActive(false) before releasing your reference to the -// timer, or it will keep on ticking! -class CCTimeSource : public RefCounted<CCTimeSource> { -public: - virtual ~CCTimeSource() { } - virtual void setClient(CCTimeSourceClient*) = 0; - virtual void setActive(bool) = 0; - virtual bool active() const = 0; - virtual void setTimebaseAndInterval(double timebase, double intervalSeconds) = 0; - virtual double lastTickTime() = 0; - virtual double nextTickTimeIfActivated() = 0; -}; - -} -#endif // CCSmoothedTimer_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTimer.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTimer.cpp deleted file mode 100644 index a5586adb5..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTimer.cpp +++ /dev/null @@ -1,105 +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 "CCTimer.h" - -#include "CCThread.h" - -namespace WebCore { - -class CCTimerTask : public CCThread::Task { -public: - explicit CCTimerTask(CCTimer* timer) - : CCThread::Task(0) - , m_timer(timer) - { - } - - ~CCTimerTask() - { - if (!m_timer) - return; - - ASSERT(m_timer->m_task == this); - m_timer->stop(); - } - - void performTask() - { - if (!m_timer) - return; - - CCTimerClient* client = m_timer->m_client; - - m_timer->stop(); - if (client) - client->onTimerFired(); - } - -private: - friend class CCTimer; - - CCTimer* m_timer; // null if cancelled -}; - -CCTimer::CCTimer(CCThread* thread, CCTimerClient* client) - : m_client(client) - , m_thread(thread) - , m_task(0) -{ -} - -CCTimer::~CCTimer() -{ - stop(); -} - -void CCTimer::startOneShot(double intervalSeconds) -{ - stop(); - - m_task = new CCTimerTask(this); - - // The thread expects delays in milliseconds. - m_thread->postDelayedTask(adoptPtr(m_task), intervalSeconds * 1000.0); -} - -void CCTimer::stop() -{ - if (!m_task) - return; - - m_task->m_timer = 0; - m_task = 0; -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTimer.h b/Source/WebCore/platform/graphics/chromium/cc/CCTimer.h deleted file mode 100644 index d3288c63c..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTimer.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: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CCTimer_h -#define CCTimer_h - - -namespace WebCore { - -class CCThread; -class CCTimerTask; - -class CCTimerClient { -public: - virtual ~CCTimerClient() { } - - virtual void onTimerFired() = 0; -}; - -class CCTimer { -public: - CCTimer(CCThread*, CCTimerClient*); - ~CCTimer(); - - // If a previous task is pending, it will be replaced with the new one. - void startOneShot(double intervalSeconds); - void stop(); - - bool isActive() const { return m_task; } - -private: - friend class CCTimerTask; - - CCTimerClient* m_client; - CCThread* m_thread; - CCTimerTask* m_task; // weak pointer -}; - -} // namespace WebCore - -#endif diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTimingFunction.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCTimingFunction.cpp deleted file mode 100644 index 28b5c13df..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTimingFunction.cpp +++ /dev/null @@ -1,96 +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 "CCTimingFunction.h" - -#include <wtf/OwnPtr.h> - -namespace { -const double epsilon = 1e-6; -} // namespace - -namespace WebCore { - -CCTimingFunction::CCTimingFunction() -{ -} - -CCTimingFunction::~CCTimingFunction() -{ -} - -double CCTimingFunction::duration() const -{ - return 1.0; -} - -PassOwnPtr<CCCubicBezierTimingFunction> CCCubicBezierTimingFunction::create(double x1, double y1, double x2, double y2) -{ - return adoptPtr(new CCCubicBezierTimingFunction(x1, y1, x2, y2)); -} - -CCCubicBezierTimingFunction::CCCubicBezierTimingFunction(double x1, double y1, double x2, double y2) - : m_curve(x1, y1, x2, y2) -{ -} - -CCCubicBezierTimingFunction::~CCCubicBezierTimingFunction() -{ -} - -float CCCubicBezierTimingFunction::getValue(double x) const -{ - UnitBezier temp(m_curve); - return static_cast<float>(temp.solve(x, epsilon)); -} - -PassOwnPtr<CCAnimationCurve> CCCubicBezierTimingFunction::clone() const -{ - return adoptPtr(new CCCubicBezierTimingFunction(*this)); -} - -// These numbers come from http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag. -PassOwnPtr<CCTimingFunction> CCEaseTimingFunction::create() -{ - return CCCubicBezierTimingFunction::create(0.25, 0.1, 0.25, 1); -} - -PassOwnPtr<CCTimingFunction> CCEaseInTimingFunction::create() -{ - return CCCubicBezierTimingFunction::create(0.42, 0, 1.0, 1); -} - -PassOwnPtr<CCTimingFunction> CCEaseOutTimingFunction::create() -{ - return CCCubicBezierTimingFunction::create(0, 0, 0.58, 1); -} - -PassOwnPtr<CCTimingFunction> CCEaseInOutTimingFunction::create() -{ - return CCCubicBezierTimingFunction::create(0.42, 0, 0.58, 1); -} - -} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCTimingFunction.h b/Source/WebCore/platform/graphics/chromium/cc/CCTimingFunction.h deleted file mode 100644 index 6a79363d7..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCTimingFunction.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 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 CCTimingFunction_h -#define CCTimingFunction_h - -#include "CCAnimationCurve.h" -#include "UnitBezier.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -// See http://www.w3.org/TR/css3-transitions/. -class CCTimingFunction : public CCFloatAnimationCurve { -public: - virtual ~CCTimingFunction(); - - // Partial implementation of CCFloatAnimationCurve. - virtual double duration() const OVERRIDE; - -protected: - CCTimingFunction(); -}; - -class CCCubicBezierTimingFunction : public CCTimingFunction { -public: - static PassOwnPtr<CCCubicBezierTimingFunction> create(double x1, double y1, double x2, double y2); - virtual ~CCCubicBezierTimingFunction(); - - // Partial implementation of CCFloatAnimationCurve. - virtual float getValue(double time) const OVERRIDE; - virtual PassOwnPtr<CCAnimationCurve> clone() const OVERRIDE; - -protected: - CCCubicBezierTimingFunction(double x1, double y1, double x2, double y2); - - UnitBezier m_curve; -}; - -class CCEaseTimingFunction { -public: - static PassOwnPtr<CCTimingFunction> create(); -}; - -class CCEaseInTimingFunction { -public: - static PassOwnPtr<CCTimingFunction> create(); -}; - -class CCEaseOutTimingFunction { -public: - static PassOwnPtr<CCTimingFunction> create(); -}; - -class CCEaseInOutTimingFunction { -public: - static PassOwnPtr<CCTimingFunction> create(); -}; - -} // namespace WebCore - -#endif // CCTimingFunction_h - diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCVideoLayerImpl.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCVideoLayerImpl.cpp deleted file mode 100644 index 0a4e8b819..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCVideoLayerImpl.cpp +++ /dev/null @@ -1,409 +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" - -#if USE(ACCELERATED_COMPOSITING) - -#include "CCVideoLayerImpl.h" - -#include "CCIOSurfaceDrawQuad.h" -#include "CCLayerTreeHostImpl.h" -#include "CCProxy.h" -#include "CCQuadSink.h" -#include "CCResourceProvider.h" -#include "CCStreamVideoDrawQuad.h" -#include "CCTextureDrawQuad.h" -#include "CCYUVVideoDrawQuad.h" -#include "Extensions3DChromium.h" -#include "GraphicsContext3D.h" -#include "NotImplemented.h" -#include "TextStream.h" -#include <public/WebVideoFrame.h> -#include <wtf/text/WTFString.h> - -namespace WebCore { - -CCVideoLayerImpl::CCVideoLayerImpl(int id, WebKit::WebVideoFrameProvider* provider) - : CCLayerImpl(id) - , m_provider(provider) - , m_frame(0) - , m_externalTextureResource(0) -{ - // This matrix is the default transformation for stream textures, and flips on the Y axis. - m_streamTextureMatrix = WebKit::WebTransformationMatrix( - 1, 0, 0, 0, - 0, -1, 0, 0, - 0, 0, 1, 0, - 0, 1, 0, 1); - - // This only happens during a commit on the compositor thread while the main - // thread is blocked. That makes this a thread-safe call to set the video - // frame provider client that does not require a lock. The same is true of - // the call in the destructor. - ASSERT(CCProxy::isMainThreadBlocked()); - m_provider->setVideoFrameProviderClient(this); -} - -CCVideoLayerImpl::~CCVideoLayerImpl() -{ - // See comment in constructor for why this doesn't need a lock. - ASSERT(CCProxy::isMainThreadBlocked()); - if (m_provider) { - m_provider->setVideoFrameProviderClient(0); - m_provider = 0; - } - freePlaneData(layerTreeHostImpl()->resourceProvider()); - -#if !ASSERT_DISABLED - for (unsigned i = 0; i < WebKit::WebVideoFrame::maxPlanes; ++i) - ASSERT(!m_framePlanes[i].resourceId); - ASSERT(!m_externalTextureResource); -#endif -} - -void CCVideoLayerImpl::stopUsingProvider() -{ - // Block the provider from shutting down until this client is done - // using the frame. - MutexLocker locker(m_providerMutex); - ASSERT(!m_frame); - m_provider = 0; -} - -// Convert WebKit::WebVideoFrame::Format to GraphicsContext3D's format enum values. -static GC3Denum convertVFCFormatToGC3DFormat(const WebKit::WebVideoFrame& frame) -{ - switch (frame.format()) { - case WebKit::WebVideoFrame::FormatYV12: - case WebKit::WebVideoFrame::FormatYV16: - return GraphicsContext3D::LUMINANCE; - case WebKit::WebVideoFrame::FormatNativeTexture: - return frame.textureTarget(); - case WebKit::WebVideoFrame::FormatInvalid: - case WebKit::WebVideoFrame::FormatRGB32: - case WebKit::WebVideoFrame::FormatEmpty: - case WebKit::WebVideoFrame::FormatI420: - notImplemented(); - } - return GraphicsContext3D::INVALID_VALUE; -} - -void CCVideoLayerImpl::willDraw(CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - CCLayerImpl::willDraw(resourceProvider); - - // Explicitly lock and unlock the provider mutex so it can be held from - // willDraw to didDraw. Since the compositor thread is in the middle of - // drawing, the layer will not be destroyed before didDraw is called. - // Therefore, the only thing that will prevent this lock from being released - // is the GPU process locking it. As the GPU process can't cause the - // destruction of the provider (calling stopUsingProvider), holding this - // lock should not cause a deadlock. - m_providerMutex.lock(); - - willDrawInternal(resourceProvider); - freeUnusedPlaneData(resourceProvider); - - if (!m_frame) - m_providerMutex.unlock(); -} - -void CCVideoLayerImpl::willDrawInternal(CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - ASSERT(!m_externalTextureResource); - - if (!m_provider) { - m_frame = 0; - return; - } - - m_frame = m_provider->getCurrentFrame(); - - if (!m_frame) - return; - - m_format = convertVFCFormatToGC3DFormat(*m_frame); - - if (m_format == GraphicsContext3D::INVALID_VALUE) { - m_provider->putCurrentFrame(m_frame); - m_frame = 0; - return; - } - - if (m_frame->planes() > WebKit::WebVideoFrame::maxPlanes) { - m_provider->putCurrentFrame(m_frame); - m_frame = 0; - return; - } - - if (!allocatePlaneData(resourceProvider)) { - m_provider->putCurrentFrame(m_frame); - m_frame = 0; - return; - } - - if (!copyPlaneData(resourceProvider)) { - m_provider->putCurrentFrame(m_frame); - m_frame = 0; - return; - } - - if (m_format == GraphicsContext3D::TEXTURE_2D) - m_externalTextureResource = resourceProvider->createResourceFromExternalTexture(m_frame->textureId()); -} - -void CCVideoLayerImpl::appendQuads(CCQuadSink& quadSink, CCAppendQuadsData& appendQuadsData) -{ - ASSERT(CCProxy::isImplThread()); - - if (!m_frame) - return; - - CCSharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState()); - appendDebugBorderQuad(quadSink, sharedQuadState, appendQuadsData); - - // FIXME: When we pass quads out of process, we need to double-buffer, or - // otherwise synchonize use of all textures in the quad. - - IntRect quadRect(IntPoint(), contentBounds()); - - switch (m_format) { - case GraphicsContext3D::LUMINANCE: { - // YUV software decoder. - const FramePlane& yPlane = m_framePlanes[WebKit::WebVideoFrame::yPlane]; - const FramePlane& uPlane = m_framePlanes[WebKit::WebVideoFrame::uPlane]; - const FramePlane& vPlane = m_framePlanes[WebKit::WebVideoFrame::vPlane]; - OwnPtr<CCYUVVideoDrawQuad> yuvVideoQuad = CCYUVVideoDrawQuad::create(sharedQuadState, quadRect, yPlane, uPlane, vPlane); - quadSink.append(yuvVideoQuad.release(), appendQuadsData); - break; - } - case GraphicsContext3D::RGBA: { - // RGBA software decoder. - const FramePlane& plane = m_framePlanes[WebKit::WebVideoFrame::rgbPlane]; - float widthScaleFactor = static_cast<float>(plane.visibleSize.width()) / plane.size.width(); - - bool premultipliedAlpha = true; - FloatRect uvRect(0, 0, widthScaleFactor, 1); - bool flipped = false; - OwnPtr<CCTextureDrawQuad> textureQuad = CCTextureDrawQuad::create(sharedQuadState, quadRect, plane.resourceId, premultipliedAlpha, uvRect, flipped); - quadSink.append(textureQuad.release(), appendQuadsData); - break; - } - case GraphicsContext3D::TEXTURE_2D: { - // NativeTexture hardware decoder. - bool premultipliedAlpha = true; - FloatRect uvRect(0, 0, 1, 1); - bool flipped = false; - OwnPtr<CCTextureDrawQuad> textureQuad = CCTextureDrawQuad::create(sharedQuadState, quadRect, m_externalTextureResource, premultipliedAlpha, uvRect, flipped); - quadSink.append(textureQuad.release(), appendQuadsData); - break; - } - case Extensions3D::TEXTURE_RECTANGLE_ARB: { - IntSize textureSize(m_frame->width(), m_frame->height()); - OwnPtr<CCIOSurfaceDrawQuad> ioSurfaceQuad = CCIOSurfaceDrawQuad::create(sharedQuadState, quadRect, textureSize, m_frame->textureId(), CCIOSurfaceDrawQuad::Unflipped); - quadSink.append(ioSurfaceQuad.release(), appendQuadsData); - break; - } - case Extensions3DChromium::GL_TEXTURE_EXTERNAL_OES: { - // StreamTexture hardware decoder. - OwnPtr<CCStreamVideoDrawQuad> streamVideoQuad = CCStreamVideoDrawQuad::create(sharedQuadState, quadRect, m_frame->textureId(), m_streamTextureMatrix); - quadSink.append(streamVideoQuad.release(), appendQuadsData); - break; - } - default: - CRASH(); // Someone updated convertVFCFormatToGC3DFormat above but update this! - } -} - -void CCVideoLayerImpl::didDraw(CCResourceProvider* resourceProvider) -{ - ASSERT(CCProxy::isImplThread()); - CCLayerImpl::didDraw(resourceProvider); - - if (!m_frame) - return; - - if (m_format == GraphicsContext3D::TEXTURE_2D) { - ASSERT(m_externalTextureResource); - // FIXME: the following assert will not be true when sending resources to a - // parent compositor. We will probably need to hold on to m_frame for - // longer, and have several "current frames" in the pipeline. - ASSERT(!resourceProvider->inUseByConsumer(m_externalTextureResource)); - resourceProvider->deleteResource(m_externalTextureResource); - m_externalTextureResource = 0; - } - - m_provider->putCurrentFrame(m_frame); - m_frame = 0; - - m_providerMutex.unlock(); -} - -static int videoFrameDimension(int originalDimension, unsigned plane, int format) -{ - if (format == WebKit::WebVideoFrame::FormatYV12 && plane != WebKit::WebVideoFrame::yPlane) - return originalDimension / 2; - return originalDimension; -} - -static bool hasPaddingBytes(const WebKit::WebVideoFrame& frame, unsigned plane) -{ - return frame.stride(plane) > videoFrameDimension(frame.width(), plane, frame.format()); -} - -IntSize CCVideoLayerImpl::computeVisibleSize(const WebKit::WebVideoFrame& frame, unsigned plane) -{ - int visibleWidth = videoFrameDimension(frame.width(), plane, frame.format()); - int originalWidth = visibleWidth; - int visibleHeight = videoFrameDimension(frame.height(), plane, frame.format()); - - // When there are dead pixels at the edge of the texture, decrease - // the frame width by 1 to prevent the rightmost pixels from - // interpolating with the dead pixels. - if (hasPaddingBytes(frame, plane)) - --visibleWidth; - - // In YV12, every 2x2 square of Y values corresponds to one U and - // one V value. If we decrease the width of the UV plane, we must decrease the - // width of the Y texture by 2 for proper alignment. This must happen - // always, even if Y's texture does not have padding bytes. - if (plane == WebKit::WebVideoFrame::yPlane && frame.format() == WebKit::WebVideoFrame::FormatYV12) { - if (hasPaddingBytes(frame, WebKit::WebVideoFrame::uPlane)) - visibleWidth = originalWidth - 2; - } - - return IntSize(visibleWidth, visibleHeight); -} - -bool CCVideoLayerImpl::FramePlane::allocateData(CCResourceProvider* resourceProvider) -{ - if (resourceId) - return true; - - resourceId = resourceProvider->createResource(CCRenderer::ImplPool, size, format, CCResourceProvider::TextureUsageAny); - return resourceId; -} - -void CCVideoLayerImpl::FramePlane::freeData(CCResourceProvider* resourceProvider) -{ - if (!resourceId) - return; - - resourceProvider->deleteResource(resourceId); - resourceId = 0; -} - -bool CCVideoLayerImpl::allocatePlaneData(CCResourceProvider* resourceProvider) -{ - int maxTextureSize = resourceProvider->maxTextureSize(); - for (unsigned planeIndex = 0; planeIndex < m_frame->planes(); ++planeIndex) { - CCVideoLayerImpl::FramePlane& plane = m_framePlanes[planeIndex]; - - IntSize requiredTextureSize(m_frame->stride(planeIndex), videoFrameDimension(m_frame->height(), planeIndex, m_frame->format())); - // FIXME: Remove the test against maxTextureSize when tiled layers are implemented. - if (requiredTextureSize.isZero() || requiredTextureSize.width() > maxTextureSize || requiredTextureSize.height() > maxTextureSize) - return false; - - if (plane.size != requiredTextureSize || plane.format != m_format) { - plane.freeData(resourceProvider); - plane.size = requiredTextureSize; - plane.format = m_format; - } - - if (!plane.resourceId) { - if (!plane.allocateData(resourceProvider)) - return false; - plane.visibleSize = computeVisibleSize(*m_frame, planeIndex); - } - } - return true; -} - -bool CCVideoLayerImpl::copyPlaneData(CCResourceProvider* resourceProvider) -{ - size_t softwarePlaneCount = m_frame->planes(); - if (!softwarePlaneCount) - return true; - - for (size_t softwarePlaneIndex = 0; softwarePlaneIndex < softwarePlaneCount; ++softwarePlaneIndex) { - CCVideoLayerImpl::FramePlane& plane = m_framePlanes[softwarePlaneIndex]; - const uint8_t* softwarePlanePixels = static_cast<const uint8_t*>(m_frame->data(softwarePlaneIndex)); - IntRect planeRect(IntPoint(), plane.size); - resourceProvider->upload(plane.resourceId, softwarePlanePixels, planeRect, planeRect, IntSize()); - } - return true; -} - -void CCVideoLayerImpl::freePlaneData(CCResourceProvider* resourceProvider) -{ - for (unsigned i = 0; i < WebKit::WebVideoFrame::maxPlanes; ++i) - m_framePlanes[i].freeData(resourceProvider); -} - -void CCVideoLayerImpl::freeUnusedPlaneData(CCResourceProvider* resourceProvider) -{ - unsigned firstUnusedPlane = m_frame ? m_frame->planes() : 0; - for (unsigned i = firstUnusedPlane; i < WebKit::WebVideoFrame::maxPlanes; ++i) - m_framePlanes[i].freeData(resourceProvider); -} - -void CCVideoLayerImpl::didReceiveFrame() -{ - setNeedsRedraw(); -} - -void CCVideoLayerImpl::didUpdateMatrix(const float matrix[16]) -{ - m_streamTextureMatrix = WebKit::WebTransformationMatrix( - matrix[0], matrix[1], matrix[2], matrix[3], - matrix[4], matrix[5], matrix[6], matrix[7], - matrix[8], matrix[9], matrix[10], matrix[11], - matrix[12], matrix[13], matrix[14], matrix[15]); - setNeedsRedraw(); -} - -void CCVideoLayerImpl::didLoseContext() -{ - freePlaneData(layerTreeHostImpl()->resourceProvider()); -} - -void CCVideoLayerImpl::setNeedsRedraw() -{ - layerTreeHostImpl()->setNeedsRedraw(); -} - -void CCVideoLayerImpl::dumpLayerProperties(TextStream& ts, int indent) const -{ - writeIndent(ts, indent); - ts << "video layer\n"; - CCLayerImpl::dumpLayerProperties(ts, indent); -} - -} - -#endif // USE(ACCELERATED_COMPOSITING) diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCVideoLayerImpl.h b/Source/WebCore/platform/graphics/chromium/cc/CCVideoLayerImpl.h deleted file mode 100644 index f8e89741e..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCVideoLayerImpl.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 AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef CCVideoLayerImpl_h -#define CCVideoLayerImpl_h - -#include "CCLayerImpl.h" -#include "GraphicsContext3D.h" -#include "IntSize.h" -#include <public/WebTransformationMatrix.h> -#include <public/WebVideoFrameProvider.h> - -namespace WebKit { -class WebVideoFrame; -} - -namespace WebCore { - -class CCLayerTreeHostImpl; -class CCVideoLayerImpl; - -class CCVideoLayerImpl : public CCLayerImpl - , public WebKit::WebVideoFrameProvider::Client { -public: - static PassOwnPtr<CCVideoLayerImpl> create(int id, WebKit::WebVideoFrameProvider* provider) - { - return adoptPtr(new CCVideoLayerImpl(id, provider)); - } - virtual ~CCVideoLayerImpl(); - - virtual void willDraw(CCResourceProvider*) OVERRIDE; - virtual void appendQuads(CCQuadSink&, CCAppendQuadsData&) OVERRIDE; - virtual void didDraw(CCResourceProvider*) OVERRIDE; - - virtual void dumpLayerProperties(TextStream&, int indent) const OVERRIDE; - - Mutex& providerMutex() { return m_providerMutex; } - - // WebKit::WebVideoFrameProvider::Client implementation. - virtual void stopUsingProvider(); // Callable on any thread. - virtual void didReceiveFrame(); // Callable on impl thread. - virtual void didUpdateMatrix(const float*); // Callable on impl thread. - - virtual void didLoseContext() OVERRIDE; - - void setNeedsRedraw(); - - struct FramePlane { - CCResourceProvider::ResourceId resourceId; - IntSize size; - GC3Denum format; - IntSize visibleSize; - - FramePlane() : resourceId(0) { } - - bool allocateData(CCResourceProvider*); - void freeData(CCResourceProvider*); - }; - -private: - CCVideoLayerImpl(int, WebKit::WebVideoFrameProvider*); - - static IntSize computeVisibleSize(const WebKit::WebVideoFrame&, unsigned plane); - virtual const char* layerTypeAsString() const OVERRIDE { return "VideoLayer"; } - - void willDrawInternal(CCResourceProvider*); - bool allocatePlaneData(CCResourceProvider*); - bool copyPlaneData(CCResourceProvider*); - void freePlaneData(CCResourceProvider*); - void freeUnusedPlaneData(CCResourceProvider*); - - // Guards the destruction of m_provider and the frame that it provides - Mutex m_providerMutex; - WebKit::WebVideoFrameProvider* m_provider; - - WebKit::WebTransformationMatrix m_streamTextureMatrix; - - WebKit::WebVideoFrame* m_frame; - GC3Denum m_format; - CCResourceProvider::ResourceId m_externalTextureResource; - - // Each index in this array corresponds to a plane in WebKit::WebVideoFrame. - FramePlane m_framePlanes[WebKit::WebVideoFrame::maxPlanes]; -}; - -} - -#endif // CCVideoLayerImpl_h diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCYUVVideoDrawQuad.cpp b/Source/WebCore/platform/graphics/chromium/cc/CCYUVVideoDrawQuad.cpp deleted file mode 100644 index 035d6a1ba..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCYUVVideoDrawQuad.cpp +++ /dev/null @@ -1,51 +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 "CCYUVVideoDrawQuad.h" - -namespace WebCore { - -PassOwnPtr<CCYUVVideoDrawQuad> CCYUVVideoDrawQuad::create(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, const CCVideoLayerImpl::FramePlane& yPlane, const CCVideoLayerImpl::FramePlane& uPlane, const CCVideoLayerImpl::FramePlane& vPlane) -{ - return adoptPtr(new CCYUVVideoDrawQuad(sharedQuadState, quadRect, yPlane, uPlane, vPlane)); -} - -CCYUVVideoDrawQuad::CCYUVVideoDrawQuad(const CCSharedQuadState* sharedQuadState, const IntRect& quadRect, const CCVideoLayerImpl::FramePlane& yPlane, const CCVideoLayerImpl::FramePlane& uPlane, const CCVideoLayerImpl::FramePlane& vPlane) - : CCDrawQuad(sharedQuadState, CCDrawQuad::YUVVideoContent, quadRect) - , m_yPlane(yPlane) - , m_uPlane(uPlane) - , m_vPlane(vPlane) -{ -} - -const CCYUVVideoDrawQuad* CCYUVVideoDrawQuad::materialCast(const CCDrawQuad* quad) -{ - ASSERT(quad->material() == CCDrawQuad::YUVVideoContent); - return static_cast<const CCYUVVideoDrawQuad*>(quad); -} - -} diff --git a/Source/WebCore/platform/graphics/chromium/cc/CCYUVVideoDrawQuad.h b/Source/WebCore/platform/graphics/chromium/cc/CCYUVVideoDrawQuad.h deleted file mode 100644 index b564e9f1e..000000000 --- a/Source/WebCore/platform/graphics/chromium/cc/CCYUVVideoDrawQuad.h +++ /dev/null @@ -1,55 +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 CCYUVVideoDrawQuad_h -#define CCYUVVideoDrawQuad_h - -#include "CCDrawQuad.h" -#include "CCVideoLayerImpl.h" -#include <wtf/PassOwnPtr.h> - -namespace WebCore { - -class CCYUVVideoDrawQuad : public CCDrawQuad { - WTF_MAKE_NONCOPYABLE(CCYUVVideoDrawQuad); -public: - static PassOwnPtr<CCYUVVideoDrawQuad> create(const CCSharedQuadState*, const IntRect&, const CCVideoLayerImpl::FramePlane& yPlane, const CCVideoLayerImpl::FramePlane& uPlane, const CCVideoLayerImpl::FramePlane& vPlane); - - const CCVideoLayerImpl::FramePlane& yPlane() const { return m_yPlane; } - const CCVideoLayerImpl::FramePlane& uPlane() const { return m_uPlane; } - const CCVideoLayerImpl::FramePlane& vPlane() const { return m_vPlane; } - - static const CCYUVVideoDrawQuad* materialCast(const CCDrawQuad*); -private: - CCYUVVideoDrawQuad(const CCSharedQuadState*, const IntRect&, const CCVideoLayerImpl::FramePlane& yPlane, const CCVideoLayerImpl::FramePlane& uPlane, const CCVideoLayerImpl::FramePlane& vPlane); - - CCVideoLayerImpl::FramePlane m_yPlane; - CCVideoLayerImpl::FramePlane m_uPlane; - CCVideoLayerImpl::FramePlane m_vPlane; -}; - -} - -#endif diff --git a/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp b/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp index c1102e7fa..2d9e86a35 100644 --- a/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp +++ b/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp @@ -31,6 +31,7 @@ #include "config.h" #include "FontPlatformDataHarfBuzz.h" +#include "FontCache.h" #include "NotImplemented.h" #include "SkAdvancedTypefaceMetrics.h" #include "SkFontHost.h" @@ -341,4 +342,34 @@ void FontPlatformData::querySystemForRenderStyle() m_style.useSubpixelRendering = useSkiaSubpixelRendering; } +#if ENABLE(OPENTYPE_VERTICAL) +static SkFontTableTag reverseByteOrder(uint32_t tableTag) +{ + return (tableTag >> 24) | ((tableTag >> 8) & 0xff00) | ((tableTag & 0xff00) << 8) | ((tableTag & 0xff) << 24); +} + +const OpenTypeVerticalData* FontPlatformData::verticalData() const +{ + if (!uniqueID()) + return 0; + return fontCache()->getVerticalData(uniqueID(), *this); +} + +PassRefPtr<SharedBuffer> FontPlatformData::openTypeTable(uint32_t table) const +{ + RefPtr<SharedBuffer> buffer; + if (!uniqueID()) + return buffer.release(); + + SkFontTableTag tag = reverseByteOrder(table); + const size_t tableSize = SkFontHost::GetTableSize(uniqueID(), tag); + if (tableSize) { + Vector<char> tableBuffer(tableSize); + SkFontHost::GetTableData(uniqueID(), tag, 0, tableSize, &tableBuffer[0]); + buffer = SharedBuffer::adoptVector(tableBuffer); + } + return buffer.release(); +} +#endif + } // namespace WebCore diff --git a/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h b/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h index d4a01f810..f176f7131 100644 --- a/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h +++ b/Source/WebCore/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h @@ -33,6 +33,7 @@ #include "FontOrientation.h" #include "FontRenderStyle.h" +#include "SharedBuffer.h" #include "SkPaint.h" #include "TextOrientation.h" #include <wtf/Forward.h> @@ -46,6 +47,7 @@ typedef uint32_t SkFontID; namespace WebCore { class FontDescription; +class OpenTypeVerticalData; #if USE(HARFBUZZ_NG) class HarfBuzzNGFace; @@ -102,6 +104,11 @@ public: FontPlatformData& operator=(const FontPlatformData&); bool isHashTableDeletedValue() const { return m_typeface == hashTableDeletedFontValue(); } +#if ENABLE(OPENTYPE_VERTICAL) + const OpenTypeVerticalData* verticalData() const; + PassRefPtr<SharedBuffer> openTypeTable(uint32_t table) const; +#endif + #ifndef NDEBUG String description() const; #endif diff --git a/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.cpp b/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.cpp index 9d65f0fda..9e55fc411 100644 --- a/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.cpp +++ b/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.cpp @@ -86,30 +86,11 @@ void HarfBuzzShaper::HarfBuzzRun::applyShapeResult(hb_buffer_t* harfbuzzBuffer) m_glyphs.resize(m_numGlyphs); m_advances.resize(m_numGlyphs); m_glyphToCharacterIndexes.resize(m_numGlyphs); - m_logClusters.resize(m_numCharacters); m_offsets.resize(m_numGlyphs); hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(harfbuzzBuffer, 0); for (unsigned i = 0; i < m_numGlyphs; ++i) m_glyphToCharacterIndexes[i] = infos[i].cluster; - - // Fill logical clusters - unsigned index = 0; - while (index < m_numGlyphs) { - unsigned nextIndex = index + 1; - while (nextIndex < m_numGlyphs && infos[index].cluster == infos[nextIndex].cluster) - ++nextIndex; - if (rtl()) { - int nextCluster = nextIndex < m_numGlyphs ? infos[nextIndex].cluster : -1; - for (int j = infos[index].cluster; j > nextCluster; --j) - m_logClusters[j] = index; - } else { - unsigned nextCluster = nextIndex < m_numGlyphs ? infos[nextIndex].cluster : m_numCharacters; - for (unsigned j = infos[index].cluster; j < nextCluster; ++j) - m_logClusters[j] = index; - } - index = nextIndex; - } } void HarfBuzzShaper::HarfBuzzRun::setGlyphAndPositions(unsigned index, uint16_t glyphId, float advance, float offsetX, float offsetY) @@ -123,14 +104,30 @@ int HarfBuzzShaper::HarfBuzzRun::characterIndexForXPosition(float targetX) { ASSERT(targetX <= m_width); float currentX = 0; - float prevAdvance = 0; - for (unsigned i = 0; i < m_numGlyphs; ++i) { - float currentAdvance = m_advances[i] / 2.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 m_glyphToCharacterIndexes[i] + (rtl() ? 1 : 0); + return rtl() ? prevCharacterIndex : m_glyphToCharacterIndexes[glyphIndex]; currentX = nextX; prevAdvance = currentAdvance; + ++glyphIndex; } return rtl() ? 0 : m_numCharacters; @@ -139,13 +136,26 @@ int HarfBuzzShaper::HarfBuzzRun::characterIndexForXPosition(float targetX) float HarfBuzzShaper::HarfBuzzRun::xPositionForOffset(unsigned offset) { ASSERT(offset < m_numCharacters); - unsigned glyphIndex = m_logClusters[offset]; - ASSERT(glyphIndex <= m_numGlyphs); + unsigned glyphIndex = 0; float position = 0; - for (unsigned i = 0; i < glyphIndex; ++i) - position += m_advances[i]; - if (rtl()) + 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; } @@ -157,7 +167,7 @@ static void normalizeCharacters(const UChar* source, UChar* destination, int len UChar32 character; int nextPosition = position; U16_NEXT(source, nextPosition, length, character); - // Don't normalize tabs as they are not treated as spaces for word-end + // 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)) diff --git a/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.h b/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.h index 946d0c089..c88ef2465 100644 --- a/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.h +++ b/Source/WebCore/platform/graphics/harfbuzz/ng/HarfBuzzShaper.h @@ -94,7 +94,6 @@ private: TextDirection m_direction; Vector<uint16_t, 256> m_glyphs; Vector<float, 256> m_advances; - Vector<uint16_t, 256> m_logClusters; Vector<uint16_t, 256> m_glyphToCharacterIndexes; Vector<FloatPoint, 256> m_offsets; float m_width; diff --git a/Source/WebCore/platform/graphics/mac/ComplexTextController.cpp b/Source/WebCore/platform/graphics/mac/ComplexTextController.cpp index 7188c88d7..edc74fbb5 100644 --- a/Source/WebCore/platform/graphics/mac/ComplexTextController.cpp +++ b/Source/WebCore/platform/graphics/mac/ComplexTextController.cpp @@ -48,7 +48,7 @@ public: } TextLayout(RenderText* text, const Font& font, float xPos) - : m_font(fontWithNoWordSpacing(font)) + : m_font(font) , m_run(constructTextRun(text, font, xPos)) , m_controller(adoptPtr(new ComplexTextController(&m_font, m_run, true))) { @@ -58,19 +58,14 @@ public: { m_controller->advance(from, 0, ByWholeGlyphs); 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); float afterWidth = m_controller->runWidthSoFar(); return afterWidth - beforeWidth; } private: - static Font fontWithNoWordSpacing(const Font& originalFont) - { - Font font(originalFont); - font.setWordSpacing(0); - return font; - } - static TextRun constructTextRun(RenderText* text, const Font& font, float xPos) { TextRun run = RenderBlock::constructTextRun(text, font, text->characters(), text->textLength(), text->style()); @@ -580,8 +575,14 @@ void ComplexTextController::adjustGlyphsAndAdvances() 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]; + CGGlyph glyph = glyphs[i]; + CGSize advance = advances[i]; + // FIXME: We should find a way to substitute spaces for characters that are treated as spaces + // before handing them off to Core Text, so that kerning can be applied as if they were spaces. + if (treatAsSpace && ch != ' ') { + glyph = fontData->spaceGlyph(); + advance.width = spaceWidth; + } if (ch == '\t' && m_run.allowTabs()) advance.width = m_font.tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_totalWidth + widthSinceLastCommit); diff --git a/Source/WebCore/platform/graphics/mac/FontCacheMac.mm b/Source/WebCore/platform/graphics/mac/FontCacheMac.mm index 6b2e05474..9b2555823 100644 --- a/Source/WebCore/platform/graphics/mac/FontCacheMac.mm +++ b/Source/WebCore/platform/graphics/mac/FontCacheMac.mm @@ -115,6 +115,12 @@ const SimpleFontData* FontCache::getFontDataForCharacters(const Font& font, cons if (!substituteFont) return 0; +#if PLATFORM(CHROMIUM) + // Chromium can't render AppleColorEmoji. + if ([[substituteFont familyName] isEqual:@"Apple Color Emoji"]) + return 0; +#endif + // 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. diff --git a/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp b/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp deleted file mode 100644 index 56139a498..000000000 --- a/Source/WebCore/platform/graphics/skia/BitLockerSkia.cpp +++ /dev/null @@ -1,119 +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 "BitLockerSkia.h" - -#include "IntRect.h" - -#include "SkCanvas.h" -#include "SkDevice.h" -#include "SkRegion.h" - -#include <CoreGraphics/CoreGraphics.h> - -namespace WebCore { - -static CGAffineTransform SkMatrixToCGAffineTransform(const SkMatrix& matrix) -{ - // CGAffineTransforms don't support perspective transforms, so make sure - // we don't get those. - ASSERT(!matrix[SkMatrix::kMPersp0]); - ASSERT(!matrix[SkMatrix::kMPersp1]); - ASSERT(matrix[SkMatrix::kMPersp2] == 1.0f); - - return CGAffineTransformMake( - matrix[SkMatrix::kMScaleX], - matrix[SkMatrix::kMSkewY], - matrix[SkMatrix::kMSkewX], - matrix[SkMatrix::kMScaleY], - matrix[SkMatrix::kMTransX], - matrix[SkMatrix::kMTransY]); -} - -BitLockerSkia::BitLockerSkia(SkCanvas* canvas) - : m_canvas(canvas) - , m_cgContext(0) -{ -} - -BitLockerSkia::~BitLockerSkia() -{ - releaseIfNeeded(); -} - -void BitLockerSkia::releaseIfNeeded() -{ - if (!m_cgContext) - return; - m_canvas->getDevice()->accessBitmap(true).unlockPixels(); - CGContextRelease(m_cgContext); - m_cgContext = 0; -} - -CGContextRef BitLockerSkia::cgContext() -{ - SkDevice* device = m_canvas->getDevice(); - ASSERT(device); - if (!device) - return 0; - releaseIfNeeded(); - const SkBitmap& bitmap = device->accessBitmap(true); - bitmap.lockPixels(); - void* pixels = bitmap.getPixels(); - m_cgContext = CGBitmapContextCreate(pixels, device->width(), - device->height(), 8, bitmap.rowBytes(), CGColorSpaceCreateDeviceRGB(), - kCGBitmapByteOrder32Host | kCGImageAlphaPremultipliedFirst); - - // Apply device matrix. - CGAffineTransform contentsTransform = CGAffineTransformMakeScale(1, -1); - contentsTransform = CGAffineTransformTranslate(contentsTransform, 0, -device->height()); - CGContextConcatCTM(m_cgContext, contentsTransform); - - // Apply clip in device coordinates. - CGMutablePathRef clipPath = CGPathCreateMutable(); - SkRegion::Iterator iter(m_canvas->getTotalClip()); - for (; !iter.done(); iter.next()) { - IntRect rect = iter.rect(); - CGPathAddRect(clipPath, 0, rect); - } - CGContextAddPath(m_cgContext, clipPath); - CGContextClip(m_cgContext); - CGPathRelease(clipPath); - - // Apply content matrix. - const SkMatrix& skMatrix = m_canvas->getTotalMatrix(); - CGAffineTransform affine = SkMatrixToCGAffineTransform(skMatrix); - CGContextConcatCTM(m_cgContext, affine); - - return m_cgContext; -} - -} diff --git a/Source/WebCore/platform/graphics/skia/BitLockerSkia.h b/Source/WebCore/platform/graphics/skia/BitLockerSkia.h deleted file mode 100644 index c83c20d3b..000000000 --- a/Source/WebCore/platform/graphics/skia/BitLockerSkia.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 BitLockerSkia_h -#define BitLockerSkia_h - -typedef struct CGContext* CGContextRef; - -class SkCanvas; - -namespace WebCore { - -// Converts a SkCanvas temporarily to a CGContext -class BitLockerSkia { -public: - explicit BitLockerSkia(SkCanvas*); - ~BitLockerSkia(); - CGContextRef cgContext(); - -private: - void releaseIfNeeded(); - SkCanvas* m_canvas; - CGContextRef m_cgContext; -}; - -} -#endif // BitLockerSkia_h diff --git a/Source/WebCore/platform/graphics/skia/FontCacheSkia.cpp b/Source/WebCore/platform/graphics/skia/FontCacheSkia.cpp index 2a8d3988f..271c3d7e9 100644 --- a/Source/WebCore/platform/graphics/skia/FontCacheSkia.cpp +++ b/Source/WebCore/platform/graphics/skia/FontCacheSkia.cpp @@ -33,6 +33,7 @@ #include "Font.h" #include "FontDescription.h" +#include "FontFamily.h" #include "FontPlatformData.h" #include "Logging.h" #include "NotImplemented.h" @@ -59,8 +60,8 @@ const SimpleFontData* FontCache::getFontDataForCharacters(const Font& font, int length) { icu::Locale locale = icu::Locale::getDefault(); - PlatformSupport::FontFamily family; - PlatformSupport::getFontFamilyForCharacters(characters, length, locale.getLanguage(), &family); + FontCache::SimpleFontFamily family; + FontCache::getFontFamilyForCharacters(characters, length, locale.getLanguage(), &family); if (family.name.isEmpty()) return 0; diff --git a/Source/WebCore/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp b/Source/WebCore/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp index d18e53ed9..6024d43df 100644 --- a/Source/WebCore/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp +++ b/Source/WebCore/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp @@ -32,60 +32,14 @@ #include "GlyphPageTreeNode.h" #include "Font.h" -#if !USE(HARFBUZZ_NG) -#include "HarfBuzzSkia.h" -#else -#include "NotImplemented.h" -#endif #include "SimpleFontData.h" #include "SkTemplates.h" #include "SkPaint.h" #include "SkUtils.h" -#if !USE(HARFBUZZ_NG) -extern "C" { -#include "harfbuzz-shaper.h" -} -#endif - namespace WebCore { -static int substituteWithVerticalGlyphs(const SimpleFontData* fontData, uint16_t* glyphs, unsigned bufferLength) -{ -#if USE(HARFBUZZ_NG) - notImplemented(); - return 0xFFFF; -#else - HB_FaceRec_* hbFace = fontData->platformData().harfbuzzFace()->face(); - if (!hbFace->gsub) { - // if there is no GSUB table, treat it as not covered - return 0Xffff; - } - - HB_Buffer buffer; - hb_buffer_new(&buffer); - for (unsigned i = 0; i < bufferLength; ++i) - hb_buffer_add_glyph(buffer, glyphs[i], 0, i); - - HB_UShort scriptIndex; - HB_UShort featureIndex; - - HB_GSUB_Select_Script(hbFace->gsub, HB_MAKE_TAG('D', 'F', 'L', 'T'), &scriptIndex); - HB_GSUB_Select_Feature(hbFace->gsub, HB_MAKE_TAG('v', 'e', 'r', 't'), scriptIndex, 0xffff, &featureIndex); - HB_GSUB_Add_Feature(hbFace->gsub, featureIndex, 1); - HB_GSUB_Select_Feature(hbFace->gsub, HB_MAKE_TAG('v', 'r', 't', '2'), scriptIndex, 0xffff, &featureIndex); - HB_GSUB_Add_Feature(hbFace->gsub, featureIndex, 1); - - int error = HB_GSUB_Apply_String(hbFace->gsub, buffer); - if (!error) { - for (unsigned i = 0; i < bufferLength; ++i) - glyphs[i] = static_cast<Glyph>(buffer->out_string[i].gindex); - } - return error; -#endif -} - bool GlyphPage::fill(unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData) { if (SkUTF16_IsHighSurrogate(buffer[bufferLength-1])) { @@ -106,15 +60,6 @@ bool GlyphPage::fill(unsigned offset, unsigned length, UChar* buffer, unsigned b return false; } - if (fontData->hasVerticalGlyphs()) { - for (unsigned i = 0; i < bufferLength; ++i) { - if (!Font::isCJKIdeograph(buffer[i])) { - substituteWithVerticalGlyphs(fontData, glyphs, length); - break; - } - } - } - 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); diff --git a/Source/WebCore/platform/image-decoders/ImageDecoder.h b/Source/WebCore/platform/image-decoders/ImageDecoder.h index ea6495fee..303d7599a 100644 --- a/Source/WebCore/platform/image-decoders/ImageDecoder.h +++ b/Source/WebCore/platform/image-decoders/ImageDecoder.h @@ -289,14 +289,14 @@ namespace WebCore { static bool rgbColorProfile(const char* profileData, unsigned profileLength) { - ASSERT(profileLength >= iccColorProfileHeaderLength); + ASSERT_UNUSED(profileLength, profileLength >= iccColorProfileHeaderLength); return !memcmp(&profileData[16], "RGB ", 4); } static bool inputDeviceColorProfile(const char* profileData, unsigned profileLength) { - ASSERT(profileLength >= iccColorProfileHeaderLength); + ASSERT_UNUSED(profileLength, profileLength >= iccColorProfileHeaderLength); return !memcmp(&profileData[12], "mntr", 4) || !memcmp(&profileData[12], "scnr", 4); } diff --git a/Source/WebCore/platform/network/blackberry/NetworkJob.cpp b/Source/WebCore/platform/network/blackberry/NetworkJob.cpp index 98ebe6059..cca89b520 100644 --- a/Source/WebCore/platform/network/blackberry/NetworkJob.cpp +++ b/Source/WebCore/platform/network/blackberry/NetworkJob.cpp @@ -19,6 +19,7 @@ #include "config.h" #include "NetworkJob.h" +#include "AuthenticationChallengeManager.h" #include "Chrome.h" #include "ChromeClient.h" #include "CookieManager.h" @@ -84,9 +85,16 @@ NetworkJob::NetworkJob() , m_deferredData(*this) , m_deferLoadingCount(0) , m_frame(0) + , m_isAuthenticationChallenging(false) { } +NetworkJob::~NetworkJob() +{ + if (m_isAuthenticationChallenging) + AuthenticationChallengeManager::instance()->cancelAuthenticationChallenge(this); +} + bool NetworkJob::initialize(int playerId, const String& pageGroupName, const KURL& url, @@ -203,10 +211,8 @@ void NetworkJob::handleNotifyStatusReceived(int status, const String& message) m_response.setHTTPStatusText(message); - if (isUnauthorized(m_extendedStatusCode)) { + if (isUnauthorized(m_extendedStatusCode)) purgeCredentials(); - BlackBerry::Platform::log(BlackBerry::Platform::LogLevelCritical, "Authentication failed, purge the stored credentials for this site."); - } } void NetworkJob::notifyHeadersReceived(BlackBerry::Platform::NetworkRequest::HeaderList& headers) @@ -484,6 +490,7 @@ void NetworkJob::handleNotifyClose(int status) #ifndef NDEBUG m_isRunning = false; #endif + if (!m_cancelled) { if (!m_statusReceived) { // Connection failed before sending notifyStatusReceived: use generic NetworkError. @@ -495,6 +502,7 @@ void NetworkJob::handleNotifyClose(int status) m_extendedStatusCode = BlackBerry::Platform::FilterStream::StatusTooManyRedirects; sendResponseIfNeeded(); + if (isClientAvailable()) { if (isError(status)) m_extendedStatusCode = status; @@ -767,7 +775,15 @@ bool NetworkJob::sendRequestWithCredentials(ProtectionSpaceServerType type, Prot return false; m_handle->getInternal()->m_currentWebChallenge = AuthenticationChallenge(); - m_frame->page()->chrome()->client()->platformPageClient()->authenticationChallenge(newURL, protectionSpace, Credential(), this); + + m_isAuthenticationChallenging = true; + updateDeferLoadingCount(1); + + AuthenticationChallengeManager::instance()->authenticationChallenge(newURL, + protectionSpace, + Credential(), + this, + m_frame->page()->chrome()->client()->platformPageClient()); return true; } @@ -828,11 +844,17 @@ void NetworkJob::fireDeleteJobTimer(Timer<NetworkJob>*) void NetworkJob::notifyChallengeResult(const KURL& url, const ProtectionSpace& protectionSpace, AuthenticationChallengeResult result, const Credential& credential) { + m_isAuthenticationChallenging = false; + if (result != AuthenticationChallengeSuccess || protectionSpace.host().isEmpty() || !url.isValid()) { m_newJobWithCredentialsStarted = false; + updateDeferLoadingCount(-1); return; } + cancelJob(); + updateDeferLoadingCount(-1); + if (m_handle->getInternal()->m_currentWebChallenge.isNull()) m_handle->getInternal()->m_currentWebChallenge = AuthenticationChallenge(protectionSpace, credential, 0, m_response, ResourceError()); diff --git a/Source/WebCore/platform/network/blackberry/NetworkJob.h b/Source/WebCore/platform/network/blackberry/NetworkJob.h index 3526374ab..8bfb46708 100644 --- a/Source/WebCore/platform/network/blackberry/NetworkJob.h +++ b/Source/WebCore/platform/network/blackberry/NetworkJob.h @@ -29,6 +29,7 @@ #include <network/FilterStream.h> #include <wtf/OwnPtr.h> #include <wtf/RefPtr.h> +#include <wtf/Vector.h> #include <wtf/text/WTFString.h> namespace BlackBerry { @@ -49,6 +50,8 @@ class ResourceRequest; class NetworkJob : public AuthenticationChallengeClient, public BlackBerry::Platform::FilterStream { public: NetworkJob(); + ~NetworkJob(); + bool initialize(int playerId, const String& pageGroupName, const KURL&, @@ -171,6 +174,8 @@ private: DeferredData m_deferredData; int m_deferLoadingCount; const Frame* m_frame; + + bool m_isAuthenticationChallenging; }; } // namespace WebCore diff --git a/Source/WebCore/platform/text/LocaleICU.cpp b/Source/WebCore/platform/text/LocaleICU.cpp index a2e15f7e1..ae9d1cbd1 100644 --- a/Source/WebCore/platform/text/LocaleICU.cpp +++ b/Source/WebCore/platform/text/LocaleICU.cpp @@ -68,6 +68,10 @@ LocaleICU::~LocaleICU() { unum_close(m_numberFormat); udat_close(m_shortDateFormat); +#if ENABLE(INPUT_TYPE_TIME_MULTIPLE_FIELDS) + udat_close(m_mediumTimeFormat); + udat_close(m_shortTimeFormat); +#endif } PassOwnPtr<LocaleICU> LocaleICU::create(const char* localeString) diff --git a/Source/WebCore/platform/text/LocalizedDate.h b/Source/WebCore/platform/text/LocalizedDate.h index 74422afb8..7449e5b1d 100644 --- a/Source/WebCore/platform/text/LocalizedDate.h +++ b/Source/WebCore/platform/text/LocalizedDate.h @@ -62,20 +62,6 @@ const Vector<String>& weekDayShortLabels(); unsigned firstDayOfWeek(); #endif -#if ENABLE(INPUT_TYPE_TIME_MULTIPLE_FIELDS) -// 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/tr35-6.html#Date_Format_Patterns -String localizedTimeFormatText(); - -// 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 localizedTimeFormatText(). -String localizedShortTimeFormatText(); - -// Returns localized period field(AM/PM) strings. -const Vector<String>& timeAMPMLabels(); -#endif } // namespace WebCore #endif // LocalizedDate_h diff --git a/Source/WebCore/platform/text/LocalizedDateICU.cpp b/Source/WebCore/platform/text/LocalizedDateICU.cpp index 96f362dde..10cb6f132 100644 --- a/Source/WebCore/platform/text/LocalizedDateICU.cpp +++ b/Source/WebCore/platform/text/LocalizedDateICU.cpp @@ -92,21 +92,4 @@ unsigned firstDayOfWeek() } #endif -#if ENABLE(INPUT_TYPE_TIME_MULTIPLE_FIELDS) -String localizedTimeFormatText() -{ - return LocaleICU::currentLocale()->timeFormat(); -} - -String localizedShortTimeFormatText() -{ - return LocaleICU::currentLocale()->shortTimeFormat(); -} - -const Vector<String>& timeAMPMLabels() -{ - return LocaleICU::currentLocale()->timeAMPMLabels(); -} -#endif - } diff --git a/Source/WebCore/platform/text/LocalizedDateWin.cpp b/Source/WebCore/platform/text/LocalizedDateWin.cpp index 6d8429cc2..bd8f367f3 100644 --- a/Source/WebCore/platform/text/LocalizedDateWin.cpp +++ b/Source/WebCore/platform/text/LocalizedDateWin.cpp @@ -92,21 +92,4 @@ unsigned firstDayOfWeek() } #endif -#if ENABLE(INPUT_TYPE_TIME_MULTIPLE_FIELDS) -String localizedTimeFormatText() -{ - return LocaleWin::currentLocale()->timeFormat(); -} - -String localizedShortTimeFormatText() -{ - return LocaleWin::currentLocale()->shortTimeFormat(); -} - -const Vector<String>& timeAMPMLabels() -{ - return LocaleWin::currentLocale()->timeAMPMLabels(); -} -#endif - } diff --git a/Source/WebCore/platform/text/Localizer.h b/Source/WebCore/platform/text/Localizer.h index a33b22268..e56fc40c9 100644 --- a/Source/WebCore/platform/text/Localizer.h +++ b/Source/WebCore/platform/text/Localizer.h @@ -37,8 +37,18 @@ public: String convertFromLocalizedNumber(const String&); #if ENABLE(INPUT_TYPE_TIME_MULTIPLE_FIELDS) String localizedDecimalSeparator(); + + // 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/tr35-6.html#Date_Format_Patterns virtual String timeFormat(); + + // 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(); + + // Returns localized period field(AM/PM) strings. virtual const Vector<String>& timeAMPMLabels(); #endif virtual ~Localizer(); diff --git a/Source/WebCore/platform/text/TextStream.cpp b/Source/WebCore/platform/text/TextStream.cpp index 5826f9f89..570f6ae50 100644 --- a/Source/WebCore/platform/text/TextStream.cpp +++ b/Source/WebCore/platform/text/TextStream.cpp @@ -87,13 +87,13 @@ TextStream& TextStream::operator<<(unsigned long long i) TextStream& TextStream::operator<<(float f) { - m_text.append(String::number(f, ShouldRoundDecimalPlaces, 2)); + m_text.append(String::numberToStringFixedWidth(f, 2)); return *this; } TextStream& TextStream::operator<<(double d) { - m_text.append(String::number(d, ShouldRoundDecimalPlaces, 2)); + m_text.append(String::numberToStringFixedWidth(d, 2)); return *this; } diff --git a/Source/WebCore/platform/text/gtk/TextBreakIteratorGtk.cpp b/Source/WebCore/platform/text/gtk/TextBreakIteratorGtk.cpp index 733d75982..b33255da5 100644 --- a/Source/WebCore/platform/text/gtk/TextBreakIteratorGtk.cpp +++ b/Source/WebCore/platform/text/gtk/TextBreakIteratorGtk.cpp @@ -233,7 +233,7 @@ NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(const UChar* bu NonSharedCharacterBreakIterator::~NonSharedCharacterBreakIterator() { if (!weakCompareAndSwap(reinterpret_cast<void**>(&nonSharedCharacterBreakIterator), 0, m_iterator)) - ubrk_close(m_iterator); + delete m_iterator; } TextBreakIterator* cursorMovementIterator(const UChar* string, int length) diff --git a/Source/WebCore/platform/text/mac/LocalizedDateMac.cpp b/Source/WebCore/platform/text/mac/LocalizedDateMac.cpp index 8a9db1493..e67c93817 100644 --- a/Source/WebCore/platform/text/mac/LocalizedDateMac.cpp +++ b/Source/WebCore/platform/text/mac/LocalizedDateMac.cpp @@ -92,21 +92,4 @@ unsigned firstDayOfWeek() } #endif -#if ENABLE(INPUT_TYPE_TIME_MULTIPLE_FIELDS) -String localizedTimeFormatText() -{ - return LocaleMac::currentLocale()->timeFormat(); -} - -String localizedShortTimeFormatText() -{ - return LocaleMac::currentLocale()->shortTimeFormat(); -} - -const Vector<String>& timeAMPMLabels() -{ - return LocaleMac::currentLocale()->timeAMPMLabels(); -} -#endif - } diff --git a/Source/WebCore/rendering/FilterEffectRenderer.h b/Source/WebCore/rendering/FilterEffectRenderer.h index bc53cdc14..4304e1671 100644 --- a/Source/WebCore/rendering/FilterEffectRenderer.h +++ b/Source/WebCore/rendering/FilterEffectRenderer.h @@ -113,7 +113,7 @@ public: bool hasFilterThatMovesPixels() const { return m_hasFilterThatMovesPixels; } LayoutRect computeSourceImageRectForDirtyRect(const LayoutRect& filterBoxRect, const LayoutRect& dirtyRect); -#if ENABLE(CSS_SHADERS) && ENABLE(WEBGL) +#if ENABLE(CSS_SHADERS) bool hasCustomShaderFilter() const { return m_hasCustomShaderFilter; } #endif private: diff --git a/Source/WebCore/rendering/InlineBox.h b/Source/WebCore/rendering/InlineBox.h index d8f7e3c17..a6b94debb 100644 --- a/Source/WebCore/rendering/InlineBox.h +++ b/Source/WebCore/rendering/InlineBox.h @@ -262,7 +262,7 @@ public: virtual void clearTruncation() { } bool isDirty() const { return m_bitfields.dirty(); } - void markDirty(bool dirty = true) { m_bitfields.setDirty(dirty); } + virtual void markDirty(bool dirty = true) { m_bitfields.setDirty(dirty); } virtual void dirtyLineBoxes(); diff --git a/Source/WebCore/rendering/InlineTextBox.cpp b/Source/WebCore/rendering/InlineTextBox.cpp index 5bc3b7652..95a6f0239 100644 --- a/Source/WebCore/rendering/InlineTextBox.cpp +++ b/Source/WebCore/rendering/InlineTextBox.cpp @@ -64,6 +64,15 @@ void InlineTextBox::destroy(RenderArena* arena) InlineBox::destroy(arena); } +void InlineTextBox::markDirty(bool dirty) +{ + if (dirty) { + m_len = 0; + m_start = 0; + } + InlineBox::markDirty(dirty); +} + LayoutRect InlineTextBox::logicalOverflowRect() const { if (knownToHaveNoOverflow() || !gTextBoxesWithOverflow) diff --git a/Source/WebCore/rendering/InlineTextBox.h b/Source/WebCore/rendering/InlineTextBox.h index 06ba040fc..9a8451578 100644 --- a/Source/WebCore/rendering/InlineTextBox.h +++ b/Source/WebCore/rendering/InlineTextBox.h @@ -64,6 +64,7 @@ public: void setNextTextBox(InlineTextBox* n) { m_nextTextBox = n; } void setPreviousTextBox(InlineTextBox* p) { m_prevTextBox = p; } + // FIXME: These accessors should ASSERT(!isDirty()). See https://bugs.webkit.org/show_bug.cgi?id=97264 unsigned start() const { return m_start; } unsigned end() const { return m_len ? m_start + m_len - 1 : m_start; } unsigned len() const { return m_len; } @@ -71,10 +72,12 @@ public: void setStart(unsigned start) { m_start = start; } void setLen(unsigned len) { m_len = len; } - void offsetRun(int d) { m_start += d; } + void offsetRun(int d) { ASSERT(!isDirty()); m_start += d; } unsigned short truncation() { return m_truncation; } + virtual void markDirty(bool dirty = true) OVERRIDE; + using InlineBox::hasHyphen; using InlineBox::setHasHyphen; using InlineBox::canHaveLeadingExpansion; diff --git a/Source/WebCore/rendering/RenderBlockLineLayout.cpp b/Source/WebCore/rendering/RenderBlockLineLayout.cpp index cbcc988aa..bfe03b804 100755 --- a/Source/WebCore/rendering/RenderBlockLineLayout.cpp +++ b/Source/WebCore/rendering/RenderBlockLineLayout.cpp @@ -2414,10 +2414,6 @@ InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resol float wordSpacing = currentStyle->wordSpacing(); float lastSpaceWordSpacing = 0; - // 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(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0; - float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true); float charWidth = 0; bool breakNBSP = autoWrap && currentStyle->nbspMode() == SPACE; @@ -2447,6 +2443,10 @@ InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resol 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(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0; + for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) { bool previousCharacterIsSpace = currentCharacterIsSpace; bool previousCharacterIsWS = currentCharacterIsWS; diff --git a/Source/WebCore/rendering/RenderBox.h b/Source/WebCore/rendering/RenderBox.h index 8b580e112..db274fb84 100644 --- a/Source/WebCore/rendering/RenderBox.h +++ b/Source/WebCore/rendering/RenderBox.h @@ -366,7 +366,7 @@ public: virtual void updateLogicalWidth(); virtual void updateLogicalHeight(); - void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const; + virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const; RenderBoxRegionInfo* renderBoxRegionInfo(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage, RenderBoxRegionInfoFlags = CacheRenderBoxRegionInfo) const; void computeLogicalWidthInRegion(LogicalExtentComputedValues&, RenderRegion* = 0, LayoutUnit offsetFromLogicalTopOfFirstPage = ZERO_LAYOUT_UNIT) const; diff --git a/Source/WebCore/rendering/RenderButton.cpp b/Source/WebCore/rendering/RenderButton.cpp index c59c82216..7103e6e50 100644 --- a/Source/WebCore/rendering/RenderButton.cpp +++ b/Source/WebCore/rendering/RenderButton.cpp @@ -35,6 +35,7 @@ using namespace HTMLNames; RenderButton::RenderButton(Node* node) : RenderDeprecatedFlexibleBox(node) + , m_buttonText(0) , m_inner(0) , m_default(false) { @@ -82,6 +83,8 @@ void RenderButton::styleDidChange(StyleDifference diff, const RenderStyle* oldSt { RenderBlock::styleDidChange(diff, oldStyle); + if (m_buttonText) + m_buttonText->setStyle(style()); if (m_inner) // RenderBlock handled updating the anonymous block's style. setupInnerStyle(m_inner->style()); @@ -105,6 +108,39 @@ void RenderButton::setupInnerStyle(RenderStyle* innerStyle) innerStyle->setBoxOrient(style()->boxOrient()); } +void RenderButton::updateFromElement() +{ + // If we're an input element, we may need to change our button text. + if (node()->hasTagName(inputTag)) { + HTMLInputElement* input = static_cast<HTMLInputElement*>(node()); + String value = input->valueWithDefault(); + setText(value); + } +} + +void RenderButton::setText(const String& str) +{ + if (str.isEmpty()) { + if (m_buttonText) { + m_buttonText->destroy(); + m_buttonText = 0; + } + } else { + if (m_buttonText) + m_buttonText->setText(str.impl()); + else { + m_buttonText = new (renderArena()) RenderTextFragment(document(), str.impl()); + m_buttonText->setStyle(style()); + addChild(m_buttonText); + } + } +} + +String RenderButton::text() const +{ + return m_buttonText ? m_buttonText->text() : 0; +} + bool RenderButton::canHaveGeneratedChildren() const { // Input elements can't have generated children, but button elements can. We'll diff --git a/Source/WebCore/rendering/RenderButton.h b/Source/WebCore/rendering/RenderButton.h index 9dde45392..5be62b012 100644 --- a/Source/WebCore/rendering/RenderButton.h +++ b/Source/WebCore/rendering/RenderButton.h @@ -48,6 +48,7 @@ public: virtual bool createsAnonymousWrapper() const { return true; } void setupInnerStyle(RenderStyle*); + virtual void updateFromElement(); virtual void updateBeforeAfterContent(PseudoId); @@ -55,6 +56,9 @@ public: virtual bool hasControlClip() const { return true; } virtual LayoutRect controlClipRect(const LayoutPoint&) const; + void setText(const String&); + String text() const; + private: virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle); virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle); @@ -65,7 +69,9 @@ private: void timerFired(Timer<RenderButton>*); + RenderTextFragment* m_buttonText; RenderBlock* m_inner; + OwnPtr<Timer<RenderButton> > m_timer; bool m_default; }; diff --git a/Source/WebCore/rendering/RenderLayer.cpp b/Source/WebCore/rendering/RenderLayer.cpp index a49544df1..75986335e 100644 --- a/Source/WebCore/rendering/RenderLayer.cpp +++ b/Source/WebCore/rendering/RenderLayer.cpp @@ -154,6 +154,7 @@ RenderLayer::RenderLayer(RenderBoxModelObject* renderer) , m_indirectCompositingReason(NoIndirectCompositingReason) #endif , m_containsDirtyOverlayScrollbars(false) + , m_updatingMarqueePosition(false) #if !ASSERT_DISABLED , m_layerListMutationAllowed(true) #endif @@ -435,8 +436,13 @@ void RenderLayer::updateLayerPositions(LayoutPoint* offsetFromRoot, UpdateLayerP #endif // With all our children positioned, now update our marquee if we need to. - if (m_marquee) + if (m_marquee) { + // FIXME: would like to use TemporaryChange<> but it doesn't work with bitfields. + bool oldUpdatingMarqueePosition = m_updatingMarqueePosition; + m_updatingMarqueePosition = true; m_marquee->updateMarqueePosition(); + m_updatingMarqueePosition = oldUpdatingMarqueePosition; + } if (offsetFromRoot) *offsetFromRoot = oldOffsetFromRoot; @@ -542,8 +548,12 @@ void RenderLayer::updateLayerPositionsAfterScroll(UpdateLayerPositionsAfterScrol // of an object, thus RenderReplica will still repaint itself properly as the layer position was // updated above. - if (m_marquee) + if (m_marquee) { + bool oldUpdatingMarqueePosition = m_updatingMarqueePosition; + m_updatingMarqueePosition = true; m_marquee->updateMarqueePosition(); + m_updatingMarqueePosition = oldUpdatingMarqueePosition; + } } #if ENABLE(CSS_COMPOSITING) @@ -1717,7 +1727,13 @@ void RenderLayer::scrollTo(int x, int y) view->updateWidgetPositions(); } - updateCompositingLayersAfterScroll(); + if (!m_updatingMarqueePosition) { + // Avoid updating compositing layers if, higher on the stack, we're already updating layer + // positions. Updating layer positions requires a full walk of up-to-date RenderLayers, and + // in this case we're still updating their positions; we'll update compositing layers later + // when that completes. + updateCompositingLayersAfterScroll(); + } RenderBoxModelObject* repaintContainer = renderer()->containerForRepaint(); Frame* frame = renderer()->frame(); @@ -3114,12 +3130,15 @@ void RenderLayer::paintLayerContents(RenderLayer* rootLayer, GraphicsContext* co updateLayerListsIfNeeded(); // Apply clip-path to context. + bool hasClipPath = false; RenderStyle* style = renderer()->style(); if (renderer()->hasClipPath() && !context->paintingDisabled() && style) { ASSERT(style->clipPath()); if (style->clipPath()->getOperationType() == ClipPathOperation::SHAPE) { + hasClipPath = true; + context->save(); ShapeClipPathOperation* clipPath = static_cast<ShapeClipPathOperation*>(style->clipPath()); - transparencyLayerContext->clipPath(clipPath->path(calculateLayerBounds(this, rootLayer, 0)), clipPath->windRule()); + context->clipPath(clipPath->path(calculateLayerBounds(this, rootLayer, 0)), clipPath->windRule()); } } @@ -3289,6 +3308,9 @@ void RenderLayer::paintLayerContents(RenderLayer* rootLayer, GraphicsContext* co context->restore(); m_usedTransparency = false; } + + if (hasClipPath) + context->restore(); } void RenderLayer::paintList(Vector<RenderLayer*>* list, RenderLayer* rootLayer, GraphicsContext* context, diff --git a/Source/WebCore/rendering/RenderLayer.h b/Source/WebCore/rendering/RenderLayer.h index 8e026833d..970b1643e 100644 --- a/Source/WebCore/rendering/RenderLayer.h +++ b/Source/WebCore/rendering/RenderLayer.h @@ -938,6 +938,8 @@ protected: #endif bool m_containsDirtyOverlayScrollbars : 1; + bool m_updatingMarqueePosition : 1; + #if !ASSERT_DISABLED bool m_layerListMutationAllowed : 1; #endif diff --git a/Source/WebCore/rendering/RenderListBox.cpp b/Source/WebCore/rendering/RenderListBox.cpp index 7a2439779..079ce429c 100644 --- a/Source/WebCore/rendering/RenderListBox.cpp +++ b/Source/WebCore/rendering/RenderListBox.cpp @@ -173,6 +173,18 @@ void RenderListBox::selectionChanged() void RenderListBox::layout() { RenderBlock::layout(); + + if (m_vBar) { + bool enabled = numVisibleItems() < numItems(); + m_vBar->setEnabled(enabled); + m_vBar->setSteps(1, max(1, numVisibleItems() - 1), itemHeight()); + m_vBar->setProportion(numVisibleItems(), numItems()); + if (!enabled) { + scrollToOffsetWithoutAnimation(VerticalScrollbar, 0); + m_indexOffset = 0; + } + } + if (m_scrollToRevealSelectionAfterLayout) { LayoutStateDisabler layoutStateDisabler(view()); scrollToRevealSelection(); @@ -250,25 +262,10 @@ LayoutUnit RenderListBox::listHeight() const return itemHeight() * numItems() - rowSpacing; } -void RenderListBox::updateLogicalHeight() +void RenderListBox::computeLogicalHeight(LayoutUnit, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const { - int toAdd = borderAndPaddingHeight(); - - int itemHeight = RenderListBox::itemHeight(); - setHeight(itemHeight * size() - rowSpacing + toAdd); - - RenderBlock::updateLogicalHeight(); - - if (m_vBar) { - bool enabled = numVisibleItems() < numItems(); - m_vBar->setEnabled(enabled); - m_vBar->setSteps(1, max(1, numVisibleItems() - 1), itemHeight); - m_vBar->setProportion(numVisibleItems(), numItems()); - if (!enabled) { - scrollToOffsetWithoutAnimation(VerticalScrollbar, 0); - m_indexOffset = 0; - } - } + LayoutUnit height = itemHeight() * size() - rowSpacing + borderAndPaddingHeight(); + RenderBox::computeLogicalHeight(height, logicalTop, computedValues); } LayoutUnit RenderListBox::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode lineDirection, LinePositionMode linePositionMode) const diff --git a/Source/WebCore/rendering/RenderListBox.h b/Source/WebCore/rendering/RenderListBox.h index d259e767c..e936dc2ce 100644 --- a/Source/WebCore/rendering/RenderListBox.h +++ b/Source/WebCore/rendering/RenderListBox.h @@ -77,7 +77,7 @@ private: virtual void computePreferredLogicalWidths(); virtual LayoutUnit baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const; - virtual void updateLogicalHeight() OVERRIDE; + virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE; virtual void layout(); diff --git a/Source/WebCore/rendering/RenderObject.h b/Source/WebCore/rendering/RenderObject.h index 3f3849f62..0b10b69dc 100644 --- a/Source/WebCore/rendering/RenderObject.h +++ b/Source/WebCore/rendering/RenderObject.h @@ -724,7 +724,7 @@ public: // Build an array of quads in absolute coords for line boxes virtual void absoluteQuads(Vector<FloatQuad>&, bool* /*wasFixed*/ = 0) const { } - void absoluteFocusRingQuads(Vector<FloatQuad>&); + virtual void absoluteFocusRingQuads(Vector<FloatQuad>&); static FloatRect absoluteBoundingBoxRectForRange(const Range*); diff --git a/Source/WebCore/rendering/RenderText.cpp b/Source/WebCore/rendering/RenderText.cpp index 7761fc1e1..6aeb4d92d 100644 --- a/Source/WebCore/rendering/RenderText.cpp +++ b/Source/WebCore/rendering/RenderText.cpp @@ -1268,6 +1268,7 @@ void RenderText::setTextWithOffset(PassRefPtr<StringImpl> text, unsigned offset, // Dirty all text boxes that include characters in between offset and offset+len. for (InlineTextBox* curr = firstTextBox(); curr; curr = curr->nextTextBox()) { + // FIXME: This shouldn't rely on the end of a dirty line box. See https://bugs.webkit.org/show_bug.cgi?id=97264 // Text run is entirely before the affected range. if (curr->end() < offset) continue; diff --git a/Source/WebCore/rendering/TextAutosizer.cpp b/Source/WebCore/rendering/TextAutosizer.cpp index c4503a13b..304bdb31c 100644 --- a/Source/WebCore/rendering/TextAutosizer.cpp +++ b/Source/WebCore/rendering/TextAutosizer.cpp @@ -35,6 +35,11 @@ namespace WebCore { +struct TextAutosizingWindowInfo { + IntSize windowSize; + IntSize minLayoutSize; +}; + TextAutosizer::TextAutosizer(Document* document) : m_document(document) { @@ -53,36 +58,68 @@ bool TextAutosizer::processSubtree(RenderObject* layoutRoot) Frame* mainFrame = m_document->page()->mainFrame(); + TextAutosizingWindowInfo windowInfo; + // Window area, in logical (density-independent) pixels. - IntSize windowSize = m_document->settings()->textAutosizingWindowSizeOverride(); - if (windowSize.isEmpty()) { + windowInfo.windowSize = m_document->settings()->textAutosizingWindowSizeOverride(); + if (windowInfo.windowSize.isEmpty()) { bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenWidthOverride(mainFrame); - windowSize = mainFrame->view()->visibleContentRect(includeScrollbars).size(); // FIXME: Check that this is always in logical (density-independent) pixels (see wkbug.com/87440). + windowInfo.windowSize = mainFrame->view()->visibleContentRect(includeScrollbars).size(); // FIXME: Check that this is always in logical (density-independent) pixels (see wkbug.com/87440). } // 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. - IntSize minLayoutSize = mainFrame->view()->layoutSize(); + windowInfo.minLayoutSize = mainFrame->view()->layoutSize(); for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->parent()) { if (!frame->view()->isInChildFrameWithFrameFlattening()) - minLayoutSize = minLayoutSize.shrunkTo(frame->view()->layoutSize()); + windowInfo.minLayoutSize = windowInfo.minLayoutSize.shrunkTo(frame->view()->layoutSize()); } - for (RenderObject* descendant = layoutRoot->nextInPreOrder(layoutRoot); descendant; descendant = descendant->nextInPreOrder(layoutRoot)) { - if (isNotAnAutosizingContainer(descendant)) - continue; - processBox(toRenderBox(descendant), windowSize, minLayoutSize); - } + // The layoutRoot could be neither a container nor a cluster, so walk up the tree till we find each of these. + RenderBlock* container = layoutRoot->isRenderBlock() ? toRenderBlock(layoutRoot) : layoutRoot->containingBlock(); + while (container && !isAutosizingContainer(container)) + container = container->containingBlock(); + + RenderBlock* cluster = container; + while (cluster && (!isAutosizingContainer(cluster) || !isAutosizingCluster(cluster))) + cluster = cluster->containingBlock(); + processCluster(cluster, container, layoutRoot, windowInfo); return true; } -static bool contentHeightIsConstrained(const RenderBox* box) +void TextAutosizer::processCluster(RenderBlock* cluster, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo& windowInfo) +{ + ASSERT(isAutosizingCluster(cluster)); + + // FIXME: Many pages set a max-width on their content. So especially for the RenderView, + // instead of just taking the width of |cluster| we should find the lowest common ancestor of + // the first and last descendant text node of the cluster (i.e. the deepest wrapper block that + // contains all the text), and use its width instead. + RenderBlock* lowestCommonAncestor = cluster; + float commonAncestorWidth = lowestCommonAncestor->contentLogicalWidth(); + + float multiplier = 1; + if (clusterShouldBeAutosized(lowestCommonAncestor, commonAncestorWidth)) { + int logicalWindowWidth = cluster->isHorizontalWritingMode() ? windowInfo.windowSize.width() : windowInfo.windowSize.height(); + int logicalLayoutWidth = cluster->isHorizontalWritingMode() ? windowInfo.minLayoutSize.width() : windowInfo.minLayoutSize.height(); + // Ignore box width in excess of the layout width, to avoid extreme multipliers. + float logicalClusterWidth = std::min<float>(commonAncestorWidth, logicalLayoutWidth); + + multiplier = logicalClusterWidth / logicalWindowWidth; + multiplier *= m_document->settings()->textAutosizingFontScaleFactor(); + multiplier = std::max(1.0f, multiplier); + } + + processContainer(multiplier, container, subtreeRoot, windowInfo); +} + +static bool contentHeightIsConstrained(const RenderBlock* container) { // FIXME: Propagate constrainedness down the tree, to avoid inefficiently walking back up from each box. // FIXME: This code needs to take into account vertical writing modes. // FIXME: Consider additional heuristics, such as ignoring fixed heights if the content is already overflowing before autosizing kicks in. - for (const RenderBox* container = box; container; container = container->containingBlock()) { + for (; container; container = container->containingBlock()) { RenderStyle* style = container->style(); if (style->overflowY() >= OSCROLL) return false; @@ -97,29 +134,28 @@ static bool contentHeightIsConstrained(const RenderBox* box) return false; } -void TextAutosizer::processBox(RenderBox* box, const IntSize& windowSize, const IntSize& layoutSize) +void TextAutosizer::processContainer(float multiplier, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo& windowInfo) { - if (contentHeightIsConstrained(box)) - return; - - int logicalWindowWidth = box->isHorizontalWritingMode() ? windowSize.width() : windowSize.height(); - int logicalLayoutWidth = box->isHorizontalWritingMode() ? layoutSize.width() : layoutSize.height(); - // Ignore box width in excess of the layout width, to avoid extreme multipliers. - float logicalBoxWidth = std::min<float>(box->logicalWidth(), logicalLayoutWidth); + ASSERT(isAutosizingContainer(container)); - float multiplier = logicalBoxWidth / logicalWindowWidth; - multiplier *= m_document->settings()->textAutosizingFontScaleFactor(); + float localMultiplier = contentHeightIsConstrained(container) ? 1 : multiplier; - if (multiplier < 1) - return; - RenderObject* descendant = nextInPreOrderMatchingFilter(box, box, isNotAnAutosizingContainer); + RenderObject* descendant = nextInPreOrderSkippingDescendantsOfContainers(subtreeRoot, subtreeRoot); while (descendant) { if (descendant->isText()) { - setMultiplier(descendant, multiplier); - setMultiplier(descendant->parent(), multiplier); // Parent does line spacing. + if (localMultiplier != descendant->style()->textAutosizingMultiplier()) { + setMultiplier(descendant, localMultiplier); + setMultiplier(descendant->parent(), localMultiplier); // Parent does line spacing. + } // FIXME: Increase list marker size proportionately. + } else if (isAutosizingContainer(descendant)) { + RenderBlock* descendantBlock = toRenderBlock(descendant); + if (isAutosizingCluster(descendantBlock)) + processCluster(descendantBlock, descendantBlock, descendantBlock, windowInfo); + else + processContainer(multiplier, descendantBlock, descendantBlock, windowInfo); } - descendant = nextInPreOrderMatchingFilter(descendant, box, isNotAnAutosizingContainer); + descendant = nextInPreOrderSkippingDescendantsOfContainers(descendant, subtreeRoot); } } @@ -158,28 +194,104 @@ float TextAutosizer::computeAutosizedFontSize(float specifiedSize, float multipl return computedSize; } -bool TextAutosizer::isNotAnAutosizingContainer(const RenderObject* renderer) +bool TextAutosizer::isAutosizingContainer(const RenderObject* renderer) { - // "Autosizing containers" are the smallest unit for which we can enable/disable - // Text Autosizing. A uniform text size multiplier is enforced within them. - // - Must be RenderBoxes since they need a well-defined logicalWidth(). + // "Autosizing containers" are the smallest unit for which we can + // enable/disable Text Autosizing. // - Must not be inline, as different multipliers on one line looks terrible. // - Must not be list items, as items in the same list should look consistent. - return !renderer->isBox() || renderer->isInline() || renderer->isListItem(); + return renderer->isRenderBlock() && !renderer->isInline() && !renderer->isListItem(); +} + +bool TextAutosizer::isAutosizingCluster(const RenderBlock* renderer) +{ + // "Autosizing clusters" are special autosizing containers within which we + // want to enforce a uniform text size multiplier, in the hopes of making + // the major sections of the page look internally consistent. + // All their descendents (including other autosizing containers) must share + // the same multiplier, except for subtrees which are themselves clusters, + // and some of their descendent containers might not be autosized at all + // (for example if their height is constrained). + // Additionally, clusterShouldBeAutosized requires each cluster to contain a + // minimum amount of text, without which it won't be autosized. + // + // Clusters are chosen using very similar criteria to CSS flow roots, aka + // block formatting contexts (http://w3.org/TR/css3-box/#flow-root), since + // flow roots correspond to box containers that behave somewhat + // independently from their parent (for example they don't overlap floats). + // The definition of a flow flow root also conveniently includes most of the + // ways that a box and its children can have significantly different width + // from the box's parent (we want to avoid having significantly different + // width blocks within a cluster, since the narrower blocks would end up + // larger than would otherwise be necessary). + ASSERT(isAutosizingContainer(renderer)); + + return renderer->isRenderView() + || renderer->isFloating() + || renderer->isOutOfFlowPositioned() + || renderer->isTableCell() + || renderer->isTableCaption() + || renderer->isFlexibleBoxIncludingDeprecated() + || renderer->hasColumns() + || renderer->style()->overflowX() != OVISIBLE + || renderer->style()->overflowY() != OVISIBLE + || renderer->containingBlock()->isHorizontalWritingMode() != renderer->isHorizontalWritingMode(); + // FIXME: Tables need special handling to multiply all their columns by + // the same amount even if they're different widths; so do hasColumns() + // renderers, and probably flexboxes... +} + +bool TextAutosizer::clusterShouldBeAutosized(const RenderBlock* lowestCommonAncestor, float commonAncestorWidth) +{ + // Don't autosize clusters that contain less than 4 lines of text (in + // practice less lines are required, since measureDescendantTextWidth + // assumes that characters are 1em wide, but most characters are narrower + // than that, so we're overestimating their contribution to the linecount). + // + // This is to reduce the likelihood of autosizing things like headers and + // footers, which can be quite visually distracting. The rationale is that + // if a cluster contains very few lines of text then it's ok to have to zoom + // in and pan from side to side to read each line, since if there are very + // few lines of text you'll only need to pan across once or twice. + const float minLinesOfText = 4; + float minTextWidth = commonAncestorWidth * minLinesOfText; + float textWidth = 0; + measureDescendantTextWidth(lowestCommonAncestor, minTextWidth, textWidth); + if (textWidth >= minTextWidth) + return true; + return false; +} + +void TextAutosizer::measureDescendantTextWidth(const RenderBlock* container, float minTextWidth, float& textWidth) +{ + bool skipLocalText = contentHeightIsConstrained(container); + + RenderObject* descendant = nextInPreOrderSkippingDescendantsOfContainers(container, container); + while (descendant) { + if (!skipLocalText && descendant->isText()) { + textWidth += toRenderText(descendant)->renderedTextLength() * descendant->style()->specifiedFontSize(); + } else if (isAutosizingContainer(descendant)) { + RenderBlock* descendantBlock = toRenderBlock(descendant); + if (!isAutosizingCluster(descendantBlock)) + measureDescendantTextWidth(descendantBlock, minTextWidth, textWidth); + } + if (textWidth >= minTextWidth) + return; + descendant = nextInPreOrderSkippingDescendantsOfContainers(descendant, container); + } } -RenderObject* TextAutosizer::nextInPreOrderMatchingFilter(RenderObject* current, const RenderObject* stayWithin, RenderObjectFilterFunctor filter) +RenderObject* TextAutosizer::nextInPreOrderSkippingDescendantsOfContainers(const RenderObject* current, const RenderObject* stayWithin) { - for (RenderObject* child = current->firstChild(); child; child = child->nextSibling()) - if (filter(child)) + if (current == stayWithin || !isAutosizingContainer(current)) + for (RenderObject* child = current->firstChild(); child; child = child->nextSibling()) return child; for (const RenderObject* ancestor = current; ancestor; ancestor = ancestor->parent()) { if (ancestor == stayWithin) return 0; for (RenderObject* sibling = ancestor->nextSibling(); sibling; sibling = sibling->nextSibling()) - if (filter(sibling)) - return sibling; + return sibling; } return 0; diff --git a/Source/WebCore/rendering/TextAutosizer.h b/Source/WebCore/rendering/TextAutosizer.h index ae9fd8363..2e2e70e6b 100644 --- a/Source/WebCore/rendering/TextAutosizer.h +++ b/Source/WebCore/rendering/TextAutosizer.h @@ -36,10 +36,11 @@ namespace WebCore { class Document; -class RenderBox; +class RenderBlock; class RenderObject; class RenderStyle; class RenderText; +struct TextAutosizingWindowInfo; class TextAutosizer { WTF_MAKE_NONCOPYABLE(TextAutosizer); @@ -56,14 +57,19 @@ public: private: explicit TextAutosizer(Document*); - void processBox(RenderBox*, const IntSize& windowSize, const IntSize& layoutSize); + void processCluster(RenderBlock* cluster, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&); + void processContainer(float multiplier, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&); + void setMultiplier(RenderObject*, float); - static bool isNotAnAutosizingContainer(const RenderObject*); + static bool isAutosizingContainer(const RenderObject*); + static bool isAutosizingCluster(const RenderBlock*); + + static bool clusterShouldBeAutosized(const RenderBlock* lowestCommonAncestor, float commonAncestorWidth); + static void measureDescendantTextWidth(const RenderBlock* container, float minTextWidth, float& textWidth); - typedef bool (*RenderObjectFilterFunctor)(const RenderObject*); - // Use to traverse the tree of descendants, excluding any subtrees within that whose root doesn't pass the filter. - static RenderObject* nextInPreOrderMatchingFilter(RenderObject* current, const RenderObject* stayWithin, RenderObjectFilterFunctor); + // Use to traverse the tree of descendants, excluding descendants of containers (but returning the containers themselves). + static RenderObject* nextInPreOrderSkippingDescendantsOfContainers(const RenderObject* current, const RenderObject* stayWithin); Document* m_document; }; diff --git a/Source/WebCore/rendering/svg/RenderSVGModelObject.cpp b/Source/WebCore/rendering/svg/RenderSVGModelObject.cpp index d44a93da4..56372b49f 100644 --- a/Source/WebCore/rendering/svg/RenderSVGModelObject.cpp +++ b/Source/WebCore/rendering/svg/RenderSVGModelObject.cpp @@ -164,6 +164,13 @@ static bool isGraphicsElement(RenderObject* renderer) return renderer->isSVGShape() || renderer->isSVGText() || renderer->isSVGImage() || renderer->node()->hasTagName(SVGNames::useTag); } +// The SVG addFocusRingRects() method adds rects in local coordinates so the default absoluteFocusRingQuads +// returns incorrect values for SVG objects. Overriding this method provides access to the absolute bounds. +void RenderSVGModelObject::absoluteFocusRingQuads(Vector<FloatQuad>& quads) +{ + quads.append(localToAbsoluteQuad(FloatQuad(repaintRectInLocalCoordinates()))); +} + bool RenderSVGModelObject::checkIntersection(RenderObject* renderer, const FloatRect& rect) { if (!renderer || renderer->style()->pointerEvents() == PE_NONE) diff --git a/Source/WebCore/rendering/svg/RenderSVGModelObject.h b/Source/WebCore/rendering/svg/RenderSVGModelObject.h index a99dd9da7..b83ca0fcb 100644 --- a/Source/WebCore/rendering/svg/RenderSVGModelObject.h +++ b/Source/WebCore/rendering/svg/RenderSVGModelObject.h @@ -72,6 +72,7 @@ protected: private: // This method should never be called, SVG uses a different nodeAtPoint method bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE; + virtual void absoluteFocusRingQuads(Vector<FloatQuad>&); }; } diff --git a/Source/WebCore/workers/SharedWorker.cpp b/Source/WebCore/workers/SharedWorker.cpp index 925cf3b2d..a626e8849 100644 --- a/Source/WebCore/workers/SharedWorker.cpp +++ b/Source/WebCore/workers/SharedWorker.cpp @@ -35,6 +35,7 @@ #include "SharedWorker.h" +#include "FeatureObserver.h" #include "InspectorInstrumentation.h" #include "KURL.h" #include "MessageChannel.h" @@ -52,6 +53,9 @@ inline SharedWorker::SharedWorker(ScriptExecutionContext* context) PassRefPtr<SharedWorker> SharedWorker::create(ScriptExecutionContext* context, const String& url, const String& name, ExceptionCode& ec) { + ASSERT(isMainThread()); + FeatureObserver::observe(static_cast<Document*>(context)->domWindow(), FeatureObserver::SharedWorkerStart); + RefPtr<SharedWorker> worker = adoptRef(new SharedWorker(context)); RefPtr<MessageChannel> channel = MessageChannel::create(context); diff --git a/Source/WebCore/workers/Worker.cpp b/Source/WebCore/workers/Worker.cpp index 456185768..f79a8b060 100644 --- a/Source/WebCore/workers/Worker.cpp +++ b/Source/WebCore/workers/Worker.cpp @@ -38,6 +38,7 @@ #include "EventListener.h" #include "EventNames.h" #include "ExceptionCode.h" +#include "FeatureObserver.h" #include "Frame.h" #include "FrameLoader.h" #include "InspectorInstrumentation.h" @@ -58,6 +59,9 @@ inline Worker::Worker(ScriptExecutionContext* context) PassRefPtr<Worker> Worker::create(ScriptExecutionContext* context, const String& url, ExceptionCode& ec) { + ASSERT(isMainThread()); + FeatureObserver::observe(static_cast<Document*>(context)->domWindow(), FeatureObserver::WorkerStart); + RefPtr<Worker> worker = adoptRef(new Worker(context)); worker->suspendIfNeeded(); diff --git a/Source/WebCore/xml/XMLErrors.cpp b/Source/WebCore/xml/XMLErrors.cpp index 807fc6ca6..ec3a27012 100644 --- a/Source/WebCore/xml/XMLErrors.cpp +++ b/Source/WebCore/xml/XMLErrors.cpp @@ -96,20 +96,20 @@ static inline PassRefPtr<Element> createXHTMLParserErrorHeader(Document* doc, co reportElement->parserSetAttributes(reportAttributes, DisallowScriptingContent); RefPtr<Element> h3 = doc->createElement(h3Tag, true); - reportElement->parserAddChild(h3.get()); - h3->parserAddChild(doc->createTextNode("This page contains the following errors:")); + reportElement->parserAppendChild(h3.get()); + h3->parserAppendChild(doc->createTextNode("This page contains the following errors:")); RefPtr<Element> fixed = doc->createElement(divTag, true); Vector<Attribute> fixedAttributes; fixedAttributes.append(Attribute(styleAttr, "font-family:monospace;font-size:12px")); fixed->parserSetAttributes(fixedAttributes, DisallowScriptingContent); - reportElement->parserAddChild(fixed.get()); + reportElement->parserAppendChild(fixed.get()); - fixed->parserAddChild(doc->createTextNode(errorMessages)); + fixed->parserAppendChild(doc->createTextNode(errorMessages)); h3 = doc->createElement(h3Tag, true); - reportElement->parserAddChild(h3.get()); - h3->parserAddChild(doc->createTextNode("Below is a rendering of the page up to the first error.")); + reportElement->parserAppendChild(h3.get()); + h3->parserAppendChild(doc->createTextNode("Below is a rendering of the page up to the first error.")); return reportElement.release(); } @@ -125,8 +125,8 @@ void XMLErrors::insertErrorMessageBlock() if (!documentElement) { RefPtr<Element> rootElement = m_document->createElement(htmlTag, true); RefPtr<Element> body = m_document->createElement(bodyTag, true); - rootElement->parserAddChild(body); - m_document->parserAddChild(rootElement); + rootElement->parserAppendChild(body); + m_document->parserAppendChild(rootElement); if (m_document->attached() && !rootElement->attached()) rootElement->attach(); documentElement = body.get(); @@ -135,14 +135,14 @@ void XMLErrors::insertErrorMessageBlock() else if (documentElement->namespaceURI() == SVGNames::svgNamespaceURI) { RefPtr<Element> rootElement = m_document->createElement(htmlTag, true); RefPtr<Element> body = m_document->createElement(bodyTag, true); - rootElement->parserAddChild(body); + rootElement->parserAppendChild(body); documentElement->parentNode()->parserRemoveChild(documentElement.get()); if (documentElement->attached()) documentElement->detach(); - body->parserAddChild(documentElement); - m_document->parserAddChild(rootElement.get()); + body->parserAppendChild(documentElement); + m_document->parserAppendChild(rootElement.get()); if (m_document->attached()) // In general, rootElement shouldn't be attached right now, but it will be if there is a style element @@ -162,8 +162,8 @@ void XMLErrors::insertErrorMessageBlock() attributes.append(Attribute(styleAttr, "white-space: normal")); RefPtr<Element> paragraph = m_document->createElement(pTag, true); paragraph->parserSetAttributes(attributes, DisallowScriptingContent); - paragraph->parserAddChild(m_document->createTextNode("This document was created as the result of an XSL transformation. The line and column numbers given are from the transformed result.")); - reportElement->parserAddChild(paragraph.release()); + paragraph->parserAppendChild(m_document->createTextNode("This document was created as the result of an XSL transformation. The line and column numbers given are from the transformed result.")); + reportElement->parserAppendChild(paragraph.release()); } #endif @@ -171,7 +171,7 @@ void XMLErrors::insertErrorMessageBlock() if (firstChild) documentElement->parserInsertBefore(reportElement, documentElement->firstChild()); else - documentElement->parserAddChild(reportElement); + documentElement->parserAppendChild(reportElement); if (documentElement->attached() && !reportElement->attached()) reportElement->attach(); diff --git a/Source/WebCore/xml/parser/XMLDocumentParser.cpp b/Source/WebCore/xml/parser/XMLDocumentParser.cpp index 69ef6a52c..5aa0e0890 100644 --- a/Source/WebCore/xml/parser/XMLDocumentParser.cpp +++ b/Source/WebCore/xml/parser/XMLDocumentParser.cpp @@ -147,7 +147,7 @@ void XMLDocumentParser::enterText() #endif ASSERT(!m_leafTextNode); m_leafTextNode = Text::create(document(), ""); - m_currentNode->parserAddChild(m_leafTextNode.get()); + m_currentNode->parserAppendChild(m_leafTextNode.get()); } #if !USE(QXMLSTREAM) @@ -295,7 +295,7 @@ bool XMLDocumentParser::parseDocumentFragment(const String& chunk, DocumentFragm // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-xhtml-syntax.html#xml-fragment-parsing-algorithm // For now we have a hack for script/style innerHTML support: if (contextElement && (contextElement->hasLocalName(HTMLNames::scriptTag) || contextElement->hasLocalName(HTMLNames::styleTag))) { - fragment->parserAddChild(fragment->document()->createTextNode(chunk)); + fragment->parserAppendChild(fragment->document()->createTextNode(chunk)); return true; } diff --git a/Source/WebCore/xml/parser/XMLDocumentParserLibxml2.cpp b/Source/WebCore/xml/parser/XMLDocumentParserLibxml2.cpp index 3a4a47374..7813ad308 100644 --- a/Source/WebCore/xml/parser/XMLDocumentParserLibxml2.cpp +++ b/Source/WebCore/xml/parser/XMLDocumentParserLibxml2.cpp @@ -816,7 +816,7 @@ void XMLDocumentParser::startElementNs(const xmlChar* xmlLocalName, const xmlCha if (scriptElement) m_scriptStartPosition = textPosition(); - m_currentNode->parserAddChild(newElement.get()); + m_currentNode->parserAppendChild(newElement.get()); pushCurrentNode(newElement.get()); if (m_view && !newElement->attached()) @@ -968,7 +968,7 @@ void XMLDocumentParser::processingInstruction(const xmlChar* target, const xmlCh pi->setCreatedByParser(true); - m_currentNode->parserAddChild(pi.get()); + m_currentNode->parserAppendChild(pi.get()); if (m_view && !pi->attached()) pi->attach(); @@ -996,7 +996,7 @@ void XMLDocumentParser::cdataBlock(const xmlChar* s, int len) exitText(); RefPtr<CDATASection> newNode = CDATASection::create(document(), toString(s, len)); - m_currentNode->parserAddChild(newNode.get()); + m_currentNode->parserAppendChild(newNode.get()); if (m_view && !newNode->attached()) newNode->attach(); } @@ -1014,7 +1014,7 @@ void XMLDocumentParser::comment(const xmlChar* s) exitText(); RefPtr<Comment> newNode = Comment::create(document(), toString(s)); - m_currentNode->parserAddChild(newNode.get()); + m_currentNode->parserAppendChild(newNode.get()); if (m_view && !newNode->attached()) newNode->attach(); } @@ -1059,7 +1059,7 @@ void XMLDocumentParser::internalSubset(const xmlChar* name, const xmlChar* exter } if (document()) - document()->parserAddChild(DocumentType::create(document(), toString(name), toString(externalID), toString(systemID))); + document()->parserAppendChild(DocumentType::create(document(), toString(name), toString(externalID), toString(systemID))); } static inline XMLDocumentParser* getParser(void* closure) diff --git a/Source/WebCore/xml/parser/XMLDocumentParserQt.cpp b/Source/WebCore/xml/parser/XMLDocumentParserQt.cpp index c0ba9ced6..9473ab795 100644 --- a/Source/WebCore/xml/parser/XMLDocumentParserQt.cpp +++ b/Source/WebCore/xml/parser/XMLDocumentParserQt.cpp @@ -480,7 +480,7 @@ void XMLDocumentParser::parseStartElement() if (scriptElement) m_scriptStartPosition = textPosition(); - m_currentNode->parserAddChild(newElement.get()); + m_currentNode->parserAppendChild(newElement.get()); pushCurrentNode(newElement.get()); if (m_view && !newElement->attached()) @@ -572,7 +572,7 @@ void XMLDocumentParser::parseProcessingInstruction() pi->setCreatedByParser(true); - m_currentNode->parserAddChild(pi.get()); + m_currentNode->parserAppendChild(pi.get()); if (m_view && !pi->attached()) pi->attach(); @@ -593,7 +593,7 @@ void XMLDocumentParser::parseCdata() RefPtr<CDATASection> newNode = CDATASection::create(document(), m_stream.text()); - m_currentNode->parserAddChild(newNode.get()); + m_currentNode->parserAppendChild(newNode.get()); if (m_view && !newNode->attached()) newNode->attach(); } @@ -604,7 +604,7 @@ void XMLDocumentParser::parseComment() RefPtr<Comment> newNode = Comment::create(document(), m_stream.text()); - m_currentNode->parserAddChild(newNode.get()); + m_currentNode->parserAppendChild(newNode.get()); if (m_view && !newNode->attached()) newNode->attach(); } @@ -636,7 +636,7 @@ void XMLDocumentParser::parseDtd() ) setIsXHTMLDocument(true); // controls if we replace entities or not. if (!m_parsingFragment) - document()->parserAddChild(DocumentType::create(document(), name, publicId, systemId)); + document()->parserAppendChild(DocumentType::create(document(), name, publicId, systemId)); } } diff --git a/Source/WebCore/xml/parser/XMLTreeBuilder.cpp b/Source/WebCore/xml/parser/XMLTreeBuilder.cpp index cc0d722d5..12defe586 100644 --- a/Source/WebCore/xml/parser/XMLTreeBuilder.cpp +++ b/Source/WebCore/xml/parser/XMLTreeBuilder.cpp @@ -214,7 +214,7 @@ void XMLTreeBuilder::processDOCTYPE(const AtomicXMLToken& token) AtomicString systemIdentifier(token.systemIdentifier().data(), token.systemIdentifier().size()); RefPtr<DocumentType> doctype = DocumentType::create(m_document, token.name(), publicIdentifier, systemIdentifier); m_document->setDocType(doctype); - m_document->parserAddChild(doctype); + m_document->parserAppendChild(doctype); if ((publicIdentifier == xhtmlTransitional) || (publicIdentifier == xhtml11) @@ -244,7 +244,7 @@ void XMLTreeBuilder::processStartTag(const AtomicXMLToken& token) processAttributes(token, top, newElement); newElement->beginParsingChildren(); - m_currentNodeStack.last().node()->parserAddChild(newElement.get()); + m_currentNodeStack.last().node()->parserAppendChild(newElement.get()); top.setNode(newElement); pushCurrentNode(top); @@ -388,7 +388,7 @@ void XMLTreeBuilder::processHTMLEntity(const AtomicXMLToken& token) inline void XMLTreeBuilder::add(PassRefPtr<Node> node) { - m_currentNodeStack.last().node()->parserAddChild(node.get()); + m_currentNodeStack.last().node()->parserAppendChild(node.get()); if (!node->attached()) node->attach(); } |
