initial import
[vuplus_webkit] / Source / WebCore / platform / graphics / cairo / PlatformContextCairo.cpp
1 /*
2  * Copyright (C) 2011 Igalia S.L.
3  * Copyright (c) 2008, Google Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "PlatformContextCairo.h"
29
30 #include "GraphicsContext.h"
31 #include "CairoUtilities.h"
32 #include "Gradient.h"
33 #include "GraphicsContext.h"
34 #include "Pattern.h"
35 #include <cairo.h>
36
37 namespace WebCore {
38
39 // In Cairo image masking is immediate, so to emulate image clipping we must save masking
40 // details as part of the context state and apply them during platform restore.
41 class ImageMaskInformation {
42 public:
43     void update(cairo_surface_t* maskSurface, const FloatRect& maskRect)
44     {
45         m_maskSurface = maskSurface;
46         m_maskRect = maskRect;
47     }
48
49     bool isValid() const { return m_maskSurface; }
50     cairo_surface_t* maskSurface() const { return m_maskSurface.get(); }
51     const FloatRect& maskRect() const { return m_maskRect; }
52
53 private:
54     RefPtr<cairo_surface_t> m_maskSurface;
55     FloatRect m_maskRect;
56 };
57
58
59 // Encapsulates the additional painting state information we store for each
60 // pushed graphics state.
61 class PlatformContextCairo::State {
62 public:
63     State()
64         : m_globalAlpha(1)
65     {
66     }
67
68     State(const State& state)
69         : m_globalAlpha(state.m_globalAlpha)
70     {
71         // We do not copy m_imageMaskInformation because otherwise it would be applied
72         // more than once during subsequent calls to restore().
73     }
74
75     ImageMaskInformation m_imageMaskInformation;
76     float m_globalAlpha;
77 };
78
79 PlatformContextCairo::PlatformContextCairo(cairo_t* cr)
80     : m_cr(cr)
81     , m_imageInterpolationQuality(InterpolationDefault)
82 {
83     m_stateStack.append(State());
84     m_state = &m_stateStack.last();
85 }
86
87 void PlatformContextCairo::restore()
88 {
89     const ImageMaskInformation& maskInformation = m_state->m_imageMaskInformation;
90     if (maskInformation.isValid()) {
91         const FloatRect& maskRect = maskInformation.maskRect();
92         cairo_pop_group_to_source(m_cr.get());
93         cairo_mask_surface(m_cr.get(), maskInformation.maskSurface(), maskRect.x(), maskRect.y());
94     }
95
96     m_stateStack.removeLast();
97     ASSERT(!m_stateStack.isEmpty());
98     m_state = &m_stateStack.last();
99
100     cairo_restore(m_cr.get());
101 }
102
103 PlatformContextCairo::~PlatformContextCairo()
104 {
105 }
106
107 void PlatformContextCairo::save()
108 {
109     m_stateStack.append(State(*m_state));
110     m_state = &m_stateStack.last();
111
112     cairo_save(m_cr.get());
113 }
114
115 void PlatformContextCairo::pushImageMask(cairo_surface_t* surface, const FloatRect& rect)
116 {
117     // We must call savePlatformState at least once before we can use image masking,
118     // since we actually apply the mask in restorePlatformState.
119     ASSERT(!m_stateStack.isEmpty());
120     m_state->m_imageMaskInformation.update(surface, rect);
121
122     // Cairo doesn't support the notion of an image clip, so we push a group here
123     // and then paint it to the surface with an image mask (which is an immediate
124     // operation) during restorePlatformState.
125
126     // We want to allow the clipped elements to composite with the surface as it
127     // is now, but they are isolated in another group. To make this work, we're
128     // going to blit the current surface contents onto the new group once we push it.
129     cairo_surface_t* currentTarget = cairo_get_target(m_cr.get());
130     cairo_surface_flush(currentTarget);
131
132     // Pushing a new group ensures that only things painted after this point are clipped.
133     cairo_push_group(m_cr.get());
134     cairo_set_operator(m_cr.get(), CAIRO_OPERATOR_SOURCE);
135
136     cairo_set_source_surface(m_cr.get(), currentTarget, 0, 0);
137     cairo_rectangle(m_cr.get(), rect.x(), rect.y(), rect.width(), rect.height());
138     cairo_fill(m_cr.get());
139 }
140
141 static void drawPatternToCairoContext(cairo_t* cr, cairo_pattern_t* pattern, const FloatRect& destRect, float alpha)
142 {
143     cairo_translate(cr, destRect.x(), destRect.y());
144     cairo_set_source(cr, pattern);
145     cairo_rectangle(cr, 0, 0, destRect.width(), destRect.height());
146     cairo_clip(cr);
147     cairo_paint_with_alpha(cr, alpha);
148 }
149
150 void PlatformContextCairo::drawSurfaceToContext(cairo_surface_t* surface, const FloatRect& destRect, const FloatRect& srcRect, GraphicsContext* context)
151 {
152     // If we're drawing a sub portion of the image or scaling then create
153     // a pattern transformation on the image and draw the transformed pattern.
154     // Test using example site at http://www.meyerweb.com/eric/css/edge/complexspiral/demo.html
155     RefPtr<cairo_pattern_t> pattern = adoptRef(cairo_pattern_create_for_surface(surface));
156
157     switch (m_imageInterpolationQuality) {
158     case InterpolationNone:
159     case InterpolationLow:
160         cairo_pattern_set_filter(pattern.get(), CAIRO_FILTER_FAST);
161         break;
162     case InterpolationMedium:
163     case InterpolationHigh:
164         cairo_pattern_set_filter(pattern.get(), CAIRO_FILTER_BILINEAR);
165         break;
166     case InterpolationDefault:
167         cairo_pattern_set_filter(pattern.get(), CAIRO_FILTER_BILINEAR);
168         break;
169     }
170     cairo_pattern_set_extend(pattern.get(), CAIRO_EXTEND_PAD);
171
172     float scaleX = srcRect.width() / destRect.width();
173     float scaleY = srcRect.height() / destRect.height();
174     cairo_matrix_t matrix = { scaleX, 0, 0, scaleY, srcRect.x(), srcRect.y() };
175     cairo_pattern_set_matrix(pattern.get(), &matrix);
176
177     ShadowBlur& shadow = context->platformContext()->shadowBlur();
178     if (shadow.type() != ShadowBlur::NoShadow) {
179         if (GraphicsContext* shadowContext = shadow.beginShadowLayer(context, destRect)) {
180             drawPatternToCairoContext(shadowContext->platformContext()->cr(), pattern.get(), destRect, 1);
181             shadow.endShadowLayer(context);
182         }
183     }
184
185     cairo_save(m_cr.get());
186     drawPatternToCairoContext(m_cr.get(), pattern.get(), destRect, globalAlpha());
187     cairo_restore(m_cr.get());
188 }
189
190 float PlatformContextCairo::globalAlpha() const
191 {
192     return m_state->m_globalAlpha;
193 }
194
195 void PlatformContextCairo::setGlobalAlpha(float globalAlpha)
196 {
197     m_state->m_globalAlpha = globalAlpha;
198 }
199
200 static inline void reduceSourceByAlpha(cairo_t* cr, float alpha)
201 {
202     if (alpha >= 1)
203         return;
204     cairo_push_group(cr);
205     cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
206     cairo_paint_with_alpha(cr, alpha);
207     cairo_pop_group_to_source(cr);
208 }
209
210 static void prepareCairoContextSource(cairo_t* cr, Pattern* pattern, Gradient* gradient, const Color& color, float globalAlpha)
211 {
212     if (pattern) {
213         RefPtr<cairo_pattern_t> cairoPattern(adoptRef(pattern->createPlatformPattern(AffineTransform())));
214         cairo_set_source(cr, cairoPattern.get());
215         reduceSourceByAlpha(cr, globalAlpha);
216     } else if (gradient) {
217         cairo_set_source(cr, gradient->platformGradient());
218
219         // FIXME: It would be faster to simply recreate the Cairo gradient and multiply the
220         // color stops by the global alpha.
221         reduceSourceByAlpha(cr, globalAlpha);
222     } else { // Solid color source.
223         if (globalAlpha < 1)
224             setSourceRGBAFromColor(cr, colorWithOverrideAlpha(color.rgb(), color.alpha() / 255.f * globalAlpha));
225         else
226             setSourceRGBAFromColor(cr, color);
227     }
228 }
229
230 void PlatformContextCairo::prepareForFilling(const GraphicsContextState& state, PatternAdjustment patternAdjustment)
231 {
232     cairo_set_fill_rule(m_cr.get(), state.fillRule == RULE_EVENODD ?  CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
233     prepareCairoContextSource(m_cr.get(),
234                               state.fillPattern.get(),
235                               state.fillGradient.get(),
236                               state.fillColor,
237                               patternAdjustment == AdjustPatternForGlobalAlpha ? globalAlpha() : 1);
238 }
239
240 void PlatformContextCairo::prepareForStroking(const GraphicsContextState& state, AlphaPreservation alphaPreservation)
241 {
242     prepareCairoContextSource(m_cr.get(),
243                               state.strokePattern.get(),
244                               state.strokeGradient.get(),
245                               state.strokeColor,
246                               alphaPreservation == PreserveAlpha ? globalAlpha() : 1);
247 }
248
249 } // namespace WebCore