1/*
2 * Copyright (C) 2006 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 android.text.TextUtils;
20import android.text.SpannedString;
21import android.text.SpannableString;
22import android.text.GraphicsOperations;
23import android.util.DisplayMetrics;
24
25import javax.microedition.khronos.opengles.GL;
26
27/**
28 * The Canvas class holds the "draw" calls. To draw something, you need
29 * 4 basic components: A Bitmap to hold the pixels, a Canvas to host
30 * the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect,
31 * Path, text, Bitmap), and a paint (to describe the colors and styles for the
32 * drawing).
33 */
34public class Canvas {
35    // assigned in constructors, freed in finalizer
36    final int mNativeCanvas;
37
38    /*  Our native canvas can be either a raster, gl, or picture canvas.
39        If we are raster, then mGL will be null, and mBitmap may or may not be
40        present (our default constructor creates a raster canvas but no
41        java-bitmap is). If we are a gl-based, then mBitmap will be null, and
42        mGL will not be null. Thus both cannot be non-null, but its possible
43        for both to be null.
44    */
45    private Bitmap  mBitmap;    // if not null, mGL must be null
46    private GL      mGL;        // if not null, mBitmap must be null
47
48    // optional field set by the caller
49    private DrawFilter  mDrawFilter;
50
51    // Package-scoped for quick access.
52    /*package*/ int mDensity = Bitmap.DENSITY_NONE;
53
54    // Used to determine when compatibility scaling is in effect.
55    private int mScreenDensity = Bitmap.DENSITY_NONE;
56
57    // Used by native code
58    @SuppressWarnings({"UnusedDeclaration"})
59    private int         mSurfaceFormat;
60
61    /**
62     * Construct an empty raster canvas. Use setBitmap() to specify a bitmap to
63     * draw into.  The initial target density is {@link Bitmap#DENSITY_NONE};
64     * this will typically be replaced when a target bitmap is set for the
65     * canvas.
66     */
67    public Canvas() {
68        // 0 means no native bitmap
69        mNativeCanvas = initRaster(0);
70    }
71
72    /**
73     * Construct a canvas with the specified bitmap to draw into. The bitmap
74     * must be mutable.
75     *
76     * <p>The initial target density of the canvas is the same as the given
77     * bitmap's density.
78     *
79     * @param bitmap Specifies a mutable bitmap for the canvas to draw into.
80     */
81    public Canvas(Bitmap bitmap) {
82        if (!bitmap.isMutable()) {
83            throw new IllegalStateException(
84                            "Immutable bitmap passed to Canvas constructor");
85        }
86        throwIfRecycled(bitmap);
87        mNativeCanvas = initRaster(bitmap.ni());
88        mBitmap = bitmap;
89        mDensity = bitmap.mDensity;
90    }
91
92    /*package*/ Canvas(int nativeCanvas) {
93        if (nativeCanvas == 0) {
94            throw new IllegalStateException();
95        }
96        mNativeCanvas = nativeCanvas;
97        mDensity = Bitmap.getDefaultDensity();
98    }
99
100    /**
101     * Construct a canvas with the specified gl context. All drawing through
102     * this canvas will be redirected to OpenGL. Note: some features may not
103     * be supported in this mode (e.g. some GL implementations may not support
104     * antialiasing or certain effects like ColorMatrix or certain Xfermodes).
105     * However, no exception will be thrown in those cases.
106     *
107     * <p>The initial target density of the canvas is the same as the initial
108     * density of bitmaps as per {@link Bitmap#getDensity() Bitmap.getDensity()}.
109     */
110    public Canvas(GL gl) {
111        mNativeCanvas = initGL();
112        mGL = gl;
113        mDensity = Bitmap.getDefaultDensity();
114    }
115
116    /**
117     * Return the GL object associated with this canvas, or null if it is not
118     * backed by GL.
119     */
120    public GL getGL() {
121        return mGL;
122    }
123
124    /**
125     * Call this to free up OpenGL resources that may be cached or allocated
126     * on behalf of the Canvas. Any subsequent drawing with a GL-backed Canvas
127     * will have to recreate those resources.
128     */
129    public static void freeGlCaches() {
130        freeCaches();
131    }
132
133    /**
134     * Specify a bitmap for the canvas to draw into.  As a side-effect, also
135     * updates the canvas's target density to match that of the bitmap.
136     *
137     * @param bitmap Specifies a mutable bitmap for the canvas to draw into.
138     *
139     * @see #setDensity(int)
140     * @see #getDensity()
141     */
142    public void setBitmap(Bitmap bitmap) {
143        if (!bitmap.isMutable()) {
144            throw new IllegalStateException();
145        }
146        if (mGL != null) {
147            throw new RuntimeException("Can't set a bitmap device on a GL canvas");
148        }
149        throwIfRecycled(bitmap);
150
151        native_setBitmap(mNativeCanvas, bitmap.ni());
152        mBitmap = bitmap;
153        mDensity = bitmap.mDensity;
154    }
155
156    /**
157     * Set the viewport dimensions if this canvas is GL based. If it is not,
158     * this method is ignored and no exception is thrown.
159     *
160     *  @param width    The width of the viewport
161     *  @param height   The height of the viewport
162     */
163    public void setViewport(int width, int height) {
164        if (mGL != null) {
165            nativeSetViewport(mNativeCanvas, width, height);
166        }
167    }
168
169    /**
170     * Return true if the device that the current layer draws into is opaque
171     * (i.e. does not support per-pixel alpha).
172     *
173     * @return true if the device that the current layer draws into is opaque
174     */
175    public native boolean isOpaque();
176
177    /**
178     * Returns the width of the current drawing layer
179     *
180     * @return the width of the current drawing layer
181     */
182    public native int getWidth();
183
184    /**
185     * Returns the height of the current drawing layer
186     *
187     * @return the height of the current drawing layer
188     */
189    public native int getHeight();
190
191    /**
192     * <p>Returns the target density of the canvas.  The default density is
193     * derived from the density of its backing bitmap, or
194     * {@link Bitmap#DENSITY_NONE} if there is not one.</p>
195     *
196     * @return Returns the current target density of the canvas, which is used
197     * to determine the scaling factor when drawing a bitmap into it.
198     *
199     * @see #setDensity(int)
200     * @see Bitmap#getDensity()
201     */
202    public int getDensity() {
203        return mDensity;
204    }
205
206    /**
207     * <p>Specifies the density for this Canvas' backing bitmap.  This modifies
208     * the target density of the canvas itself, as well as the density of its
209     * backing bitmap via {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}.
210     *
211     * @param density The new target density of the canvas, which is used
212     * to determine the scaling factor when drawing a bitmap into it.  Use
213     * {@link Bitmap#DENSITY_NONE} to disable bitmap scaling.
214     *
215     * @see #getDensity()
216     * @see Bitmap#setDensity(int)
217     */
218    public void setDensity(int density) {
219        if (mBitmap != null) {
220            mBitmap.setDensity(density);
221        }
222        mDensity = density;
223    }
224
225    /** @hide */
226    public void setScreenDensity(int density) {
227        mScreenDensity = density;
228    }
229
230    // the SAVE_FLAG constants must match their native equivalents
231
232    /** restore the current matrix when restore() is called */
233    public static final int MATRIX_SAVE_FLAG = 0x01;
234    /** restore the current clip when restore() is called */
235    public static final int CLIP_SAVE_FLAG = 0x02;
236    /** the layer needs to per-pixel alpha */
237    public static final int HAS_ALPHA_LAYER_SAVE_FLAG = 0x04;
238    /** the layer needs to 8-bits per color component */
239    public static final int FULL_COLOR_LAYER_SAVE_FLAG = 0x08;
240    /** clip against the layer's bounds */
241    public static final int CLIP_TO_LAYER_SAVE_FLAG = 0x10;
242    /** restore everything when restore() is called */
243    public static final int ALL_SAVE_FLAG = 0x1F;
244
245    /**
246     * Saves the current matrix and clip onto a private stack. Subsequent
247     * calls to translate,scale,rotate,skew,concat or clipRect,clipPath
248     * will all operate as usual, but when the balancing call to restore()
249     * is made, those calls will be forgotten, and the settings that existed
250     * before the save() will be reinstated.
251     *
252     * @return The value to pass to restoreToCount() to balance this save()
253     */
254    public native int save();
255
256    /**
257     * Based on saveFlags, can save the current matrix and clip onto a private
258     * stack. Subsequent calls to translate,scale,rotate,skew,concat or
259     * clipRect,clipPath will all operate as usual, but when the balancing
260     * call to restore() is made, those calls will be forgotten, and the
261     * settings that existed before the save() will be reinstated.
262     *
263     * @param saveFlags flag bits that specify which parts of the Canvas state
264     *                  to save/restore
265     * @return The value to pass to restoreToCount() to balance this save()
266     */
267    public native int save(int saveFlags);
268
269    /**
270     * This behaves the same as save(), but in addition it allocates an
271     * offscreen bitmap. All drawing calls are directed there, and only when
272     * the balancing call to restore() is made is that offscreen transfered to
273     * the canvas (or the previous layer). Subsequent calls to translate,
274     * scale, rotate, skew, concat or clipRect, clipPath all operate on this
275     * copy. When the balancing call to restore() is made, this copy is
276     * deleted and the previous matrix/clip state is restored.
277     *
278     * @param bounds May be null. The maximum size the offscreen bitmap
279     *               needs to be (in local coordinates)
280     * @param paint  This is copied, and is applied to the offscreen when
281     *               restore() is called.
282     * @param saveFlags  see _SAVE_FLAG constants
283     * @return       value to pass to restoreToCount() to balance this save()
284     */
285    public int saveLayer(RectF bounds, Paint paint, int saveFlags) {
286        return native_saveLayer(mNativeCanvas, bounds,
287                                paint != null ? paint.mNativePaint : 0,
288                                saveFlags);
289    }
290
291    /**
292     * Helper version of saveLayer() that takes 4 values rather than a RectF.
293     */
294    public int saveLayer(float left, float top, float right, float bottom,
295                         Paint paint, int saveFlags) {
296        return native_saveLayer(mNativeCanvas, left, top, right, bottom,
297                                paint != null ? paint.mNativePaint : 0,
298                                saveFlags);
299    }
300
301    /**
302     * This behaves the same as save(), but in addition it allocates an
303     * offscreen bitmap. All drawing calls are directed there, and only when
304     * the balancing call to restore() is made is that offscreen transfered to
305     * the canvas (or the previous layer). Subsequent calls to translate,
306     * scale, rotate, skew, concat or clipRect, clipPath all operate on this
307     * copy. When the balancing call to restore() is made, this copy is
308     * deleted and the previous matrix/clip state is restored.
309     *
310     * @param bounds    The maximum size the offscreen bitmap needs to be
311     *                  (in local coordinates)
312     * @param alpha     The alpha to apply to the offscreen when when it is
313                        drawn during restore()
314     * @param saveFlags see _SAVE_FLAG constants
315     * @return          value to pass to restoreToCount() to balance this call
316     */
317    public int saveLayerAlpha(RectF bounds, int alpha, int saveFlags) {
318        alpha = Math.min(255, Math.max(0, alpha));
319        return native_saveLayerAlpha(mNativeCanvas, bounds, alpha, saveFlags);
320    }
321
322    /**
323     * Helper for saveLayerAlpha() that takes 4 values instead of a RectF.
324     */
325    public int saveLayerAlpha(float left, float top, float right, float bottom,
326                              int alpha, int saveFlags) {
327        return native_saveLayerAlpha(mNativeCanvas, left, top, right, bottom,
328                                     alpha, saveFlags);
329    }
330
331    /**
332     * This call balances a previous call to save(), and is used to remove all
333     * modifications to the matrix/clip state since the last save call. It is
334     * an error to call restore() more times than save() was called.
335     */
336    public native void restore();
337
338    /**
339     * Returns the number of matrix/clip states on the Canvas' private stack.
340     * This will equal # save() calls - # restore() calls.
341     */
342    public native int getSaveCount();
343
344    /**
345     * Efficient way to pop any calls to save() that happened after the save
346     * count reached saveCount. It is an error for saveCount to be less than 1.
347     *
348     * Example:
349     *    int count = canvas.save();
350     *    ... // more calls potentially to save()
351     *    canvas.restoreToCount(count);
352     *    // now the canvas is back in the same state it was before the initial
353     *    // call to save().
354     *
355     * @param saveCount The save level to restore to.
356     */
357    public native void restoreToCount(int saveCount);
358
359    /**
360     * Preconcat the current matrix with the specified translation
361     *
362     * @param dx The distance to translate in X
363     * @param dy The distance to translate in Y
364    */
365    public native void translate(float dx, float dy);
366
367    /**
368     * Preconcat the current matrix with the specified scale.
369     *
370     * @param sx The amount to scale in X
371     * @param sy The amount to scale in Y
372     */
373    public native void scale(float sx, float sy);
374
375    /**
376     * Preconcat the current matrix with the specified scale.
377     *
378     * @param sx The amount to scale in X
379     * @param sy The amount to scale in Y
380     * @param px The x-coord for the pivot point (unchanged by the rotation)
381     * @param py The y-coord for the pivot point (unchanged by the rotation)
382     */
383    public final void scale(float sx, float sy, float px, float py) {
384        translate(px, py);
385        scale(sx, sy);
386        translate(-px, -py);
387    }
388
389    /**
390     * Preconcat the current matrix with the specified rotation.
391     *
392     * @param degrees The amount to rotate, in degrees
393     */
394    public native void rotate(float degrees);
395
396    /**
397     * Preconcat the current matrix with the specified rotation.
398     *
399     * @param degrees The amount to rotate, in degrees
400     * @param px The x-coord for the pivot point (unchanged by the rotation)
401     * @param py The y-coord for the pivot point (unchanged by the rotation)
402     */
403    public final void rotate(float degrees, float px, float py) {
404        translate(px, py);
405        rotate(degrees);
406        translate(-px, -py);
407    }
408
409    /**
410     * Preconcat the current matrix with the specified skew.
411     *
412     * @param sx The amount to skew in X
413     * @param sy The amount to skew in Y
414     */
415    public native void skew(float sx, float sy);
416
417    /**
418     * Preconcat the current matrix with the specified matrix.
419     *
420     * @param matrix The matrix to preconcatenate with the current matrix
421     */
422    public void concat(Matrix matrix) {
423        native_concat(mNativeCanvas, matrix.native_instance);
424    }
425
426    /**
427     * Completely replace the current matrix with the specified matrix. If the
428     * matrix parameter is null, then the current matrix is reset to identity.
429     *
430     * @param matrix The matrix to replace the current matrix with. If it is
431     *               null, set the current matrix to identity.
432     */
433    public void setMatrix(Matrix matrix) {
434        native_setMatrix(mNativeCanvas,
435                         matrix == null ? 0 : matrix.native_instance);
436    }
437
438    /**
439     * Return, in ctm, the current transformation matrix. This does not alter
440     * the matrix in the canvas, but just returns a copy of it.
441     */
442    public void getMatrix(Matrix ctm) {
443        native_getCTM(mNativeCanvas, ctm.native_instance);
444    }
445
446    /**
447     * Return a new matrix with a copy of the canvas' current transformation
448     * matrix.
449     */
450    public final Matrix getMatrix() {
451        Matrix m = new Matrix();
452        getMatrix(m);
453        return m;
454    }
455
456    /**
457     * Modify the current clip with the specified rectangle.
458     *
459     * @param rect The rect to intersect with the current clip
460     * @param op How the clip is modified
461     * @return true if the resulting clip is non-empty
462     */
463    public boolean clipRect(RectF rect, Region.Op op) {
464        return native_clipRect(mNativeCanvas,
465                               rect.left, rect.top, rect.right, rect.bottom,
466                               op.nativeInt);
467    }
468
469    /**
470     * Modify the current clip with the specified rectangle, which is
471     * expressed in local coordinates.
472     *
473     * @param rect The rectangle to intersect with the current clip.
474     * @param op How the clip is modified
475     * @return true if the resulting clip is non-empty
476     */
477    public boolean clipRect(Rect rect, Region.Op op) {
478        return native_clipRect(mNativeCanvas,
479                               rect.left, rect.top, rect.right, rect.bottom,
480                               op.nativeInt);
481    }
482
483    /**
484     * Intersect the current clip with the specified rectangle, which is
485     * expressed in local coordinates.
486     *
487     * @param rect The rectangle to intersect with the current clip.
488     * @return true if the resulting clip is non-empty
489     */
490    public native boolean clipRect(RectF rect);
491
492    /**
493     * Intersect the current clip with the specified rectangle, which is
494     * expressed in local coordinates.
495     *
496     * @param rect The rectangle to intersect with the current clip.
497     * @return true if the resulting clip is non-empty
498     */
499    public native boolean clipRect(Rect rect);
500
501    /**
502     * Modify the current clip with the specified rectangle, which is
503     * expressed in local coordinates.
504     *
505     * @param left   The left side of the rectangle to intersect with the
506     *               current clip
507     * @param top    The top of the rectangle to intersect with the current
508     *               clip
509     * @param right  The right side of the rectangle to intersect with the
510     *               current clip
511     * @param bottom The bottom of the rectangle to intersect with the current
512     *               clip
513     * @param op     How the clip is modified
514     * @return       true if the resulting clip is non-empty
515     */
516    public boolean clipRect(float left, float top, float right, float bottom,
517                            Region.Op op) {
518        return native_clipRect(mNativeCanvas, left, top, right, bottom,
519                               op.nativeInt);
520    }
521
522    /**
523     * Intersect the current clip with the specified rectangle, which is
524     * expressed in local coordinates.
525     *
526     * @param left   The left side of the rectangle to intersect with the
527     *               current clip
528     * @param top    The top of the rectangle to intersect with the current clip
529     * @param right  The right side of the rectangle to intersect with the
530     *               current clip
531     * @param bottom The bottom of the rectangle to intersect with the current
532     *               clip
533     * @return       true if the resulting clip is non-empty
534     */
535    public native boolean clipRect(float left, float top,
536                                   float right, float bottom);
537
538    /**
539     * Intersect the current clip with the specified rectangle, which is
540     * expressed in local coordinates.
541     *
542     * @param left   The left side of the rectangle to intersect with the
543     *               current clip
544     * @param top    The top of the rectangle to intersect with the current clip
545     * @param right  The right side of the rectangle to intersect with the
546     *               current clip
547     * @param bottom The bottom of the rectangle to intersect with the current
548     *               clip
549     * @return       true if the resulting clip is non-empty
550     */
551    public native boolean clipRect(int left, int top,
552                                   int right, int bottom);
553
554    /**
555        * Modify the current clip with the specified path.
556     *
557     * @param path The path to operate on the current clip
558     * @param op   How the clip is modified
559     * @return     true if the resulting is non-empty
560     */
561    public boolean clipPath(Path path, Region.Op op) {
562        return native_clipPath(mNativeCanvas, path.ni(), op.nativeInt);
563    }
564
565    /**
566     * Intersect the current clip with the specified path.
567     *
568     * @param path The path to intersect with the current clip
569     * @return     true if the resulting is non-empty
570     */
571    public boolean clipPath(Path path) {
572        return clipPath(path, Region.Op.INTERSECT);
573    }
574
575    /**
576     * Modify the current clip with the specified region. Note that unlike
577     * clipRect() and clipPath() which transform their arguments by the
578     * current matrix, clipRegion() assumes its argument is already in the
579     * coordinate system of the current layer's bitmap, and so not
580     * transformation is performed.
581     *
582     * @param region The region to operate on the current clip, based on op
583     * @param op How the clip is modified
584     * @return true if the resulting is non-empty
585     */
586    public boolean clipRegion(Region region, Region.Op op) {
587        return native_clipRegion(mNativeCanvas, region.ni(), op.nativeInt);
588    }
589
590    /**
591     * Intersect the current clip with the specified region. Note that unlike
592     * clipRect() and clipPath() which transform their arguments by the
593     * current matrix, clipRegion() assumes its argument is already in the
594     * coordinate system of the current layer's bitmap, and so not
595     * transformation is performed.
596     *
597     * @param region The region to operate on the current clip, based on op
598     * @return true if the resulting is non-empty
599     */
600    public boolean clipRegion(Region region) {
601        return clipRegion(region, Region.Op.INTERSECT);
602    }
603
604    public DrawFilter getDrawFilter() {
605        return mDrawFilter;
606    }
607
608    public void setDrawFilter(DrawFilter filter) {
609        int nativeFilter = 0;
610        if (filter != null) {
611            nativeFilter = filter.mNativeInt;
612        }
613        mDrawFilter = filter;
614        nativeSetDrawFilter(mNativeCanvas, nativeFilter);
615    }
616
617    public enum EdgeType {
618        BW(0),  //!< treat edges by just rounding to nearest pixel boundary
619        AA(1);  //!< treat edges by rounding-out, since they may be antialiased
620
621        EdgeType(int nativeInt) {
622            this.nativeInt = nativeInt;
623        }
624        final int nativeInt;
625    }
626
627    /**
628     * Return true if the specified rectangle, after being transformed by the
629     * current matrix, would lie completely outside of the current clip. Call
630     * this to check if an area you intend to draw into is clipped out (and
631     * therefore you can skip making the draw calls).
632     *
633     * @param rect  the rect to compare with the current clip
634     * @param type  specifies how to treat the edges (BW or antialiased)
635     * @return      true if the rect (transformed by the canvas' matrix)
636     *              does not intersect with the canvas' clip
637     */
638    public boolean quickReject(RectF rect, EdgeType type) {
639        return native_quickReject(mNativeCanvas, rect, type.nativeInt);
640    }
641
642    /**
643     * Return true if the specified path, after being transformed by the
644     * current matrix, would lie completely outside of the current clip. Call
645     * this to check if an area you intend to draw into is clipped out (and
646     * therefore you can skip making the draw calls). Note: for speed it may
647     * return false even if the path itself might not intersect the clip
648     * (i.e. the bounds of the path intersects, but the path does not).
649     *
650     * @param path        The path to compare with the current clip
651     * @param type        true if the path should be considered antialiased,
652     *                    since that means it may
653     *                    affect a larger area (more pixels) than
654     *                    non-antialiased.
655     * @return            true if the path (transformed by the canvas' matrix)
656     *                    does not intersect with the canvas' clip
657     */
658    public boolean quickReject(Path path, EdgeType type) {
659        return native_quickReject(mNativeCanvas, path.ni(), type.nativeInt);
660    }
661
662    /**
663     * Return true if the specified rectangle, after being transformed by the
664     * current matrix, would lie completely outside of the current clip. Call
665     * this to check if an area you intend to draw into is clipped out (and
666     * therefore you can skip making the draw calls).
667     *
668     * @param left        The left side of the rectangle to compare with the
669     *                    current clip
670     * @param top         The top of the rectangle to compare with the current
671     *                    clip
672     * @param right       The right side of the rectangle to compare with the
673     *                    current clip
674     * @param bottom      The bottom of the rectangle to compare with the
675     *                    current clip
676     * @param type        true if the rect should be considered antialiased,
677     *                    since that means it may affect a larger area (more
678     *                    pixels) than non-antialiased.
679     * @return            true if the rect (transformed by the canvas' matrix)
680     *                    does not intersect with the canvas' clip
681     */
682    public boolean quickReject(float left, float top, float right, float bottom,
683                               EdgeType type) {
684        return native_quickReject(mNativeCanvas, left, top, right, bottom,
685                                  type.nativeInt);
686    }
687
688    /**
689     * Retrieve the clip bounds, returning true if they are non-empty.
690     *
691     * @param bounds Return the clip bounds here. If it is null, ignore it but
692     *               still return true if the current clip is non-empty.
693     * @return true if the current clip is non-empty.
694     */
695    public boolean getClipBounds(Rect bounds) {
696        return native_getClipBounds(mNativeCanvas, bounds);
697    }
698
699    /**
700     * Retrieve the clip bounds.
701     *
702     * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty.
703     */
704    public final Rect getClipBounds() {
705        Rect r = new Rect();
706        getClipBounds(r);
707        return r;
708    }
709
710    /**
711     * Fill the entire canvas' bitmap (restricted to the current clip) with the
712     * specified RGB color, using srcover porterduff mode.
713     *
714     * @param r red component (0..255) of the color to draw onto the canvas
715     * @param g green component (0..255) of the color to draw onto the canvas
716     * @param b blue component (0..255) of the color to draw onto the canvas
717     */
718    public void drawRGB(int r, int g, int b) {
719        native_drawRGB(mNativeCanvas, r, g, b);
720    }
721
722    /**
723     * Fill the entire canvas' bitmap (restricted to the current clip) with the
724     * specified ARGB color, using srcover porterduff mode.
725     *
726     * @param a alpha component (0..255) of the color to draw onto the canvas
727     * @param r red component (0..255) of the color to draw onto the canvas
728     * @param g green component (0..255) of the color to draw onto the canvas
729     * @param b blue component (0..255) of the color to draw onto the canvas
730     */
731    public void drawARGB(int a, int r, int g, int b) {
732        native_drawARGB(mNativeCanvas, a, r, g, b);
733    }
734
735    /**
736     * Fill the entire canvas' bitmap (restricted to the current clip) with the
737     * specified color, using srcover porterduff mode.
738     *
739     * @param color the color to draw onto the canvas
740     */
741    public void drawColor(int color) {
742        native_drawColor(mNativeCanvas, color);
743    }
744
745    /**
746     * Fill the entire canvas' bitmap (restricted to the current clip) with the
747     * specified color and porter-duff xfermode.
748     *
749     * @param color the color to draw with
750     * @param mode  the porter-duff mode to apply to the color
751     */
752    public void drawColor(int color, PorterDuff.Mode mode) {
753        native_drawColor(mNativeCanvas, color, mode.nativeInt);
754    }
755
756    /**
757     * Fill the entire canvas' bitmap (restricted to the current clip) with
758     * the specified paint. This is equivalent (but faster) to drawing an
759     * infinitely large rectangle with the specified paint.
760     *
761     * @param paint The paint used to draw onto the canvas
762     */
763    public void drawPaint(Paint paint) {
764        native_drawPaint(mNativeCanvas, paint.mNativePaint);
765    }
766
767    /**
768     * Draw a series of points. Each point is centered at the coordinate
769     * specified by pts[], and its diameter is specified by the paint's stroke
770     * width (as transformed by the canvas' CTM), with special treatment for
771     * a stroke width of 0, which always draws exactly 1 pixel (or at most 4
772     * if antialiasing is enabled). The shape of the point is controlled by
773     * the paint's Cap type. The shape is a square, unless the cap type is
774     * Round, in which case the shape is a circle.
775     *
776     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
777     * @param offset   Number of values to skip before starting to draw.
778     * @param count    The number of values to process, after skipping offset
779     *                 of them. Since one point uses two values, the number of
780     *                 "points" that are drawn is really (count >> 1).
781     * @param paint    The paint used to draw the points
782     */
783    public native void drawPoints(float[] pts, int offset, int count,
784                                  Paint paint);
785
786    /**
787     * Helper for drawPoints() that assumes you want to draw the entire array
788     */
789    public void drawPoints(float[] pts, Paint paint) {
790        drawPoints(pts, 0, pts.length, paint);
791    }
792
793    /**
794     * Helper for drawPoints() for drawing a single point.
795     */
796    public native void drawPoint(float x, float y, Paint paint);
797
798    /**
799     * Draw a line segment with the specified start and stop x,y coordinates,
800     * using the specified paint. NOTE: since a line is always "framed", the
801     * Style is ignored in the paint.
802     *
803     * @param startX The x-coordinate of the start point of the line
804     * @param startY The y-coordinate of the start point of the line
805     * @param paint  The paint used to draw the line
806     */
807    public void drawLine(float startX, float startY, float stopX, float stopY,
808                         Paint paint) {
809        native_drawLine(mNativeCanvas, startX, startY, stopX, stopY,
810                        paint.mNativePaint);
811    }
812
813    /**
814     * Draw a series of lines. Each line is taken from 4 consecutive values
815     * in the pts array. Thus to draw 1 line, the array must contain at least 4
816     * values. This is logically the same as drawing the array as follows:
817     * drawLine(pts[0], pts[1], pts[2], pts[3]) followed by
818     * drawLine(pts[4], pts[5], pts[6], pts[7]) and so on.
819     *
820     * @param pts      Array of points to draw [x0 y0 x1 y1 x2 y2 ...]
821     * @param offset   Number of values in the array to skip before drawing.
822     * @param count    The number of values in the array to process, after
823     *                 skipping "offset" of them. Since each line uses 4 values,
824     *                 the number of "lines" that are drawn is really
825     *                 (count >> 2).
826     * @param paint    The paint used to draw the points
827     */
828    public native void drawLines(float[] pts, int offset, int count,
829                                 Paint paint);
830
831    public void drawLines(float[] pts, Paint paint) {
832        drawLines(pts, 0, pts.length, paint);
833    }
834
835    /**
836     * Draw the specified Rect using the specified paint. The rectangle will
837     * be filled or framed based on the Style in the paint.
838     *
839     * @param rect  The rect to be drawn
840     * @param paint The paint used to draw the rect
841     */
842    public void drawRect(RectF rect, Paint paint) {
843        native_drawRect(mNativeCanvas, rect, paint.mNativePaint);
844    }
845
846    /**
847     * Draw the specified Rect using the specified Paint. The rectangle
848     * will be filled or framed based on the Style in the paint.
849     *
850     * @param r        The rectangle to be drawn.
851     * @param paint    The paint used to draw the rectangle
852     */
853    public void drawRect(Rect r, Paint paint) {
854        drawRect(r.left, r.top, r.right, r.bottom, paint);
855    }
856
857
858    /**
859     * Draw the specified Rect using the specified paint. The rectangle will
860     * be filled or framed based on the Style in the paint.
861     *
862     * @param left   The left side of the rectangle to be drawn
863     * @param top    The top side of the rectangle to be drawn
864     * @param right  The right side of the rectangle to be drawn
865     * @param bottom The bottom side of the rectangle to be drawn
866     * @param paint  The paint used to draw the rect
867     */
868    public void drawRect(float left, float top, float right, float bottom,
869                         Paint paint) {
870        native_drawRect(mNativeCanvas, left, top, right, bottom,
871                        paint.mNativePaint);
872    }
873
874    /**
875     * Draw the specified oval using the specified paint. The oval will be
876     * filled or framed based on the Style in the paint.
877     *
878     * @param oval The rectangle bounds of the oval to be drawn
879     */
880    public void drawOval(RectF oval, Paint paint) {
881        if (oval == null) {
882            throw new NullPointerException();
883        }
884        native_drawOval(mNativeCanvas, oval, paint.mNativePaint);
885    }
886
887    /**
888     * Draw the specified circle using the specified paint. If radius is <= 0,
889     * then nothing will be drawn. The circle will be filled or framed based
890     * on the Style in the paint.
891     *
892     * @param cx     The x-coordinate of the center of the cirle to be drawn
893     * @param cy     The y-coordinate of the center of the cirle to be drawn
894     * @param radius The radius of the cirle to be drawn
895     * @param paint  The paint used to draw the circle
896     */
897    public void drawCircle(float cx, float cy, float radius, Paint paint) {
898        native_drawCircle(mNativeCanvas, cx, cy, radius,
899                          paint.mNativePaint);
900    }
901
902    /**
903     * Draw the specified arc, which will be scaled to fit inside the
904     * specified oval. If the sweep angle is >= 360, then the oval is drawn
905     * completely. Note that this differs slightly from SkPath::arcTo, which
906     * treats the sweep angle mod 360.
907     *
908     * @param oval       The bounds of oval used to define the shape and size
909     *                   of the arc
910     * @param startAngle Starting angle (in degrees) where the arc begins
911     * @param sweepAngle Sweep angle (in degrees) measured clockwise
912     * @param useCenter If true, include the center of the oval in the arc, and
913                        close it if it is being stroked. This will draw a wedge
914     * @param paint      The paint used to draw the arc
915     */
916    public void drawArc(RectF oval, float startAngle, float sweepAngle,
917                        boolean useCenter, Paint paint) {
918        if (oval == null) {
919            throw new NullPointerException();
920        }
921        native_drawArc(mNativeCanvas, oval, startAngle, sweepAngle,
922                       useCenter, paint.mNativePaint);
923    }
924
925    /**
926     * Draw the specified round-rect using the specified paint. The roundrect
927     * will be filled or framed based on the Style in the paint.
928     *
929     * @param rect  The rectangular bounds of the roundRect to be drawn
930     * @param rx    The x-radius of the oval used to round the corners
931     * @param ry    The y-radius of the oval used to round the corners
932     * @param paint The paint used to draw the roundRect
933     */
934    public void drawRoundRect(RectF rect, float rx, float ry, Paint paint) {
935        if (rect == null) {
936            throw new NullPointerException();
937        }
938        native_drawRoundRect(mNativeCanvas, rect, rx, ry,
939                             paint.mNativePaint);
940    }
941
942    /**
943     * Draw the specified path using the specified paint. The path will be
944     * filled or framed based on the Style in the paint.
945     *
946     * @param path  The path to be drawn
947     * @param paint The paint used to draw the path
948     */
949    public void drawPath(Path path, Paint paint) {
950        native_drawPath(mNativeCanvas, path.ni(), paint.mNativePaint);
951    }
952
953    private static void throwIfRecycled(Bitmap bitmap) {
954        if (bitmap.isRecycled()) {
955            throw new RuntimeException(
956                        "Canvas: trying to use a recycled bitmap " + bitmap);
957        }
958    }
959
960    /**
961     * Draw the specified bitmap, with its top/left corner at (x,y), using
962     * the specified paint, transformed by the current matrix.
963     *
964     * <p>Note: if the paint contains a maskfilter that generates a mask which
965     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
966     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
967     * Thus the color outside of the original width/height will be the edge
968     * color replicated.
969     *
970     * <p>If the bitmap and canvas have different densities, this function
971     * will take care of automatically scaling the bitmap to draw at the
972     * same density as the canvas.
973     *
974     * @param bitmap The bitmap to be drawn
975     * @param left   The position of the left side of the bitmap being drawn
976     * @param top    The position of the top side of the bitmap being drawn
977     * @param paint  The paint used to draw the bitmap (may be null)
978     */
979    public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
980        throwIfRecycled(bitmap);
981        native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top,
982                paint != null ? paint.mNativePaint : 0, mDensity, mScreenDensity,
983                bitmap.mDensity);
984    }
985
986    /**
987     * Draw the specified bitmap, scaling/translating automatically to fill
988     * the destination rectangle. If the source rectangle is not null, it
989     * specifies the subset of the bitmap to draw.
990     *
991     * <p>Note: if the paint contains a maskfilter that generates a mask which
992     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
993     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
994     * Thus the color outside of the original width/height will be the edge
995     * color replicated.
996     *
997     * <p>This function <em>ignores the density associated with the bitmap</em>.
998     * This is because the source and destination rectangle coordinate
999     * spaces are in their respective densities, so must already have the
1000     * appropriate scaling factor applied.
1001     *
1002     * @param bitmap The bitmap to be drawn
1003     * @param src    May be null. The subset of the bitmap to be drawn
1004     * @param dst    The rectangle that the bitmap will be scaled/translated
1005     *               to fit into
1006     * @param paint  May be null. The paint used to draw the bitmap
1007     */
1008    public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) {
1009        if (dst == null) {
1010            throw new NullPointerException();
1011        }
1012        throwIfRecycled(bitmap);
1013        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1014                          paint != null ? paint.mNativePaint : 0,
1015                          mScreenDensity, bitmap.mDensity);
1016    }
1017
1018    /**
1019     * Draw the specified bitmap, scaling/translating automatically to fill
1020     * the destination rectangle. If the source rectangle is not null, it
1021     * specifies the subset of the bitmap to draw.
1022     *
1023     * <p>Note: if the paint contains a maskfilter that generates a mask which
1024     * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
1025     * then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
1026     * Thus the color outside of the original width/height will be the edge
1027     * color replicated.
1028     *
1029     * <p>This function <em>ignores the density associated with the bitmap</em>.
1030     * This is because the source and destination rectangle coordinate
1031     * spaces are in their respective densities, so must already have the
1032     * appropriate scaling factor applied.
1033     *
1034     * @param bitmap The bitmap to be drawn
1035     * @param src    May be null. The subset of the bitmap to be drawn
1036     * @param dst    The rectangle that the bitmap will be scaled/translated
1037     *               to fit into
1038     * @param paint  May be null. The paint used to draw the bitmap
1039     */
1040    public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) {
1041        if (dst == null) {
1042            throw new NullPointerException();
1043        }
1044        throwIfRecycled(bitmap);
1045        native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst,
1046                          paint != null ? paint.mNativePaint : 0,
1047                          mScreenDensity, bitmap.mDensity);
1048    }
1049
1050    /**
1051     * Treat the specified array of colors as a bitmap, and draw it. This gives
1052     * the same result as first creating a bitmap from the array, and then
1053     * drawing it, but this method avoids explicitly creating a bitmap object
1054     * which can be more efficient if the colors are changing often.
1055     *
1056     * @param colors Array of colors representing the pixels of the bitmap
1057     * @param offset Offset into the array of colors for the first pixel
1058     * @param stride The number of of colors in the array between rows (must be
1059     *               >= width or <= -width).
1060     * @param x The X coordinate for where to draw the bitmap
1061     * @param y The Y coordinate for where to draw the bitmap
1062     * @param width The width of the bitmap
1063     * @param height The height of the bitmap
1064     * @param hasAlpha True if the alpha channel of the colors contains valid
1065     *                 values. If false, the alpha byte is ignored (assumed to
1066     *                 be 0xFF for every pixel).
1067     * @param paint  May be null. The paint used to draw the bitmap
1068     */
1069    public void drawBitmap(int[] colors, int offset, int stride, float x,
1070                           float y, int width, int height, boolean hasAlpha,
1071                           Paint paint) {
1072        // check for valid input
1073        if (width < 0) {
1074            throw new IllegalArgumentException("width must be >= 0");
1075        }
1076        if (height < 0) {
1077            throw new IllegalArgumentException("height must be >= 0");
1078        }
1079        if (Math.abs(stride) < width) {
1080            throw new IllegalArgumentException("abs(stride) must be >= width");
1081        }
1082        int lastScanline = offset + (height - 1) * stride;
1083        int length = colors.length;
1084        if (offset < 0 || (offset + width > length) || lastScanline < 0
1085                || (lastScanline + width > length)) {
1086            throw new ArrayIndexOutOfBoundsException();
1087        }
1088        // quick escape if there's nothing to draw
1089        if (width == 0 || height == 0) {
1090            return;
1091        }
1092        // punch down to native for the actual draw
1093        native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha,
1094                paint != null ? paint.mNativePaint : 0);
1095    }
1096
1097    /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y
1098     */
1099    public void drawBitmap(int[] colors, int offset, int stride, int x, int y,
1100                           int width, int height, boolean hasAlpha,
1101                           Paint paint) {
1102        // call through to the common float version
1103        drawBitmap(colors, offset, stride, (float)x, (float)y, width, height,
1104                   hasAlpha, paint);
1105    }
1106
1107    /**
1108     * Draw the bitmap using the specified matrix.
1109     *
1110     * @param bitmap The bitmap to draw
1111     * @param matrix The matrix used to transform the bitmap when it is drawn
1112     * @param paint  May be null. The paint used to draw the bitmap
1113     */
1114    public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
1115        nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(),
1116                paint != null ? paint.mNativePaint : 0);
1117    }
1118
1119    private static void checkRange(int length, int offset, int count) {
1120        if ((offset | count) < 0 || offset + count > length) {
1121            throw new ArrayIndexOutOfBoundsException();
1122        }
1123    }
1124
1125    /**
1126     * Draw the bitmap through the mesh, where mesh vertices are evenly
1127     * distributed across the bitmap. There are meshWidth+1 vertices across, and
1128     * meshHeight+1 vertices down. The verts array is accessed in row-major
1129     * order, so that the first meshWidth+1 vertices are distributed across the
1130     * top of the bitmap from left to right. A more general version of this
1131     * methid is drawVertices().
1132     *
1133     * @param bitmap The bitmap to draw using the mesh
1134     * @param meshWidth The number of columns in the mesh. Nothing is drawn if
1135     *                  this is 0
1136     * @param meshHeight The number of rows in the mesh. Nothing is drawn if
1137     *                   this is 0
1138     * @param verts Array of x,y pairs, specifying where the mesh should be
1139     *              drawn. There must be at least
1140     *              (meshWidth+1) * (meshHeight+1) * 2 + meshOffset values
1141     *              in the array
1142     * @param vertOffset Number of verts elements to skip before drawing
1143     * @param colors May be null. Specifies a color at each vertex, which is
1144     *               interpolated across the cell, and whose values are
1145     *               multiplied by the corresponding bitmap colors. If not null,
1146     *               there must be at least (meshWidth+1) * (meshHeight+1) +
1147     *               colorOffset values in the array.
1148     * @param colorOffset Number of color elements to skip before drawing
1149     * @param paint  May be null. The paint used to draw the bitmap
1150     */
1151    public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight,
1152                               float[] verts, int vertOffset,
1153                               int[] colors, int colorOffset, Paint paint) {
1154        if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) {
1155            throw new ArrayIndexOutOfBoundsException();
1156        }
1157        if (meshWidth == 0 || meshHeight == 0) {
1158            return;
1159        }
1160        int count = (meshWidth + 1) * (meshHeight + 1);
1161        // we mul by 2 since we need two floats per vertex
1162        checkRange(verts.length, vertOffset, count * 2);
1163        if (colors != null) {
1164            // no mul by 2, since we need only 1 color per vertex
1165            checkRange(colors.length, colorOffset, count);
1166        }
1167        nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight,
1168                             verts, vertOffset, colors, colorOffset,
1169                             paint != null ? paint.mNativePaint : 0);
1170    }
1171
1172    public enum VertexMode {
1173        TRIANGLES(0),
1174        TRIANGLE_STRIP(1),
1175        TRIANGLE_FAN(2);
1176
1177        VertexMode(int nativeInt) {
1178            this.nativeInt = nativeInt;
1179        }
1180        final int nativeInt;
1181    }
1182
1183    /**
1184     * Draw the array of vertices, interpreted as triangles (based on mode). The
1185     * verts array is required, and specifies the x,y pairs for each vertex. If
1186     * texs is non-null, then it is used to specify the coordinate in shader
1187     * coordinates to use at each vertex (the paint must have a shader in this
1188     * case). If there is no texs array, but there is a color array, then each
1189     * color is interpolated across its corresponding triangle in a gradient. If
1190     * both texs and colors arrays are present, then they behave as before, but
1191     * the resulting color at each pixels is the result of multiplying the
1192     * colors from the shader and the color-gradient together. The indices array
1193     * is optional, but if it is present, then it is used to specify the index
1194     * of each triangle, rather than just walking through the arrays in order.
1195     *
1196     * @param mode How to interpret the array of vertices
1197     * @param vertexCount The number of values in the vertices array (and
1198     *      corresponding texs and colors arrays if non-null). Each logical
1199     *      vertex is two values (x, y), vertexCount must be a multiple of 2.
1200     * @param verts Array of vertices for the mesh
1201     * @param vertOffset Number of values in the verts to skip before drawing.
1202     * @param texs May be null. If not null, specifies the coordinates to sample
1203     *      into the current shader (e.g. bitmap tile or gradient)
1204     * @param texOffset Number of values in texs to skip before drawing.
1205     * @param colors May be null. If not null, specifies a color for each
1206     *      vertex, to be interpolated across the triangle.
1207     * @param colorOffset Number of values in colors to skip before drawing.
1208     * @param indices If not null, array of indices to reference into the
1209     *      vertex (texs, colors) array.
1210     * @param indexCount number of entries in the indices array (if not null).
1211     * @param paint Specifies the shader to use if the texs array is non-null.
1212     */
1213    public void drawVertices(VertexMode mode, int vertexCount,
1214                             float[] verts, int vertOffset,
1215                             float[] texs, int texOffset,
1216                             int[] colors, int colorOffset,
1217                             short[] indices, int indexOffset,
1218                             int indexCount, Paint paint) {
1219        checkRange(verts.length, vertOffset, vertexCount);
1220        if (texs != null) {
1221            checkRange(texs.length, texOffset, vertexCount);
1222        }
1223        if (colors != null) {
1224            checkRange(colors.length, colorOffset, vertexCount);
1225        }
1226        if (indices != null) {
1227            checkRange(indices.length, indexOffset, indexCount);
1228        }
1229        nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts,
1230                           vertOffset, texs, texOffset, colors, colorOffset,
1231                          indices, indexOffset, indexCount, paint.mNativePaint);
1232    }
1233
1234    /**
1235     * Draw the text, with origin at (x,y), using the specified paint. The
1236     * origin is interpreted based on the Align setting in the paint.
1237     *
1238     * @param text  The text to be drawn
1239     * @param x     The x-coordinate of the origin of the text being drawn
1240     * @param y     The y-coordinate of the origin of the text being drawn
1241     * @param paint The paint used for the text (e.g. color, size, style)
1242     */
1243    public void drawText(char[] text, int index, int count, float x, float y,
1244                         Paint paint) {
1245        if ((index | count | (index + count) |
1246            (text.length - index - count)) < 0) {
1247            throw new IndexOutOfBoundsException();
1248        }
1249        native_drawText(mNativeCanvas, text, index, count, x, y,
1250                        paint.mNativePaint);
1251    }
1252
1253    /**
1254     * Draw the text, with origin at (x,y), using the specified paint. The
1255     * origin is interpreted based on the Align setting in the paint.
1256     *
1257     * @param text  The text to be drawn
1258     * @param x     The x-coordinate of the origin of the text being drawn
1259     * @param y     The y-coordinate of the origin of the text being drawn
1260     * @param paint The paint used for the text (e.g. color, size, style)
1261     */
1262    public native void drawText(String text, float x, float y, Paint paint);
1263
1264    /**
1265     * Draw the text, with origin at (x,y), using the specified paint.
1266     * The origin is interpreted based on the Align setting in the paint.
1267     *
1268     * @param text  The text to be drawn
1269     * @param start The index of the first character in text to draw
1270     * @param end   (end - 1) is the index of the last character in text to draw
1271     * @param x     The x-coordinate of the origin of the text being drawn
1272     * @param y     The y-coordinate of the origin of the text being drawn
1273     * @param paint The paint used for the text (e.g. color, size, style)
1274     */
1275    public void drawText(String text, int start, int end, float x, float y,
1276                         Paint paint) {
1277        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1278            throw new IndexOutOfBoundsException();
1279        }
1280        native_drawText(mNativeCanvas, text, start, end, x, y,
1281                        paint.mNativePaint);
1282    }
1283
1284    /**
1285     * Draw the specified range of text, specified by start/end, with its
1286     * origin at (x,y), in the specified Paint. The origin is interpreted
1287     * based on the Align setting in the Paint.
1288     *
1289     * @param text     The text to be drawn
1290     * @param start    The index of the first character in text to draw
1291     * @param end      (end - 1) is the index of the last character in text
1292     *                 to draw
1293     * @param x        The x-coordinate of origin for where to draw the text
1294     * @param y        The y-coordinate of origin for where to draw the text
1295     * @param paint The paint used for the text (e.g. color, size, style)
1296     */
1297    public void drawText(CharSequence text, int start, int end, float x,
1298                         float y, Paint paint) {
1299        if (text instanceof String || text instanceof SpannedString ||
1300            text instanceof SpannableString) {
1301            native_drawText(mNativeCanvas, text.toString(), start, end, x, y,
1302                            paint.mNativePaint);
1303        }
1304        else if (text instanceof GraphicsOperations) {
1305            ((GraphicsOperations) text).drawText(this, start, end, x, y,
1306                                                     paint);
1307        }
1308        else {
1309            char[] buf = TemporaryBuffer.obtain(end - start);
1310            TextUtils.getChars(text, start, end, buf, 0);
1311            drawText(buf, 0, end - start, x, y, paint);
1312            TemporaryBuffer.recycle(buf);
1313        }
1314    }
1315
1316    /**
1317     * Draw the text in the array, with each character's origin specified by
1318     * the pos array.
1319     *
1320     * @param text     The text to be drawn
1321     * @param index    The index of the first character to draw
1322     * @param count    The number of characters to draw, starting from index.
1323     * @param pos      Array of [x,y] positions, used to position each
1324     *                 character
1325     * @param paint    The paint used for the text (e.g. color, size, style)
1326     */
1327    public void drawPosText(char[] text, int index, int count, float[] pos,
1328                            Paint paint) {
1329        if (index < 0 || index + count > text.length || count*2 > pos.length) {
1330            throw new IndexOutOfBoundsException();
1331        }
1332        native_drawPosText(mNativeCanvas, text, index, count, pos,
1333                           paint.mNativePaint);
1334    }
1335
1336    /**
1337     * Draw the text in the array, with each character's origin specified by
1338     * the pos array.
1339     *
1340     * @param text  The text to be drawn
1341     * @param pos   Array of [x,y] positions, used to position each character
1342     * @param paint The paint used for the text (e.g. color, size, style)
1343     */
1344    public void drawPosText(String text, float[] pos, Paint paint) {
1345        if (text.length()*2 > pos.length) {
1346            throw new ArrayIndexOutOfBoundsException();
1347        }
1348        native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint);
1349    }
1350
1351    /**
1352     * Draw the text, with origin at (x,y), using the specified paint, along
1353     * the specified path. The paint's Align setting determins where along the
1354     * path to start the text.
1355     *
1356     * @param text     The text to be drawn
1357     * @param path     The path the text should follow for its baseline
1358     * @param hOffset  The distance along the path to add to the text's
1359     *                 starting position
1360     * @param vOffset  The distance above(-) or below(+) the path to position
1361     *                 the text
1362     * @param paint    The paint used for the text (e.g. color, size, style)
1363     */
1364    public void drawTextOnPath(char[] text, int index, int count, Path path,
1365                               float hOffset, float vOffset, Paint paint) {
1366        if (index < 0 || index + count > text.length) {
1367            throw new ArrayIndexOutOfBoundsException();
1368        }
1369        native_drawTextOnPath(mNativeCanvas, text, index, count,
1370                              path.ni(), hOffset, vOffset,
1371                              paint.mNativePaint);
1372    }
1373
1374    /**
1375     * Draw the text, with origin at (x,y), using the specified paint, along
1376     * the specified path. The paint's Align setting determins where along the
1377     * path to start the text.
1378     *
1379     * @param text     The text to be drawn
1380     * @param path     The path the text should follow for its baseline
1381     * @param hOffset  The distance along the path to add to the text's
1382     *                 starting position
1383     * @param vOffset  The distance above(-) or below(+) the path to position
1384     *                 the text
1385     * @param paint    The paint used for the text (e.g. color, size, style)
1386     */
1387    public void drawTextOnPath(String text, Path path, float hOffset,
1388                               float vOffset, Paint paint) {
1389        if (text.length() > 0) {
1390            native_drawTextOnPath(mNativeCanvas, text, path.ni(),
1391                                  hOffset, vOffset, paint.mNativePaint);
1392        }
1393    }
1394
1395    /**
1396     * Save the canvas state, draw the picture, and restore the canvas state.
1397     * This differs from picture.draw(canvas), which does not perform any
1398     * save/restore.
1399     *
1400     * @param picture  The picture to be drawn
1401     */
1402    public void drawPicture(Picture picture) {
1403        picture.endRecording();
1404        native_drawPicture(mNativeCanvas, picture.ni());
1405    }
1406
1407    /**
1408     * Draw the picture, stretched to fit into the dst rectangle.
1409     */
1410    public void drawPicture(Picture picture, RectF dst) {
1411        save();
1412        translate(dst.left, dst.top);
1413        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1414            scale(dst.width() / picture.getWidth(),
1415                  dst.height() / picture.getHeight());
1416        }
1417        drawPicture(picture);
1418        restore();
1419    }
1420
1421    /**
1422     * Draw the picture, stretched to fit into the dst rectangle.
1423     */
1424    public void drawPicture(Picture picture, Rect dst) {
1425        save();
1426        translate(dst.left, dst.top);
1427        if (picture.getWidth() > 0 && picture.getHeight() > 0) {
1428            scale((float)dst.width() / picture.getWidth(),
1429                  (float)dst.height() / picture.getHeight());
1430        }
1431        drawPicture(picture);
1432        restore();
1433    }
1434
1435    protected void finalize() throws Throwable {
1436        super.finalize();
1437        // If the constructor threw an exception before setting mNativeCanvas, the native finalizer
1438        // must not be invoked.
1439        if (mNativeCanvas != 0) {
1440            finalizer(mNativeCanvas);
1441        }
1442    }
1443
1444    /**
1445     * Free up as much memory as possible from private caches (e.g. fonts,
1446     * images)
1447     *
1448     * @hide - for now
1449     */
1450    public static native void freeCaches();
1451
1452    private static native int initRaster(int nativeBitmapOrZero);
1453    private static native int initGL();
1454    private static native void native_setBitmap(int nativeCanvas, int bitmap);
1455    private static native void nativeSetViewport(int nCanvas, int w, int h);
1456    private static native int native_saveLayer(int nativeCanvas, RectF bounds,
1457                                               int paint, int layerFlags);
1458    private static native int native_saveLayer(int nativeCanvas, float l,
1459                                               float t, float r, float b,
1460                                               int paint, int layerFlags);
1461    private static native int native_saveLayerAlpha(int nativeCanvas,
1462                                                    RectF bounds, int alpha,
1463                                                    int layerFlags);
1464    private static native int native_saveLayerAlpha(int nativeCanvas, float l,
1465                                                    float t, float r, float b,
1466                                                    int alpha, int layerFlags);
1467
1468    private static native void native_concat(int nCanvas, int nMatrix);
1469    private static native void native_setMatrix(int nCanvas, int nMatrix);
1470    private static native boolean native_clipRect(int nCanvas,
1471                                                  float left, float top,
1472                                                  float right, float bottom,
1473                                                  int regionOp);
1474    private static native boolean native_clipPath(int nativeCanvas,
1475                                                  int nativePath,
1476                                                  int regionOp);
1477    private static native boolean native_clipRegion(int nativeCanvas,
1478                                                    int nativeRegion,
1479                                                    int regionOp);
1480    private static native void nativeSetDrawFilter(int nativeCanvas,
1481                                                   int nativeFilter);
1482    private static native boolean native_getClipBounds(int nativeCanvas,
1483                                                       Rect bounds);
1484    private static native void native_getCTM(int canvas, int matrix);
1485    private static native boolean native_quickReject(int nativeCanvas,
1486                                                     RectF rect,
1487                                                     int native_edgeType);
1488    private static native boolean native_quickReject(int nativeCanvas,
1489                                                     int path,
1490                                                     int native_edgeType);
1491    private static native boolean native_quickReject(int nativeCanvas,
1492                                                     float left, float top,
1493                                                     float right, float bottom,
1494                                                     int native_edgeType);
1495    private static native void native_drawRGB(int nativeCanvas, int r, int g,
1496                                              int b);
1497    private static native void native_drawARGB(int nativeCanvas, int a, int r,
1498                                               int g, int b);
1499    private static native void native_drawColor(int nativeCanvas, int color);
1500    private static native void native_drawColor(int nativeCanvas, int color,
1501                                                int mode);
1502    private static native void native_drawPaint(int nativeCanvas, int paint);
1503    private static native void native_drawLine(int nativeCanvas, float startX,
1504                                               float startY, float stopX,
1505                                               float stopY, int paint);
1506    private static native void native_drawRect(int nativeCanvas, RectF rect,
1507                                               int paint);
1508    private static native void native_drawRect(int nativeCanvas, float left,
1509                                               float top, float right,
1510                                               float bottom, int paint);
1511    private static native void native_drawOval(int nativeCanvas, RectF oval,
1512                                               int paint);
1513    private static native void native_drawCircle(int nativeCanvas, float cx,
1514                                                 float cy, float radius,
1515                                                 int paint);
1516    private static native void native_drawArc(int nativeCanvas, RectF oval,
1517                                              float startAngle, float sweep,
1518                                              boolean useCenter, int paint);
1519    private static native void native_drawRoundRect(int nativeCanvas,
1520                                                    RectF rect, float rx,
1521                                                    float ry, int paint);
1522    private static native void native_drawPath(int nativeCanvas, int path,
1523                                               int paint);
1524    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1525                                                 float left, float top,
1526                                                 int nativePaintOrZero,
1527                                                 int canvasDensity,
1528                                                 int screenDensity,
1529                                                 int bitmapDensity);
1530    private native void native_drawBitmap(int nativeCanvas, int bitmap,
1531                                                 Rect src, RectF dst,
1532                                                 int nativePaintOrZero,
1533                                                 int screenDensity,
1534                                                 int bitmapDensity);
1535    private static native void native_drawBitmap(int nativeCanvas, int bitmap,
1536                                                 Rect src, Rect dst,
1537                                                 int nativePaintOrZero,
1538                                                 int screenDensity,
1539                                                 int bitmapDensity);
1540    private static native void native_drawBitmap(int nativeCanvas, int[] colors,
1541                                                int offset, int stride, float x,
1542                                                 float y, int width, int height,
1543                                                 boolean hasAlpha,
1544                                                 int nativePaintOrZero);
1545    private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap,
1546                                                      int nMatrix, int nPaint);
1547    private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap,
1548                                                    int meshWidth, int meshHeight,
1549                                                    float[] verts, int vertOffset,
1550                                                    int[] colors, int colorOffset, int nPaint);
1551    private static native void nativeDrawVertices(int nCanvas, int mode, int n,
1552                   float[] verts, int vertOffset, float[] texs, int texOffset,
1553                   int[] colors, int colorOffset, short[] indices,
1554                   int indexOffset, int indexCount, int nPaint);
1555
1556    private static native void native_drawText(int nativeCanvas, char[] text,
1557                                               int index, int count, float x,
1558                                               float y, int paint);
1559    private static native void native_drawText(int nativeCanvas, String text,
1560                                               int start, int end, float x,
1561                                               float y, int paint);
1562    private static native void native_drawPosText(int nativeCanvas,
1563                                                  char[] text, int index,
1564                                                  int count, float[] pos,
1565                                                  int paint);
1566    private static native void native_drawPosText(int nativeCanvas,
1567                                                  String text, float[] pos,
1568                                                  int paint);
1569    private static native void native_drawTextOnPath(int nativeCanvas,
1570                                                     char[] text, int index,
1571                                                     int count, int path,
1572                                                     float hOffset,
1573                                                     float vOffset, int paint);
1574    private static native void native_drawTextOnPath(int nativeCanvas,
1575                                                     String text, int path,
1576                                                     float hOffset,
1577                                                     float vOffset, int paint);
1578    private static native void native_drawPicture(int nativeCanvas,
1579                                                  int nativePicture);
1580    private static native void finalizer(int nativeCanvas);
1581}
1582