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
26/**
27 * Delegate implementing the native methods of android.graphics.LinearGradient
28 *
29 * Through the layoutlib_create tool, the original native methods of LinearGradient have been
30 * replaced by calls to methods of the same name in this delegate class.
31 *
32 * This class behaves like the original native implementation, but in Java, keeping previously
33 * native data into its own objects and mapping them to int that are sent back and forth between
34 * it and the original LinearGradient class.
35 *
36 * Because this extends {@link Shader_Delegate}, there's no need to use a {@link DelegateManager},
37 * as all the Shader classes will be added to the manager owned by {@link Shader_Delegate}.
38 *
39 * @see Shader_Delegate
40 *
41 */
42public final class LinearGradient_Delegate extends Gradient_Delegate {
43
44    // ---- delegate data ----
45    private java.awt.Paint mJavaPaint;
46
47    // ---- Public Helper methods ----
48
49    @Override
50    public java.awt.Paint getJavaPaint() {
51        return mJavaPaint;
52    }
53
54    // ---- native methods ----
55
56    @LayoutlibDelegate
57    /*package*/ static int nativeCreate1(LinearGradient thisGradient,
58            float x0, float y0, float x1, float y1,
59            int colors[], float positions[], int tileMode) {
60        LinearGradient_Delegate newDelegate = new LinearGradient_Delegate(x0, y0, x1, y1,
61                colors, positions, Shader_Delegate.getTileMode(tileMode));
62        return sManager.addNewDelegate(newDelegate);
63    }
64
65    @LayoutlibDelegate
66    /*package*/ static int nativeCreate2(LinearGradient thisGradient,
67            float x0, float y0, float x1, float y1,
68            int color0, int color1, int tileMode) {
69        return nativeCreate1(thisGradient,
70                x0, y0, x1, y1, new int[] { color0, color1}, null /*positions*/,
71                tileMode);
72    }
73
74    @LayoutlibDelegate
75    /*package*/ static int nativePostCreate1(LinearGradient thisGradient,
76            int native_shader, float x0, float y0, float x1, float y1,
77            int colors[], float positions[], int tileMode) {
78        // nothing to be done here.
79        return 0;
80    }
81
82    @LayoutlibDelegate
83    /*package*/ static int nativePostCreate2(LinearGradient thisGradient,
84            int native_shader, float x0, float y0, float x1, float y1,
85            int color0, int color1, int tileMode) {
86        // nothing to be done here.
87        return 0;
88    }
89
90    // ---- Private delegate/helper methods ----
91
92    /**
93     * Create a shader that draws a linear gradient along a line.
94     *
95     * @param x0 The x-coordinate for the start of the gradient line
96     * @param y0 The y-coordinate for the start of the gradient line
97     * @param x1 The x-coordinate for the end of the gradient line
98     * @param y1 The y-coordinate for the end of the gradient line
99     * @param colors The colors to be distributed along the gradient line
100     * @param positions May be null. The relative positions [0..1] of each
101     *            corresponding color in the colors array. If this is null, the
102     *            the colors are distributed evenly along the gradient line.
103     * @param tile The Shader tiling mode
104     */
105    private LinearGradient_Delegate(float x0, float y0, float x1, float y1,
106            int colors[], float positions[], TileMode tile) {
107        super(colors, positions);
108        mJavaPaint = new LinearGradientPaint(x0, y0, x1, y1, mColors, mPositions, tile);
109    }
110
111    // ---- Custom Java Paint ----
112    /**
113     * Linear Gradient (Java) Paint able to handle more than 2 points, as
114     * {@link java.awt.GradientPaint} only supports 2 points and does not support Android's tile
115     * modes.
116     */
117    private class LinearGradientPaint extends GradientPaint {
118
119        private final float mX0;
120        private final float mY0;
121        private final float mDx;
122        private final float mDy;
123        private final float mDSize2;
124
125        public LinearGradientPaint(float x0, float y0, float x1, float y1, int colors[],
126                float positions[], TileMode tile) {
127            super(colors, positions, tile);
128            mX0 = x0;
129            mY0 = y0;
130            mDx = x1 - x0;
131            mDy = y1 - y0;
132            mDSize2 = mDx * mDx + mDy * mDy;
133        }
134
135        @Override
136        public java.awt.PaintContext createContext(
137                java.awt.image.ColorModel      colorModel,
138                java.awt.Rectangle             deviceBounds,
139                java.awt.geom.Rectangle2D      userBounds,
140                java.awt.geom.AffineTransform  xform,
141                java.awt.RenderingHints        hints) {
142            precomputeGradientColors();
143
144            java.awt.geom.AffineTransform canvasMatrix;
145            try {
146                canvasMatrix = xform.createInverse();
147            } catch (java.awt.geom.NoninvertibleTransformException e) {
148                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
149                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
150                canvasMatrix = new java.awt.geom.AffineTransform();
151            }
152
153            java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
154            try {
155                localMatrix = localMatrix.createInverse();
156            } catch (java.awt.geom.NoninvertibleTransformException e) {
157                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
158                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
159                localMatrix = new java.awt.geom.AffineTransform();
160            }
161
162            return new LinearGradientPaintContext(canvasMatrix, localMatrix, colorModel);
163        }
164
165        private class LinearGradientPaintContext implements java.awt.PaintContext {
166
167            private final java.awt.geom.AffineTransform mCanvasMatrix;
168            private final java.awt.geom.AffineTransform mLocalMatrix;
169            private final java.awt.image.ColorModel mColorModel;
170
171            private LinearGradientPaintContext(
172                    java.awt.geom.AffineTransform canvasMatrix,
173                    java.awt.geom.AffineTransform localMatrix,
174                    java.awt.image.ColorModel colorModel) {
175                mCanvasMatrix = canvasMatrix;
176                mLocalMatrix = localMatrix;
177                mColorModel = colorModel;
178            }
179
180            @Override
181            public void dispose() {
182            }
183
184            @Override
185            public java.awt.image.ColorModel getColorModel() {
186                return mColorModel;
187            }
188
189            @Override
190            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
191                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
192                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
193
194                int[] data = new int[w*h];
195
196                int index = 0;
197                float[] pt1 = new float[2];
198                float[] pt2 = new float[2];
199                for (int iy = 0 ; iy < h ; iy++) {
200                    for (int ix = 0 ; ix < w ; ix++) {
201                        // handle the canvas transform
202                        pt1[0] = x + ix;
203                        pt1[1] = y + iy;
204                        mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
205
206                        // handle the local matrix.
207                        pt1[0] = pt2[0];
208                        pt1[1] = pt2[1];
209                        mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
210
211                        data[index++] = getColor(pt2[0], pt2[1]);
212                    }
213                }
214
215                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
216
217                return image.getRaster();
218            }
219        }
220
221        /**
222         * Returns a color for an arbitrary point.
223         */
224        private int getColor(float x, float y) {
225            float pos;
226            if (mDx == 0) {
227                pos = (y - mY0) / mDy;
228            } else if (mDy == 0) {
229                pos = (x - mX0) / mDx;
230            } else {
231                // find the x position on the gradient vector.
232                float _x = (mDx*mDy*(y-mY0) + mDy*mDy*mX0 + mDx*mDx*x) / mDSize2;
233                // from it get the position relative to the vector
234                pos = (_x - mX0) / mDx;
235            }
236
237            return getGradientColor(pos);
238        }
239    }
240}
241