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 long 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 long 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    // ---- Private delegate/helper methods ----
75
76    /**
77     * Create a shader that draws a linear gradient along a line.
78     *
79     * @param x0 The x-coordinate for the start of the gradient line
80     * @param y0 The y-coordinate for the start of the gradient line
81     * @param x1 The x-coordinate for the end of the gradient line
82     * @param y1 The y-coordinate for the end of the gradient line
83     * @param colors The colors to be distributed along the gradient line
84     * @param positions May be null. The relative positions [0..1] of each
85     *            corresponding color in the colors array. If this is null, the
86     *            the colors are distributed evenly along the gradient line.
87     * @param tile The Shader tiling mode
88     */
89    private LinearGradient_Delegate(float x0, float y0, float x1, float y1,
90            int colors[], float positions[], TileMode tile) {
91        super(colors, positions);
92        mJavaPaint = new LinearGradientPaint(x0, y0, x1, y1, mColors, mPositions, tile);
93    }
94
95    // ---- Custom Java Paint ----
96    /**
97     * Linear Gradient (Java) Paint able to handle more than 2 points, as
98     * {@link java.awt.GradientPaint} only supports 2 points and does not support Android's tile
99     * modes.
100     */
101    private class LinearGradientPaint extends GradientPaint {
102
103        private final float mX0;
104        private final float mY0;
105        private final float mDx;
106        private final float mDy;
107        private final float mDSize2;
108
109        public LinearGradientPaint(float x0, float y0, float x1, float y1, int colors[],
110                float positions[], TileMode tile) {
111            super(colors, positions, tile);
112            mX0 = x0;
113            mY0 = y0;
114            mDx = x1 - x0;
115            mDy = y1 - y0;
116            mDSize2 = mDx * mDx + mDy * mDy;
117        }
118
119        @Override
120        public java.awt.PaintContext createContext(
121                java.awt.image.ColorModel      colorModel,
122                java.awt.Rectangle             deviceBounds,
123                java.awt.geom.Rectangle2D      userBounds,
124                java.awt.geom.AffineTransform  xform,
125                java.awt.RenderingHints        hints) {
126            precomputeGradientColors();
127
128            java.awt.geom.AffineTransform canvasMatrix;
129            try {
130                canvasMatrix = xform.createInverse();
131            } catch (java.awt.geom.NoninvertibleTransformException e) {
132                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
133                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
134                canvasMatrix = new java.awt.geom.AffineTransform();
135            }
136
137            java.awt.geom.AffineTransform localMatrix = getLocalMatrix();
138            try {
139                localMatrix = localMatrix.createInverse();
140            } catch (java.awt.geom.NoninvertibleTransformException e) {
141                Bridge.getLog().fidelityWarning(LayoutLog.TAG_MATRIX_INVERSE,
142                        "Unable to inverse matrix in LinearGradient", e, null /*data*/);
143                localMatrix = new java.awt.geom.AffineTransform();
144            }
145
146            return new LinearGradientPaintContext(canvasMatrix, localMatrix, colorModel);
147        }
148
149        private class LinearGradientPaintContext implements java.awt.PaintContext {
150
151            private final java.awt.geom.AffineTransform mCanvasMatrix;
152            private final java.awt.geom.AffineTransform mLocalMatrix;
153            private final java.awt.image.ColorModel mColorModel;
154
155            private LinearGradientPaintContext(
156                    java.awt.geom.AffineTransform canvasMatrix,
157                    java.awt.geom.AffineTransform localMatrix,
158                    java.awt.image.ColorModel colorModel) {
159                mCanvasMatrix = canvasMatrix;
160                mLocalMatrix = localMatrix;
161                mColorModel = colorModel;
162            }
163
164            @Override
165            public void dispose() {
166            }
167
168            @Override
169            public java.awt.image.ColorModel getColorModel() {
170                return mColorModel;
171            }
172
173            @Override
174            public java.awt.image.Raster getRaster(int x, int y, int w, int h) {
175                java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(w, h,
176                        java.awt.image.BufferedImage.TYPE_INT_ARGB);
177
178                int[] data = new int[w*h];
179
180                int index = 0;
181                float[] pt1 = new float[2];
182                float[] pt2 = new float[2];
183                for (int iy = 0 ; iy < h ; iy++) {
184                    for (int ix = 0 ; ix < w ; ix++) {
185                        // handle the canvas transform
186                        pt1[0] = x + ix;
187                        pt1[1] = y + iy;
188                        mCanvasMatrix.transform(pt1, 0, pt2, 0, 1);
189
190                        // handle the local matrix.
191                        pt1[0] = pt2[0];
192                        pt1[1] = pt2[1];
193                        mLocalMatrix.transform(pt1, 0, pt2, 0, 1);
194
195                        data[index++] = getColor(pt2[0], pt2[1]);
196                    }
197                }
198
199                image.setRGB(0 /*startX*/, 0 /*startY*/, w, h, data, 0 /*offset*/, w /*scansize*/);
200
201                return image.getRaster();
202            }
203        }
204
205        /**
206         * Returns a color for an arbitrary point.
207         */
208        private int getColor(float x, float y) {
209            float pos;
210            if (mDx == 0) {
211                pos = (y - mY0) / mDy;
212            } else if (mDy == 0) {
213                pos = (x - mX0) / mDx;
214            } else {
215                // find the x position on the gradient vector.
216                float _x = (mDx*mDy*(y-mY0) + mDy*mDy*mX0 + mDx*mDx*x) / mDSize2;
217                // from it get the position relative to the vector
218                pos = (_x - mX0) / mDx;
219            }
220
221            return getGradientColor(pos);
222        }
223    }
224}
225