1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.graphics;
18
19import com.android.ide.common.rendering.api.LayoutLog;
20import com.android.layoutlib.bridge.Bridge;
21import com.android.layoutlib.bridge.impl.DelegateManager;
22import com.android.tools.layoutlib.annotations.LayoutlibDelegate;
23
24import android.graphics.Shader.TileMode;
25
26import java.awt.image.ColorModel;
27
28/**
29 * Delegate implementing the native methods of android.graphics.LinearGradient
30 *
31 * Through the layoutlib_create tool, the original native methods of LinearGradient have been
32 * replaced by calls to methods of the same name in this delegate class.
33 *
34 * This class behaves like the original native implementation, but in Java, keeping previously
35 * native data into its own objects and mapping them to int that are sent back and forth between
36 * it and the original LinearGradient class.
37 *
38 * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
39 * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
40 *
41 * @see Shader_Delegate
42 *
43 */
44public final class LinearGradient_Delegate extends Gradient_Delegate {
45
46    // ---- delegate data ----
47    private java.awt.Paint mJavaPaint;
48
49    // ---- Public Helper methods ----
50
51    @Override
52    public java.awt.Paint getJavaPaint() {
53        return mJavaPaint;
54    }
55
56    // ---- native methods ----
57
58    @LayoutlibDelegate
59    /*package*/ static long nativeCreate1(LinearGradient thisGradient, long matrix,
60            float x0, float y0, float x1, float y1,
61            int colors[], float positions[], int tileMode) {
62        LinearGradient_Delegate newDelegate = new LinearGradient_Delegate(matrix, x0, y0,
63                x1, y1, colors, positions, Shader_Delegate.getTileMode(tileMode));
64        return sManager.addNewDelegate(newDelegate);
65    }
66
67    @LayoutlibDelegate
68    /*package*/ static long nativeCreate2(LinearGradient thisGradient, long matrix,
69            float x0, float y0, float x1, float y1,
70            int color0, int color1, int tileMode) {
71        return nativeCreate1(thisGradient, matrix, x0, y0, x1, y1, new int[] { color0, color1},
72                null /*positions*/, tileMode);
73    }
74
75    // ---- Private delegate/helper methods ----
76
77    /**
78     * Create a shader that draws a linear gradient along a line.
79     *
80     * @param nativeMatrix reference to the shader's native transformation matrix
81     * @param x0 The x-coordinate for the start of the gradient line
82     * @param y0 The y-coordinate for the start of the gradient line
83     * @param x1 The x-coordinate for the end of the gradient line
84     * @param y1 The y-coordinate for the end of the gradient line
85     * @param colors The colors to be distributed along the gradient line
86     * @param positions May be null. The relative positions [0..1] of each
87     *            corresponding color in the colors array. If this is null, the
88     *            the colors are distributed evenly along the gradient line.
89     * @param tile The Shader tiling mode
90     */
91    private LinearGradient_Delegate(long nativeMatrix, float x0, float y0, float x1,
92            float y1, int colors[], float positions[], TileMode tile) {
93        super(nativeMatrix, colors, positions);
94        mJavaPaint = new LinearGradientPaint(x0, y0, x1, y1, mColors, mPositions, tile);
95    }
96
97    // ---- Custom Java Paint ----
98    /**
99     * Linear Gradient (Java) Paint able to handle more than 2 points, as
100     * {@link java.awt.GradientPaint} only supports 2 points and does not support Android's tile
101     * modes.
102     */
103    private class LinearGradientPaint extends GradientPaint {
104
105        private final float mX0;
106        private final float mY0;
107        private final float mDx;
108        private final float mDy;
109        private final float mDSize2;
110
111        public LinearGradientPaint(float x0, float y0, float x1, float y1, int colors[],
112                float positions[], TileMode tile) {
113            super(colors, positions, tile);
114            mX0 = x0;
115            mY0 = y0;
116            mDx = x1 - x0;
117            mDy = y1 - y0;
118            mDSize2 = mDx * mDx + mDy * mDy;
119        }
120
121        @Override
122        public java.awt.PaintContext createContext(
123                java.awt.image.ColorModel      colorModel,
124                java.awt.Rectangle             deviceBounds,
125                java.awt.geom.Rectangle2D      userBounds,
126                java.awt.geom.AffineTransform  xform,
127                java.awt.RenderingHints        hints) {
128            precomputeGradientColors();
129
130            java.awt.geom.AffineTransform canvasMatrix;
131            try {
132                canvasMatrix = xform.createInverse();
133            } catch (java.awt.geom.NoninvertibleTransformException e) {
134                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
135                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
136                canvasMatrix = new java.awt.geom.AffineTransform();
137            }
138
139            java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
140            try {
141                localMatrix = localMatrix.createInverse();
142            } catch (java.awt.geom.NoninvertibleTransformException e) {
143                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
144                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
145                localMatrix = new java.awt.geom.AffineTransform();
146            }
147
148            return new LinearGradientPaintContext(canvasMatrix, localMatrix, colorModel);
149        }
150
151        private class LinearGradientPaintContext implements java.awt.PaintContext {
152
153            private final java.awt.geom.AffineTransform mCanvasMatrix;
154            private final java.awt.geom.AffineTransform mLocalMatrix;
155            private final java.awt.image.ColorModel mColorModel;
156
157            private LinearGradientPaintContext(
158                    java.awt.geom.AffineTransform canvasMatrix,
159                    java.awt.geom.AffineTransform localMatrix,
160                    java.awt.image.ColorModel colorModel) {
161                mCanvasMatrix = canvasMatrix;
162                mLocalMatrix = localMatrix;
163                mColorModel = colorModel.hasAlpha() ? colorModel : ColorModel.getRGBdefault();
164            }
165
166            @Override
167            public void dispose() {
168            }
169
170            @Override
171            public java.awt.image.ColorModel getColorModel() {
172                return mColorModel;
173            }
174
175            @Override
176            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
177                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(
178                    mColorModel, mColorModel.createCompatibleWritableRaster(w, h),
179                    mColorModel.isAlphaPremultiplied(), null);
180
181                int[] data = new int[w*h];
182
183                int index = 0;
184                float[] pt1 = new float[2];
185                float[] pt2 = new float[2];
186                for (int iy = 0 ; iy < h ; iy++) {
187                    for (int ix = 0 ; ix < w ; ix++) {
188                        // handle the canvas transform
189                        pt1[0] = x + ix;
190                        pt1[1] = y + iy;
191                        mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
192
193                        // handle the local matrix.
194                        pt1[0] = pt2[0];
195                        pt1[1] = pt2[1];
196                        mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
197
198                        data[index++] = getColor(pt2[0], pt2[1]);
199                    }
200                }
201
202                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
203
204                return image.getRaster();
205            }
206        }
207
208        /**
209         * Returns a color for an arbitrary point.
210         */
211        private int getColor(float x, float y) {
212            float pos;
213            if (mDx == 0) {
214                pos = (y - mY0) / mDy;
215            } else if (mDy == 0) {
216                pos = (x - mX0) / mDx;
217            } else {
218                // find the x position on the gradient vector.
219                float _x = (mDx*mDy*(y-mY0) + mDy*mDy*mX0 + mDx*mDx*x) / mDSize2;
220                // from it get the position relative to the vector
221                pos = (_x - mX0) / mDx;
222            }
223
224            return getGradientColor(pos);
225        }
226    }
227}
228