Paint.java revision 0c702b88c5d0d4380930b920f5be6e66dd95a0d8
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.GraphicsOperations;
20import android.text.SpannableString;
21import android.text.SpannedString;
22import android.text.TextUtils;
23
24/**
25 * The Paint class holds the style and color information about how to draw
26 * geometries, text and bitmaps.
27 */
28public class Paint {
29
30    /*package*/ int     mNativePaint;
31    private ColorFilter mColorFilter;
32    private MaskFilter  mMaskFilter;
33    private PathEffect  mPathEffect;
34    private Rasterizer  mRasterizer;
35    private Shader      mShader;
36    private Typeface    mTypeface;
37    private Xfermode    mXfermode;
38
39    private boolean     mHasCompatScaling;
40    private float       mCompatScaling;
41    private float       mInvCompatScaling;
42    /* package */ int   mBidiFlags = BIDI_DEFAULT_LTR;
43
44    private static final Style[] sStyleArray = {
45        Style.FILL, Style.STROKE, Style.FILL_AND_STROKE
46    };
47    private static final Cap[] sCapArray = {
48        Cap.BUTT, Cap.ROUND, Cap.SQUARE
49    };
50    private static final Join[] sJoinArray = {
51        Join.MITER, Join.ROUND, Join.BEVEL
52    };
53    private static final Align[] sAlignArray = {
54        Align.LEFT, Align.CENTER, Align.RIGHT
55    };
56
57    /** bit mask for the flag enabling antialiasing */
58    public static final int ANTI_ALIAS_FLAG     = 0x01;
59    /** bit mask for the flag enabling bitmap filtering */
60    public static final int FILTER_BITMAP_FLAG  = 0x02;
61    /** bit mask for the flag enabling dithering */
62    public static final int DITHER_FLAG         = 0x04;
63    /** bit mask for the flag enabling underline text */
64    public static final int UNDERLINE_TEXT_FLAG = 0x08;
65    /** bit mask for the flag enabling strike-thru text */
66    public static final int STRIKE_THRU_TEXT_FLAG = 0x10;
67    /** bit mask for the flag enabling fake-bold text */
68    public static final int FAKE_BOLD_TEXT_FLAG = 0x20;
69    /** bit mask for the flag enabling linear-text (no caching) */
70    public static final int LINEAR_TEXT_FLAG    = 0x40;
71    /** bit mask for the flag enabling subpixel-text */
72    public static final int SUBPIXEL_TEXT_FLAG  = 0x80;
73    /** bit mask for the flag enabling device kerning for text */
74    public static final int DEV_KERN_TEXT_FLAG  = 0x100;
75
76    // we use this when we first create a paint
77    private static final int DEFAULT_PAINT_FLAGS = DEV_KERN_TEXT_FLAG;
78
79    /**
80     * Bidi flag to set LTR paragraph direction.
81     *
82     * @hide
83     */
84    public static final int BIDI_LTR = 0x0;
85
86    /**
87     * Bidi flag to set RTL paragraph direction.
88     *
89     * @hide
90     */
91    public static final int BIDI_RTL = 0x1;
92
93    /**
94     * Bidi flag to detect paragraph direction via heuristics, defaulting to
95     * LTR.
96     *
97     * @hide
98     */
99    public static final int BIDI_DEFAULT_LTR = 0x2;
100
101    /**
102     * Bidi flag to detect paragraph direction via heuristics, defaulting to
103     * RTL.
104     *
105     * @hide
106     */
107    public static final int BIDI_DEFAULT_RTL = 0x3;
108
109    /**
110     * Bidi flag to override direction to all LTR (ignore bidi).
111     *
112     * @hide
113     */
114    public static final int BIDI_FORCE_LTR = 0x4;
115
116    /**
117     * Bidi flag to override direction to all RTL (ignore bidi).
118     *
119     * @hide
120     */
121    public static final int BIDI_FORCE_RTL = 0x5;
122
123    /**
124     * Maximum Bidi flag value.
125     * @hide
126     */
127    private static final int BIDI_MAX_FLAG_VALUE = BIDI_FORCE_RTL;
128
129    /**
130     * Mask for bidi flags.
131     * @hide
132     */
133    private static final int BIDI_FLAG_MASK = 0x7;
134
135    /**
136     * Flag for getTextRunAdvances indicating left-to-right run direction.
137     * @hide
138     */
139    public static final int DIRECTION_LTR = 0;
140
141    /**
142     * Flag for getTextRunAdvances indicating right-to-left run direction.
143     * @hide
144     */
145    public static final int DIRECTION_RTL = 1;
146
147    /**
148     * Option for getTextRunCursor to compute the valid cursor after
149     * offset or the limit of the context, whichever is less.
150     * @hide
151     */
152    public static final int CURSOR_AFTER = 0;
153
154    /**
155     * Option for getTextRunCursor to compute the valid cursor at or after
156     * the offset or the limit of the context, whichever is less.
157     * @hide
158     */
159    public static final int CURSOR_AT_OR_AFTER = 1;
160
161     /**
162     * Option for getTextRunCursor to compute the valid cursor before
163     * offset or the start of the context, whichever is greater.
164     * @hide
165     */
166    public static final int CURSOR_BEFORE = 2;
167
168   /**
169     * Option for getTextRunCursor to compute the valid cursor at or before
170     * offset or the start of the context, whichever is greater.
171     * @hide
172     */
173    public static final int CURSOR_AT_OR_BEFORE = 3;
174
175    /**
176     * Option for getTextRunCursor to return offset if the cursor at offset
177     * is valid, or -1 if it isn't.
178     * @hide
179     */
180    public static final int CURSOR_AT = 4;
181
182    /**
183     * Maximum cursor option value.
184     */
185    private static final int CURSOR_OPT_MAX_VALUE = CURSOR_AT;
186
187    /**
188     * The Style specifies if the primitive being drawn is filled, stroked, or
189     * both (in the same color). The default is FILL.
190     */
191    public enum Style {
192        /**
193         * Geometry and text drawn with this style will be filled, ignoring all
194         * stroke-related settings in the paint.
195         */
196        FILL            (0),
197        /**
198         * Geometry and text drawn with this style will be stroked, respecting
199         * the stroke-related fields on the paint.
200         */
201        STROKE          (1),
202        /**
203         * Geometry and text drawn with this style will be both filled and
204         * stroked at the same time, respecting the stroke-related fields on
205         * the paint. This mode can give unexpected results if the geometry
206         * is oriented counter-clockwise. This restriction does not apply to
207         * either FILL or STROKE.
208         */
209        FILL_AND_STROKE (2);
210
211        Style(int nativeInt) {
212            this.nativeInt = nativeInt;
213        }
214        final int nativeInt;
215    }
216
217    /**
218     * The Cap specifies the treatment for the beginning and ending of
219     * stroked lines and paths. The default is BUTT.
220     */
221    public enum Cap {
222        /**
223         * The stroke ends with the path, and does not project beyond it.
224         */
225        BUTT    (0),
226        /**
227         * The stroke projects out as a semicircle, with the center at the
228         * end of the path.
229         */
230        ROUND   (1),
231        /**
232         * The stroke projects out as a square, with the center at the end
233         * of the path.
234         */
235        SQUARE  (2);
236
237        private Cap(int nativeInt) {
238            this.nativeInt = nativeInt;
239        }
240        final int nativeInt;
241    }
242
243    /**
244     * The Join specifies the treatment where lines and curve segments
245     * join on a stroked path. The default is MITER.
246     */
247    public enum Join {
248        /**
249         * The outer edges of a join meet at a sharp angle
250         */
251        MITER   (0),
252        /**
253         * The outer edges of a join meet in a circular arc.
254         */
255        ROUND   (1),
256        /**
257         * The outer edges of a join meet with a straight line
258         */
259        BEVEL   (2);
260
261        private Join(int nativeInt) {
262            this.nativeInt = nativeInt;
263        }
264        final int nativeInt;
265    }
266
267    /**
268     * Align specifies how drawText aligns its text relative to the
269     * [x,y] coordinates. The default is LEFT.
270     */
271    public enum Align {
272        /**
273         * The text is drawn to the right of the x,y origin
274         */
275        LEFT    (0),
276        /**
277         * The text is drawn centered horizontally on the x,y origin
278         */
279        CENTER  (1),
280        /**
281         * The text is drawn to the left of the x,y origin
282         */
283        RIGHT   (2);
284
285        private Align(int nativeInt) {
286            this.nativeInt = nativeInt;
287        }
288        final int nativeInt;
289    }
290
291    /**
292     * Create a new paint with default settings.
293     */
294    public Paint() {
295        this(0);
296    }
297
298    /**
299     * Create a new paint with the specified flags. Use setFlags() to change
300     * these after the paint is created.
301     *
302     * @param flags initial flag bits, as if they were passed via setFlags().
303     */
304    public Paint(int flags) {
305        mNativePaint = native_init();
306        setFlags(flags | DEFAULT_PAINT_FLAGS);
307        mCompatScaling = mInvCompatScaling = 1;
308    }
309
310    /**
311     * Create a new paint, initialized with the attributes in the specified
312     * paint parameter.
313     *
314     * @param paint Existing paint used to initialized the attributes of the
315     *              new paint.
316     */
317    public Paint(Paint paint) {
318        mNativePaint = native_initWithPaint(paint.mNativePaint);
319        mHasCompatScaling = paint.mHasCompatScaling;
320        mCompatScaling = paint.mCompatScaling;
321        mInvCompatScaling = paint.mInvCompatScaling;
322        mBidiFlags = paint.mBidiFlags;
323    }
324
325    /** Restores the paint to its default settings. */
326    public void reset() {
327        native_reset(mNativePaint);
328        setFlags(DEFAULT_PAINT_FLAGS);
329        mHasCompatScaling = false;
330        mCompatScaling = mInvCompatScaling = 1;
331        mBidiFlags = BIDI_DEFAULT_LTR;
332    }
333
334    /**
335     * Copy the fields from src into this paint. This is equivalent to calling
336     * get() on all of the src fields, and calling the corresponding set()
337     * methods on this.
338     */
339    public void set(Paint src) {
340        if (this != src) {
341            // copy over the native settings
342            native_set(mNativePaint, src.mNativePaint);
343            // copy over our java settings
344            mColorFilter    = src.mColorFilter;
345            mMaskFilter     = src.mMaskFilter;
346            mPathEffect     = src.mPathEffect;
347            mRasterizer     = src.mRasterizer;
348            mShader         = src.mShader;
349            mTypeface       = src.mTypeface;
350            mXfermode       = src.mXfermode;
351            mHasCompatScaling = src.mHasCompatScaling;
352            mCompatScaling    = src.mCompatScaling;
353            mInvCompatScaling = src.mInvCompatScaling;
354            mBidiFlags      = src.mBidiFlags;
355        }
356    }
357
358    /** @hide */
359    public void setCompatibilityScaling(float factor) {
360        if (factor == 1.0) {
361            mHasCompatScaling = false;
362            mCompatScaling = mInvCompatScaling = 1.0f;
363        } else {
364            mHasCompatScaling = true;
365            mCompatScaling = factor;
366            mInvCompatScaling = 1.0f/factor;
367        }
368    }
369
370    /**
371     * Return the bidi flags on the paint.
372     *
373     * @return the bidi flags on the paint
374     * @hide
375     */
376    public int getBidiFlags() {
377        return mBidiFlags;
378    }
379
380    /**
381     * Set the bidi flags on the paint.
382     * @hide
383     */
384    public void setBidiFlags(int flags) {
385        // only flag value is the 3-bit BIDI control setting
386        flags &= BIDI_FLAG_MASK;
387        if (flags > BIDI_MAX_FLAG_VALUE) {
388            throw new IllegalArgumentException("unknown bidi flag: " + flags);
389        }
390        mBidiFlags = flags;
391    }
392
393    /**
394     * Return the paint's flags. Use the Flag enum to test flag values.
395     *
396     * @return the paint's flags (see enums ending in _Flag for bit masks)
397     */
398    public native int getFlags();
399
400    /**
401     * Set the paint's flags. Use the Flag enum to specific flag values.
402     *
403     * @param flags The new flag bits for the paint
404     */
405    public native void setFlags(int flags);
406
407    /**
408     * Helper for getFlags(), returning true if ANTI_ALIAS_FLAG bit is set
409     * AntiAliasing smooths out the edges of what is being drawn, but is has
410     * no impact on the interior of the shape. See setDither() and
411     * setFilterBitmap() to affect how colors are treated.
412     *
413     * @return true if the antialias bit is set in the paint's flags.
414     */
415    public final boolean isAntiAlias() {
416        return (getFlags() & ANTI_ALIAS_FLAG) != 0;
417    }
418
419    /**
420     * Helper for setFlags(), setting or clearing the ANTI_ALIAS_FLAG bit
421     * AntiAliasing smooths out the edges of what is being drawn, but is has
422     * no impact on the interior of the shape. See setDither() and
423     * setFilterBitmap() to affect how colors are treated.
424     *
425     * @param aa true to set the antialias bit in the flags, false to clear it
426     */
427    public native void setAntiAlias(boolean aa);
428
429    /**
430     * Helper for getFlags(), returning true if DITHER_FLAG bit is set
431     * Dithering affects how colors that are higher precision than the device
432     * are down-sampled. No dithering is generally faster, but higher precision
433     * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to
434     * distribute the error inherent in this process, to reduce the visual
435     * artifacts.
436     *
437     * @return true if the dithering bit is set in the paint's flags.
438     */
439    public final boolean isDither() {
440        return (getFlags() & DITHER_FLAG) != 0;
441    }
442
443    /**
444     * Helper for setFlags(), setting or clearing the DITHER_FLAG bit
445     * Dithering affects how colors that are higher precision than the device
446     * are down-sampled. No dithering is generally faster, but higher precision
447     * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to
448     * distribute the error inherent in this process, to reduce the visual
449     * artifacts.
450     *
451     * @param dither true to set the dithering bit in flags, false to clear it
452     */
453    public native void setDither(boolean dither);
454
455    /**
456     * Helper for getFlags(), returning true if LINEAR_TEXT_FLAG bit is set
457     *
458     * @return true if the lineartext bit is set in the paint's flags
459     */
460    public final boolean isLinearText() {
461        return (getFlags() & LINEAR_TEXT_FLAG) != 0;
462    }
463
464    /**
465     * Helper for setFlags(), setting or clearing the LINEAR_TEXT_FLAG bit
466     *
467     * @param linearText true to set the linearText bit in the paint's flags,
468     *                   false to clear it.
469     */
470    public native void setLinearText(boolean linearText);
471
472    /**
473     * Helper for getFlags(), returning true if SUBPIXEL_TEXT_FLAG bit is set
474     *
475     * @return true if the subpixel bit is set in the paint's flags
476     */
477    public final boolean isSubpixelText() {
478        return (getFlags() & SUBPIXEL_TEXT_FLAG) != 0;
479    }
480
481    /**
482     * Helper for setFlags(), setting or clearing the SUBPIXEL_TEXT_FLAG bit
483     *
484     * @param subpixelText true to set the subpixelText bit in the paint's
485     *                     flags, false to clear it.
486     */
487    public native void setSubpixelText(boolean subpixelText);
488
489    /**
490     * Helper for getFlags(), returning true if UNDERLINE_TEXT_FLAG bit is set
491     *
492     * @return true if the underlineText bit is set in the paint's flags.
493     */
494    public final boolean isUnderlineText() {
495        return (getFlags() & UNDERLINE_TEXT_FLAG) != 0;
496    }
497
498    /**
499     * Helper for setFlags(), setting or clearing the UNDERLINE_TEXT_FLAG bit
500     *
501     * @param underlineText true to set the underlineText bit in the paint's
502     *                      flags, false to clear it.
503     */
504    public native void setUnderlineText(boolean underlineText);
505
506    /**
507     * Helper for getFlags(), returning true if STRIKE_THRU_TEXT_FLAG bit is set
508     *
509     * @return true if the strikeThruText bit is set in the paint's flags.
510     */
511    public final boolean isStrikeThruText() {
512        return (getFlags() & STRIKE_THRU_TEXT_FLAG) != 0;
513    }
514
515    /**
516     * Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit
517     *
518     * @param strikeThruText true to set the strikeThruText bit in the paint's
519     *                       flags, false to clear it.
520     */
521    public native void setStrikeThruText(boolean strikeThruText);
522
523    /**
524     * Helper for getFlags(), returning true if FAKE_BOLD_TEXT_FLAG bit is set
525     *
526     * @return true if the fakeBoldText bit is set in the paint's flags.
527     */
528    public final boolean isFakeBoldText() {
529        return (getFlags() & FAKE_BOLD_TEXT_FLAG) != 0;
530    }
531
532    /**
533     * Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit
534     *
535     * @param fakeBoldText true to set the fakeBoldText bit in the paint's
536     *                     flags, false to clear it.
537     */
538    public native void setFakeBoldText(boolean fakeBoldText);
539
540    /**
541     * Whether or not the bitmap filter is activated.
542     * Filtering affects the sampling of bitmaps when they are transformed.
543     * Filtering does not affect how the colors in the bitmap are converted into
544     * device pixels. That is dependent on dithering and xfermodes.
545     *
546     * @see #setFilterBitmap(boolean) setFilterBitmap()
547     */
548    public final boolean isFilterBitmap() {
549        return (getFlags() & FILTER_BITMAP_FLAG) != 0;
550    }
551
552    /**
553     * Helper for setFlags(), setting or clearing the FILTER_BITMAP_FLAG bit.
554     * Filtering affects the sampling of bitmaps when they are transformed.
555     * Filtering does not affect how the colors in the bitmap are converted into
556     * device pixels. That is dependent on dithering and xfermodes.
557     *
558     * @param filter true to set the FILTER_BITMAP_FLAG bit in the paint's
559     *               flags, false to clear it.
560     */
561    public native void setFilterBitmap(boolean filter);
562
563    /**
564     * Return the paint's style, used for controlling how primitives'
565     * geometries are interpreted (except for drawBitmap, which always assumes
566     * FILL_STYLE).
567     *
568     * @return the paint's style setting (Fill, Stroke, StrokeAndFill)
569     */
570    public Style getStyle() {
571        return sStyleArray[native_getStyle(mNativePaint)];
572    }
573
574    /**
575     * Set the paint's style, used for controlling how primitives'
576     * geometries are interpreted (except for drawBitmap, which always assumes
577     * Fill).
578     *
579     * @param style The new style to set in the paint
580     */
581    public void setStyle(Style style) {
582        native_setStyle(mNativePaint, style.nativeInt);
583    }
584
585    /**
586     * Return the paint's color. Note that the color is a 32bit value
587     * containing alpha as well as r,g,b. This 32bit value is not premultiplied,
588     * meaning that its alpha can be any value, regardless of the values of
589     * r,g,b. See the Color class for more details.
590     *
591     * @return the paint's color (and alpha).
592     */
593    public native int getColor();
594
595    /**
596     * Set the paint's color. Note that the color is an int containing alpha
597     * as well as r,g,b. This 32bit value is not premultiplied, meaning that
598     * its alpha can be any value, regardless of the values of r,g,b.
599     * See the Color class for more details.
600     *
601     * @param color The new color (including alpha) to set in the paint.
602     */
603    public native void setColor(int color);
604
605    /**
606     * Helper to getColor() that just returns the color's alpha value. This is
607     * the same as calling getColor() >>> 24. It always returns a value between
608     * 0 (completely transparent) and 255 (completely opaque).
609     *
610     * @return the alpha component of the paint's color.
611     */
612    public native int getAlpha();
613
614    /**
615     * Helper to setColor(), that only assigns the color's alpha value,
616     * leaving its r,g,b values unchanged. Results are undefined if the alpha
617     * value is outside of the range [0..255]
618     *
619     * @param a set the alpha component [0..255] of the paint's color.
620     */
621    public native void setAlpha(int a);
622
623    /**
624     * Helper to setColor(), that takes a,r,g,b and constructs the color int
625     *
626     * @param a The new alpha component (0..255) of the paint's color.
627     * @param r The new red component (0..255) of the paint's color.
628     * @param g The new green component (0..255) of the paint's color.
629     * @param b The new blue component (0..255) of the paint's color.
630     */
631    public void setARGB(int a, int r, int g, int b) {
632        setColor((a << 24) | (r << 16) | (g << 8) | b);
633    }
634
635    /**
636     * Return the width for stroking.
637     * <p />
638     * A value of 0 strokes in hairline mode.
639     * Hairlines always draws a single pixel independent of the canva's matrix.
640     *
641     * @return the paint's stroke width, used whenever the paint's style is
642     *         Stroke or StrokeAndFill.
643     */
644    public native float getStrokeWidth();
645
646    /**
647     * Set the width for stroking.
648     * Pass 0 to stroke in hairline mode.
649     * Hairlines always draws a single pixel independent of the canva's matrix.
650     *
651     * @param width set the paint's stroke width, used whenever the paint's
652     *              style is Stroke or StrokeAndFill.
653     */
654    public native void setStrokeWidth(float width);
655
656    /**
657     * Return the paint's stroke miter value. Used to control the behavior
658     * of miter joins when the joins angle is sharp.
659     *
660     * @return the paint's miter limit, used whenever the paint's style is
661     *         Stroke or StrokeAndFill.
662     */
663    public native float getStrokeMiter();
664
665    /**
666     * Set the paint's stroke miter value. This is used to control the behavior
667     * of miter joins when the joins angle is sharp. This value must be >= 0.
668     *
669     * @param miter set the miter limit on the paint, used whenever the paint's
670     *              style is Stroke or StrokeAndFill.
671     */
672    public native void setStrokeMiter(float miter);
673
674    /**
675     * Return the paint's Cap, controlling how the start and end of stroked
676     * lines and paths are treated.
677     *
678     * @return the line cap style for the paint, used whenever the paint's
679     *         style is Stroke or StrokeAndFill.
680     */
681    public Cap getStrokeCap() {
682        return sCapArray[native_getStrokeCap(mNativePaint)];
683    }
684
685    /**
686     * Set the paint's Cap.
687     *
688     * @param cap set the paint's line cap style, used whenever the paint's
689     *            style is Stroke or StrokeAndFill.
690     */
691    public void setStrokeCap(Cap cap) {
692        native_setStrokeCap(mNativePaint, cap.nativeInt);
693    }
694
695    /**
696     * Return the paint's stroke join type.
697     *
698     * @return the paint's Join.
699     */
700    public Join getStrokeJoin() {
701        return sJoinArray[native_getStrokeJoin(mNativePaint)];
702    }
703
704    /**
705     * Set the paint's Join.
706     *
707     * @param join set the paint's Join, used whenever the paint's style is
708     *             Stroke or StrokeAndFill.
709     */
710    public void setStrokeJoin(Join join) {
711        native_setStrokeJoin(mNativePaint, join.nativeInt);
712    }
713
714    /**
715     * Applies any/all effects (patheffect, stroking) to src, returning the
716     * result in dst. The result is that drawing src with this paint will be
717     * the same as drawing dst with a default paint (at least from the
718     * geometric perspective).
719     *
720     * @param src input path
721     * @param dst output path (may be the same as src)
722     * @return    true if the path should be filled, or false if it should be
723     *                 drawn with a hairline (width == 0)
724     */
725    public boolean getFillPath(Path src, Path dst) {
726        return native_getFillPath(mNativePaint, src.ni(), dst.ni());
727    }
728
729    /**
730     * Get the paint's shader object.
731     *
732     * @return the paint's shader (or null)
733     */
734    public Shader getShader() {
735        return mShader;
736    }
737
738    /**
739     * Set or clear the shader object.
740     * <p />
741     * Pass null to clear any previous shader.
742     * As a convenience, the parameter passed is also returned.
743     *
744     * @param shader May be null. the new shader to be installed in the paint
745     * @return       shader
746     */
747    public Shader setShader(Shader shader) {
748        int shaderNative = 0;
749        if (shader != null)
750            shaderNative = shader.native_instance;
751        native_setShader(mNativePaint, shaderNative);
752        mShader = shader;
753        return shader;
754    }
755
756    /**
757     * Get the paint's colorfilter (maybe be null).
758     *
759     * @return the paint's colorfilter (maybe be null)
760     */
761    public ColorFilter getColorFilter() {
762        return mColorFilter;
763    }
764
765    /**
766     * Set or clear the paint's colorfilter, returning the parameter.
767     *
768     * @param filter May be null. The new filter to be installed in the paint
769     * @return       filter
770     */
771    public ColorFilter setColorFilter(ColorFilter filter) {
772        int filterNative = 0;
773        if (filter != null)
774            filterNative = filter.native_instance;
775        native_setColorFilter(mNativePaint, filterNative);
776        mColorFilter = filter;
777        return filter;
778    }
779
780    /**
781     * Get the paint's xfermode object.
782     *
783     * @return the paint's xfermode (or null)
784     */
785    public Xfermode getXfermode() {
786        return mXfermode;
787    }
788
789    /**
790     * Set or clear the xfermode object.
791     * <p />
792     * Pass null to clear any previous xfermode.
793     * As a convenience, the parameter passed is also returned.
794     *
795     * @param xfermode May be null. The xfermode to be installed in the paint
796     * @return         xfermode
797     */
798    public Xfermode setXfermode(Xfermode xfermode) {
799        int xfermodeNative = 0;
800        if (xfermode != null)
801            xfermodeNative = xfermode.native_instance;
802        native_setXfermode(mNativePaint, xfermodeNative);
803        mXfermode = xfermode;
804        return xfermode;
805    }
806
807    /**
808     * Get the paint's patheffect object.
809     *
810     * @return the paint's patheffect (or null)
811     */
812    public PathEffect getPathEffect() {
813        return mPathEffect;
814    }
815
816    /**
817     * Set or clear the patheffect object.
818     * <p />
819     * Pass null to clear any previous patheffect.
820     * As a convenience, the parameter passed is also returned.
821     *
822     * @param effect May be null. The patheffect to be installed in the paint
823     * @return       effect
824     */
825    public PathEffect setPathEffect(PathEffect effect) {
826        int effectNative = 0;
827        if (effect != null) {
828            effectNative = effect.native_instance;
829        }
830        native_setPathEffect(mNativePaint, effectNative);
831        mPathEffect = effect;
832        return effect;
833    }
834
835    /**
836     * Get the paint's maskfilter object.
837     *
838     * @return the paint's maskfilter (or null)
839     */
840    public MaskFilter getMaskFilter() {
841        return mMaskFilter;
842    }
843
844    /**
845     * Set or clear the maskfilter object.
846     * <p />
847     * Pass null to clear any previous maskfilter.
848     * As a convenience, the parameter passed is also returned.
849     *
850     * @param maskfilter May be null. The maskfilter to be installed in the
851     *                   paint
852     * @return           maskfilter
853     */
854    public MaskFilter setMaskFilter(MaskFilter maskfilter) {
855        int maskfilterNative = 0;
856        if (maskfilter != null) {
857            maskfilterNative = maskfilter.native_instance;
858        }
859        native_setMaskFilter(mNativePaint, maskfilterNative);
860        mMaskFilter = maskfilter;
861        return maskfilter;
862    }
863
864    /**
865     * Get the paint's typeface object.
866     * <p />
867     * The typeface object identifies which font to use when drawing or
868     * measuring text.
869     *
870     * @return the paint's typeface (or null)
871     */
872    public Typeface getTypeface() {
873        return mTypeface;
874    }
875
876    /**
877     * Set or clear the typeface object.
878     * <p />
879     * Pass null to clear any previous typeface.
880     * As a convenience, the parameter passed is also returned.
881     *
882     * @param typeface May be null. The typeface to be installed in the paint
883     * @return         typeface
884     */
885    public Typeface setTypeface(Typeface typeface) {
886        int typefaceNative = 0;
887        if (typeface != null) {
888            typefaceNative = typeface.native_instance;
889        }
890        native_setTypeface(mNativePaint, typefaceNative);
891        mTypeface = typeface;
892        return typeface;
893    }
894
895    /**
896     * Get the paint's rasterizer (or null).
897     * <p />
898     * The raster controls/modifies how paths/text are turned into alpha masks.
899     *
900     * @return         the paint's rasterizer (or null)
901     */
902    public Rasterizer getRasterizer() {
903        return mRasterizer;
904    }
905
906    /**
907     * Set or clear the rasterizer object.
908     * <p />
909     * Pass null to clear any previous rasterizer.
910     * As a convenience, the parameter passed is also returned.
911     *
912     * @param rasterizer May be null. The new rasterizer to be installed in
913     *                   the paint.
914     * @return           rasterizer
915     */
916    public Rasterizer setRasterizer(Rasterizer rasterizer) {
917        int rasterizerNative = 0;
918        if (rasterizer != null) {
919            rasterizerNative = rasterizer.native_instance;
920        }
921        native_setRasterizer(mNativePaint, rasterizerNative);
922        mRasterizer = rasterizer;
923        return rasterizer;
924    }
925
926    /**
927     * Temporary API to expose layer drawing. This draws a shadow layer below
928     * the main layer, with the specified offset and color, and blur radius.
929     * If radius is 0, then the shadow layer is removed.
930     */
931    public native void setShadowLayer(float radius, float dx, float dy,
932                                      int color);
933
934    /**
935     * Temporary API to clear the shadow layer.
936     */
937    public void clearShadowLayer() {
938        setShadowLayer(0, 0, 0, 0);
939    }
940
941    /**
942     * Return the paint's Align value for drawing text. This controls how the
943     * text is positioned relative to its origin. LEFT align means that all of
944     * the text will be drawn to the right of its origin (i.e. the origin
945     * specifieds the LEFT edge of the text) and so on.
946     *
947     * @return the paint's Align value for drawing text.
948     */
949    public Align getTextAlign() {
950        return sAlignArray[native_getTextAlign(mNativePaint)];
951    }
952
953    /**
954     * Set the paint's text alignment. This controls how the
955     * text is positioned relative to its origin. LEFT align means that all of
956     * the text will be drawn to the right of its origin (i.e. the origin
957     * specifieds the LEFT edge of the text) and so on.
958     *
959     * @param align set the paint's Align value for drawing text.
960     */
961    public void setTextAlign(Align align) {
962        native_setTextAlign(mNativePaint, align.nativeInt);
963    }
964
965    /**
966     * Return the paint's text size.
967     *
968     * @return the paint's text size.
969     */
970    public native float getTextSize();
971
972    /**
973     * Set the paint's text size. This value must be > 0
974     *
975     * @param textSize set the paint's text size.
976     */
977    public native void setTextSize(float textSize);
978
979    /**
980     * Return the paint's horizontal scale factor for text. The default value
981     * is 1.0.
982     *
983     * @return the paint's scale factor in X for drawing/measuring text
984     */
985    public native float getTextScaleX();
986
987    /**
988     * Set the paint's horizontal scale factor for text. The default value
989     * is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will
990     * stretch the text narrower.
991     *
992     * @param scaleX set the paint's scale in X for drawing/measuring text.
993     */
994    public native void setTextScaleX(float scaleX);
995
996    /**
997     * Return the paint's horizontal skew factor for text. The default value
998     * is 0.
999     *
1000     * @return         the paint's skew factor in X for drawing text.
1001     */
1002    public native float getTextSkewX();
1003
1004    /**
1005     * Set the paint's horizontal skew factor for text. The default value
1006     * is 0. For approximating oblique text, use values around -0.25.
1007     *
1008     * @param skewX set the paint's skew factor in X for drawing text.
1009     */
1010    public native void setTextSkewX(float skewX);
1011
1012    /**
1013     * Return the distance above (negative) the baseline (ascent) based on the
1014     * current typeface and text size.
1015     *
1016     * @return the distance above (negative) the baseline (ascent) based on the
1017     *         current typeface and text size.
1018     */
1019    public native float ascent();
1020
1021    /**
1022     * Return the distance below (positive) the baseline (descent) based on the
1023     * current typeface and text size.
1024     *
1025     * @return the distance below (positive) the baseline (descent) based on
1026     *         the current typeface and text size.
1027     */
1028    public native float descent();
1029
1030    /**
1031     * Class that describes the various metrics for a font at a given text size.
1032     * Remember, Y values increase going down, so those values will be positive,
1033     * and values that measure distances going up will be negative. This class
1034     * is returned by getFontMetrics().
1035     */
1036    public static class FontMetrics {
1037        /**
1038         * The maximum distance above the baseline for the tallest glyph in
1039         * the font at a given text size.
1040         */
1041        public float   top;
1042        /**
1043         * The recommended distance above the baseline for singled spaced text.
1044         */
1045        public float   ascent;
1046        /**
1047         * The recommended distance below the baseline for singled spaced text.
1048         */
1049        public float   descent;
1050        /**
1051         * The maximum distance below the baseline for the lowest glyph in
1052         * the font at a given text size.
1053         */
1054        public float   bottom;
1055        /**
1056         * The recommended additional space to add between lines of text.
1057         */
1058        public float   leading;
1059    }
1060
1061    /**
1062     * Return the font's recommended interline spacing, given the Paint's
1063     * settings for typeface, textSize, etc. If metrics is not null, return the
1064     * fontmetric values in it.
1065     *
1066     * @param metrics If this object is not null, its fields are filled with
1067     *                the appropriate values given the paint's text attributes.
1068     * @return the font's recommended interline spacing.
1069     */
1070    public native float getFontMetrics(FontMetrics metrics);
1071
1072    /**
1073     * Allocates a new FontMetrics object, and then calls getFontMetrics(fm)
1074     * with it, returning the object.
1075     */
1076    public FontMetrics getFontMetrics() {
1077        FontMetrics fm = new FontMetrics();
1078        getFontMetrics(fm);
1079        return fm;
1080    }
1081
1082    /**
1083     * Convenience method for callers that want to have FontMetrics values as
1084     * integers.
1085     */
1086    public static class FontMetricsInt {
1087        public int   top;
1088        public int   ascent;
1089        public int   descent;
1090        public int   bottom;
1091        public int   leading;
1092
1093        @Override public String toString() {
1094            return "FontMetricsInt: top=" + top + " ascent=" + ascent +
1095                    " descent=" + descent + " bottom=" + bottom +
1096                    " leading=" + leading;
1097        }
1098    }
1099
1100    /**
1101     * Return the font's interline spacing, given the Paint's settings for
1102     * typeface, textSize, etc. If metrics is not null, return the fontmetric
1103     * values in it. Note: all values have been converted to integers from
1104     * floats, in such a way has to make the answers useful for both spacing
1105     * and clipping. If you want more control over the rounding, call
1106     * getFontMetrics().
1107     *
1108     * @return the font's interline spacing.
1109     */
1110    public native int getFontMetricsInt(FontMetricsInt fmi);
1111
1112    public FontMetricsInt getFontMetricsInt() {
1113        FontMetricsInt fm = new FontMetricsInt();
1114        getFontMetricsInt(fm);
1115        return fm;
1116    }
1117
1118    /**
1119     * Return the recommend line spacing based on the current typeface and
1120     * text size.
1121     *
1122     * @return  recommend line spacing based on the current typeface and
1123     *          text size.
1124     */
1125    public float getFontSpacing() {
1126        return getFontMetrics(null);
1127    }
1128
1129    /**
1130     * Return the width of the text.
1131     *
1132     * @param text  The text to measure
1133     * @param index The index of the first character to start measuring
1134     * @param count THe number of characters to measure, beginning with start
1135     * @return      The width of the text
1136     */
1137    public float measureText(char[] text, int index, int count) {
1138        if (!mHasCompatScaling) return native_measureText(text, index, count);
1139        final float oldSize = getTextSize();
1140        setTextSize(oldSize*mCompatScaling);
1141        float w = native_measureText(text, index, count);
1142        setTextSize(oldSize);
1143        return w*mInvCompatScaling;
1144    }
1145
1146    private native float native_measureText(char[] text, int index, int count);
1147
1148    /**
1149     * Return the width of the text.
1150     *
1151     * @param text  The text to measure
1152     * @param start The index of the first character to start measuring
1153     * @param end   1 beyond the index of the last character to measure
1154     * @return      The width of the text
1155     */
1156    public float measureText(String text, int start, int end) {
1157        if (!mHasCompatScaling) return native_measureText(text, start, end);
1158        final float oldSize = getTextSize();
1159        setTextSize(oldSize*mCompatScaling);
1160        float w = native_measureText(text, start, end);
1161        setTextSize(oldSize);
1162        return w*mInvCompatScaling;
1163    }
1164
1165    private native float native_measureText(String text, int start, int end);
1166
1167    /**
1168     * Return the width of the text.
1169     *
1170     * @param text  The text to measure
1171     * @return      The width of the text
1172     */
1173    public float measureText(String text) {
1174        if (!mHasCompatScaling) return native_measureText(text);
1175        final float oldSize = getTextSize();
1176        setTextSize(oldSize*mCompatScaling);
1177        float w = native_measureText(text);
1178        setTextSize(oldSize);
1179        return w*mInvCompatScaling;
1180    }
1181
1182    private native float native_measureText(String text);
1183
1184    /**
1185     * Return the width of the text.
1186     *
1187     * @param text  The text to measure
1188     * @param start The index of the first character to start measuring
1189     * @param end   1 beyond the index of the last character to measure
1190     * @return      The width of the text
1191     */
1192    public float measureText(CharSequence text, int start, int end) {
1193        if (text instanceof String) {
1194            return measureText((String)text, start, end);
1195        }
1196        if (text instanceof SpannedString ||
1197            text instanceof SpannableString) {
1198            return measureText(text.toString(), start, end);
1199        }
1200        if (text instanceof GraphicsOperations) {
1201            return ((GraphicsOperations)text).measureText(start, end, this);
1202        }
1203
1204        char[] buf = TemporaryBuffer.obtain(end - start);
1205        TextUtils.getChars(text, start, end, buf, 0);
1206        float result = measureText(buf, 0, end - start);
1207        TemporaryBuffer.recycle(buf);
1208        return result;
1209    }
1210
1211    /**
1212     * Measure the text, stopping early if the measured width exceeds maxWidth.
1213     * Return the number of chars that were measured, and if measuredWidth is
1214     * not null, return in it the actual width measured.
1215     *
1216     * @param text  The text to measure
1217     * @param index The offset into text to begin measuring at
1218     * @param count The number of maximum number of entries to measure. If count
1219     *              is negative, then the characters before index are measured
1220     *              in reverse order. This allows for measuring the end of
1221     *              string.
1222     * @param maxWidth The maximum width to accumulate.
1223     * @param measuredWidth Optional. If not null, returns the actual width
1224     *                     measured.
1225     * @return The number of chars that were measured. Will always be <=
1226     *         abs(count).
1227     */
1228    public int breakText(char[] text, int index, int count,
1229                                float maxWidth, float[] measuredWidth) {
1230        if (!mHasCompatScaling) {
1231            return native_breakText(text, index, count, maxWidth, measuredWidth);
1232        }
1233        final float oldSize = getTextSize();
1234        setTextSize(oldSize*mCompatScaling);
1235        int res = native_breakText(text, index, count, maxWidth*mCompatScaling,
1236                measuredWidth);
1237        setTextSize(oldSize);
1238        if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling;
1239        return res;
1240    }
1241
1242    private native int native_breakText(char[] text, int index, int count,
1243                                        float maxWidth, float[] measuredWidth);
1244
1245    /**
1246     * Measure the text, stopping early if the measured width exceeds maxWidth.
1247     * Return the number of chars that were measured, and if measuredWidth is
1248     * not null, return in it the actual width measured.
1249     *
1250     * @param text  The text to measure
1251     * @param start The offset into text to begin measuring at
1252     * @param end   The end of the text slice to measure.
1253     * @param measureForwards If true, measure forwards, starting at start.
1254     *                        Otherwise, measure backwards, starting with end.
1255     * @param maxWidth The maximum width to accumulate.
1256     * @param measuredWidth Optional. If not null, returns the actual width
1257     *                     measured.
1258     * @return The number of chars that were measured. Will always be <=
1259     *         abs(end - start).
1260     */
1261    public int breakText(CharSequence text, int start, int end,
1262                         boolean measureForwards,
1263                         float maxWidth, float[] measuredWidth) {
1264        if (start == 0 && text instanceof String && end == text.length()) {
1265            return breakText((String) text, measureForwards, maxWidth,
1266                             measuredWidth);
1267        }
1268
1269        char[] buf = TemporaryBuffer.obtain(end - start);
1270        int result;
1271
1272        TextUtils.getChars(text, start, end, buf, 0);
1273
1274        if (measureForwards) {
1275            result = breakText(buf, 0, end - start, maxWidth, measuredWidth);
1276        } else {
1277            result = breakText(buf, 0, -(end - start), maxWidth, measuredWidth);
1278        }
1279
1280        TemporaryBuffer.recycle(buf);
1281        return result;
1282    }
1283
1284    /**
1285     * Measure the text, stopping early if the measured width exceeds maxWidth.
1286     * Return the number of chars that were measured, and if measuredWidth is
1287     * not null, return in it the actual width measured.
1288     *
1289     * @param text  The text to measure
1290     * @param measureForwards If true, measure forwards, starting with the
1291     *                        first character in the string. Otherwise,
1292     *                        measure backwards, starting with the
1293     *                        last character in the string.
1294     * @param maxWidth The maximum width to accumulate.
1295     * @param measuredWidth Optional. If not null, returns the actual width
1296     *                     measured.
1297     * @return The number of chars that were measured. Will always be <=
1298     *         abs(count).
1299     */
1300    public int breakText(String text, boolean measureForwards,
1301                                float maxWidth, float[] measuredWidth) {
1302        if (!mHasCompatScaling) {
1303            return native_breakText(text, measureForwards, maxWidth, measuredWidth);
1304        }
1305        final float oldSize = getTextSize();
1306        setTextSize(oldSize*mCompatScaling);
1307        int res = native_breakText(text, measureForwards, maxWidth*mCompatScaling,
1308                measuredWidth);
1309        setTextSize(oldSize);
1310        if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling;
1311        return res;
1312    }
1313
1314    private native int native_breakText(String text, boolean measureForwards,
1315                                        float maxWidth, float[] measuredWidth);
1316
1317    /**
1318     * Return the advance widths for the characters in the string.
1319     *
1320     * @param text     The text to measure
1321     * @param index    The index of the first char to to measure
1322     * @param count    The number of chars starting with index to measure
1323     * @param widths   array to receive the advance widths of the characters.
1324     *                 Must be at least a large as count.
1325     * @return         the actual number of widths returned.
1326     */
1327    public int getTextWidths(char[] text, int index, int count,
1328                             float[] widths) {
1329        if ((index | count) < 0 || index + count > text.length
1330                || count > widths.length) {
1331            throw new ArrayIndexOutOfBoundsException();
1332        }
1333
1334        if (!mHasCompatScaling) {
1335            return native_getTextWidths(mNativePaint, text, index, count, widths);
1336        }
1337        final float oldSize = getTextSize();
1338        setTextSize(oldSize*mCompatScaling);
1339        int res = native_getTextWidths(mNativePaint, text, index, count, widths);
1340        setTextSize(oldSize);
1341        for (int i=0; i<res; i++) {
1342            widths[i] *= mInvCompatScaling;
1343        }
1344        return res;
1345    }
1346
1347    /**
1348     * Return the advance widths for the characters in the string.
1349     *
1350     * @param text     The text to measure
1351     * @param start    The index of the first char to to measure
1352     * @param end      The end of the text slice to measure
1353     * @param widths   array to receive the advance widths of the characters.
1354     *                 Must be at least a large as (end - start).
1355     * @return         the actual number of widths returned.
1356     */
1357    public int getTextWidths(CharSequence text, int start, int end,
1358                             float[] widths) {
1359        if (text instanceof String) {
1360            return getTextWidths((String) text, start, end, widths);
1361        }
1362        if (text instanceof SpannedString ||
1363            text instanceof SpannableString) {
1364            return getTextWidths(text.toString(), start, end, widths);
1365        }
1366        if (text instanceof GraphicsOperations) {
1367            return ((GraphicsOperations) text).getTextWidths(start, end,
1368                                                                 widths, this);
1369        }
1370
1371        char[] buf = TemporaryBuffer.obtain(end - start);
1372        TextUtils.getChars(text, start, end, buf, 0);
1373        int result = getTextWidths(buf, 0, end - start, widths);
1374        TemporaryBuffer.recycle(buf);
1375        return result;
1376    }
1377
1378    /**
1379     * Return the advance widths for the characters in the string.
1380     *
1381     * @param text   The text to measure
1382     * @param start  The index of the first char to to measure
1383     * @param end    The end of the text slice to measure
1384     * @param widths array to receive the advance widths of the characters.
1385     *               Must be at least a large as the text.
1386     * @return       the number of unichars in the specified text.
1387     */
1388    public int getTextWidths(String text, int start, int end, float[] widths) {
1389        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1390            throw new IndexOutOfBoundsException();
1391        }
1392        if (end - start > widths.length) {
1393            throw new ArrayIndexOutOfBoundsException();
1394        }
1395
1396        if (!mHasCompatScaling) {
1397            return native_getTextWidths(mNativePaint, text, start, end, widths);
1398        }
1399        final float oldSize = getTextSize();
1400        setTextSize(oldSize*mCompatScaling);
1401        int res = native_getTextWidths(mNativePaint, text, start, end, widths);
1402        setTextSize(oldSize);
1403        for (int i=0; i<res; i++) {
1404            widths[i] *= mInvCompatScaling;
1405        }
1406        return res;
1407    }
1408
1409    /**
1410     * Return the advance widths for the characters in the string.
1411     *
1412     * @param text   The text to measure
1413     * @param widths array to receive the advance widths of the characters.
1414     *               Must be at least a large as the text.
1415     * @return       the number of unichars in the specified text.
1416     */
1417    public int getTextWidths(String text, float[] widths) {
1418        return getTextWidths(text, 0, text.length(), widths);
1419    }
1420
1421    /**
1422     * Convenience overload that takes a char array instead of a
1423     * String.
1424     *
1425     * @see #getTextRunAdvances(String, int, int, int, int, int, float[], int)
1426     * @hide
1427     */
1428    public float getTextRunAdvances(char[] chars, int index, int count,
1429            int contextIndex, int contextCount, int flags, float[] advances,
1430            int advancesIndex) {
1431
1432        if ((index | count | contextIndex | contextCount | advancesIndex
1433                | (index - contextIndex)
1434                | ((contextIndex + contextCount) - (index + count))
1435                | (chars.length - (contextIndex + contextCount))
1436                | (advances == null ? 0 :
1437                    (advances.length - (advancesIndex + count)))) < 0) {
1438            throw new IndexOutOfBoundsException();
1439        }
1440        if (flags != DIRECTION_LTR && flags != DIRECTION_RTL) {
1441            throw new IllegalArgumentException("unknown flags value: " + flags);
1442        }
1443
1444        if (!mHasCompatScaling) {
1445            return native_getTextRunAdvances(mNativePaint, chars, index, count,
1446                    contextIndex, contextCount, flags, advances, advancesIndex);
1447        }
1448
1449        final float oldSize = getTextSize();
1450        setTextSize(oldSize * mCompatScaling);
1451        float res = native_getTextRunAdvances(mNativePaint, chars, index, count,
1452                contextIndex, contextCount, flags, advances, advancesIndex);
1453        setTextSize(oldSize);
1454
1455        if (advances != null) {
1456            for (int i = advancesIndex, e = i + count; i < e; i++) {
1457                advances[i] *= mInvCompatScaling;
1458            }
1459        }
1460        return res * mInvCompatScaling; // assume errors are not significant
1461    }
1462
1463    /**
1464     * Convenience overload that takes a CharSequence instead of a
1465     * String.
1466     *
1467     * @see #getTextRunAdvances(String, int, int, int, int, int, float[], int)
1468     * @hide
1469     */
1470    public float getTextRunAdvances(CharSequence text, int start, int end,
1471            int contextStart, int contextEnd, int flags, float[] advances,
1472            int advancesIndex) {
1473
1474        if (text instanceof String) {
1475            return getTextRunAdvances((String) text, start, end,
1476                    contextStart, contextEnd, flags, advances, advancesIndex);
1477        }
1478        if (text instanceof SpannedString ||
1479            text instanceof SpannableString) {
1480            return getTextRunAdvances(text.toString(), start, end,
1481                    contextStart, contextEnd, flags, advances, advancesIndex);
1482        }
1483        if (text instanceof GraphicsOperations) {
1484            return ((GraphicsOperations) text).getTextRunAdvances(start, end,
1485                    contextStart, contextEnd, flags, advances, advancesIndex, this);
1486        }
1487
1488        int contextLen = contextEnd - contextStart;
1489        int len = end - start;
1490        char[] buf = TemporaryBuffer.obtain(contextLen);
1491        TextUtils.getChars(text, start, end, buf, 0);
1492        float result = getTextRunAdvances(buf, start - contextStart, len,
1493                0, contextLen, flags, advances, advancesIndex);
1494        TemporaryBuffer.recycle(buf);
1495        return result;
1496    }
1497
1498    /**
1499     * Returns the total advance width for the characters in the run
1500     * between start and end, and if advances is not null, the advance
1501     * assigned to each of these characters (java chars).
1502     *
1503     * <p>The trailing surrogate in a valid surrogate pair is assigned
1504     * an advance of 0.  Thus the number of returned advances is
1505     * always equal to count, not to the number of unicode codepoints
1506     * represented by the run.
1507     *
1508     * <p>In the case of conjuncts or combining marks, the total
1509     * advance is assigned to the first logical character, and the
1510     * following characters are assigned an advance of 0.
1511     *
1512     * <p>This generates the sum of the advances of glyphs for
1513     * characters in a reordered cluster as the width of the first
1514     * logical character in the cluster, and 0 for the widths of all
1515     * other characters in the cluster.  In effect, such clusters are
1516     * treated like conjuncts.
1517     *
1518     * <p>The shaping bounds limit the amount of context available
1519     * outside start and end that can be used for shaping analysis.
1520     * These bounds typically reflect changes in bidi level or font
1521     * metrics across which shaping does not occur.
1522     *
1523     * @param text the text to measure
1524     * @param start the index of the first character to measure
1525     * @param end the index past the last character to measure
1526     * @param contextStart the index of the first character to use for shaping context,
1527     * must be <= start
1528     * @param contextEnd the index past the last character to use for shaping context,
1529     * must be >= end
1530     * @param flags the flags to control the advances, either {@link #DIRECTION_LTR}
1531     * or {@link #DIRECTION_RTL}
1532     * @param advances array to receive the advances, must have room for all advances,
1533     * can be null if only total advance is needed
1534     * @param advancesIndex the position in advances at which to put the
1535     * advance corresponding to the character at start
1536     * @return the total advance
1537     *
1538     * @hide
1539     */
1540    public float getTextRunAdvances(String text, int start, int end, int contextStart,
1541            int contextEnd, int flags, float[] advances, int advancesIndex) {
1542
1543        if ((start | end | contextStart | contextEnd | advancesIndex | (end - start)
1544                | (start - contextStart) | (contextEnd - end)
1545                | (text.length() - contextEnd)
1546                | (advances == null ? 0 :
1547                    (advances.length - advancesIndex - (end - start)))) < 0) {
1548            throw new IndexOutOfBoundsException();
1549        }
1550        if (flags != DIRECTION_LTR && flags != DIRECTION_RTL) {
1551            throw new IllegalArgumentException("unknown flags value: " + flags);
1552        }
1553
1554        if (!mHasCompatScaling) {
1555            return native_getTextRunAdvances(mNativePaint, text, start, end,
1556                    contextStart, contextEnd, flags, advances, advancesIndex);
1557        }
1558
1559        final float oldSize = getTextSize();
1560        setTextSize(oldSize * mCompatScaling);
1561        float totalAdvance = native_getTextRunAdvances(mNativePaint, text, start, end,
1562                contextStart, contextEnd, flags, advances, advancesIndex);
1563        setTextSize(oldSize);
1564
1565        if (advances != null) {
1566            for (int i = advancesIndex, e = i + (end - start); i < e; i++) {
1567                advances[i] *= mInvCompatScaling;
1568            }
1569        }
1570        return totalAdvance * mInvCompatScaling; // assume errors are insignificant
1571    }
1572
1573    /**
1574     * Returns the next cursor position in the run.  This avoids placing the
1575     * cursor between surrogates, between characters that form conjuncts,
1576     * between base characters and combining marks, or within a reordering
1577     * cluster.
1578     *
1579     * <p>ContextStart and offset are relative to the start of text.
1580     * The context is the shaping context for cursor movement, generally
1581     * the bounds of the metric span enclosing the cursor in the direction of
1582     * movement.
1583     *
1584     * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
1585     * cursor position, this returns -1.  Otherwise this will never return a
1586     * value before contextStart or after contextStart + contextLength.
1587     *
1588     * @param text the text
1589     * @param contextStart the start of the context
1590     * @param contextLength the length of the context
1591     * @param flags either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR}
1592     * @param offset the cursor position to move from
1593     * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
1594     * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
1595     * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
1596     * @return the offset of the next position, or -1
1597     * @hide
1598     */
1599    public int getTextRunCursor(char[] text, int contextStart, int contextLength,
1600            int flags, int offset, int cursorOpt) {
1601        int contextEnd = contextStart + contextLength;
1602        if (((contextStart | contextEnd | offset | (contextEnd - contextStart)
1603                | (offset - contextStart) | (contextEnd - offset)
1604                | (text.length - contextEnd) | cursorOpt) < 0)
1605                || cursorOpt > CURSOR_OPT_MAX_VALUE) {
1606            throw new IndexOutOfBoundsException();
1607        }
1608
1609        return native_getTextRunCursor(mNativePaint, text,
1610                contextStart, contextLength, flags, offset, cursorOpt);
1611    }
1612
1613    /**
1614     * Returns the next cursor position in the run.  This avoids placing the
1615     * cursor between surrogates, between characters that form conjuncts,
1616     * between base characters and combining marks, or within a reordering
1617     * cluster.
1618     *
1619     * <p>ContextStart, contextEnd, and offset are relative to the start of
1620     * text.  The context is the shaping context for cursor movement, generally
1621     * the bounds of the metric span enclosing the cursor in the direction of
1622     * movement.
1623     *
1624     * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
1625     * cursor position, this returns -1.  Otherwise this will never return a
1626     * value before contextStart or after contextEnd.
1627     *
1628     * @param text the text
1629     * @param contextStart the start of the context
1630     * @param contextEnd the end of the context
1631     * @param flags either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR}
1632     * @param offset the cursor position to move from
1633     * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
1634     * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
1635     * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
1636     * @return the offset of the next position, or -1
1637     * @hide
1638     */
1639    public int getTextRunCursor(CharSequence text, int contextStart,
1640           int contextEnd, int flags, int offset, int cursorOpt) {
1641
1642        if (text instanceof String || text instanceof SpannedString ||
1643                text instanceof SpannableString) {
1644            return getTextRunCursor(text.toString(), contextStart, contextEnd,
1645                    flags, offset, cursorOpt);
1646        }
1647        if (text instanceof GraphicsOperations) {
1648            return ((GraphicsOperations) text).getTextRunCursor(
1649                    contextStart, contextEnd, flags, offset, cursorOpt, this);
1650        }
1651
1652        int contextLen = contextEnd - contextStart;
1653        char[] buf = TemporaryBuffer.obtain(contextLen);
1654        TextUtils.getChars(text, contextStart, contextEnd, buf, 0);
1655        int result = getTextRunCursor(buf, 0, contextLen, flags, offset, cursorOpt);
1656        TemporaryBuffer.recycle(buf);
1657        return result;
1658    }
1659
1660    /**
1661     * Returns the next cursor position in the run.  This avoids placing the
1662     * cursor between surrogates, between characters that form conjuncts,
1663     * between base characters and combining marks, or within a reordering
1664     * cluster.
1665     *
1666     * <p>ContextStart, contextEnd, and offset are relative to the start of
1667     * text.  The context is the shaping context for cursor movement, generally
1668     * the bounds of the metric span enclosing the cursor in the direction of
1669     * movement.
1670     *
1671     * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
1672     * cursor position, this returns -1.  Otherwise this will never return a
1673     * value before contextStart or after contextEnd.
1674     *
1675     * @param text the text
1676     * @param contextStart the start of the context
1677     * @param contextEnd the end of the context
1678     * @param flags either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR}
1679     * @param offset the cursor position to move from
1680     * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
1681     * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
1682     * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
1683     * @return the offset of the next position, or -1
1684     * @hide
1685     */
1686    public int getTextRunCursor(String text, int contextStart, int contextEnd,
1687            int flags, int offset, int cursorOpt) {
1688        if (((contextStart | contextEnd | offset | (contextEnd - contextStart)
1689                | (offset - contextStart) | (contextEnd - offset)
1690                | (text.length() - contextEnd) | cursorOpt) < 0)
1691                || cursorOpt > CURSOR_OPT_MAX_VALUE) {
1692            throw new IndexOutOfBoundsException();
1693        }
1694
1695        return native_getTextRunCursor(mNativePaint, text,
1696                contextStart, contextEnd, flags, offset, cursorOpt);
1697    }
1698
1699    /**
1700     * Return the path (outline) for the specified text.
1701     * Note: just like Canvas.drawText, this will respect the Align setting in
1702     * the paint.
1703     *
1704     * @param text     The text to retrieve the path from
1705     * @param index    The index of the first character in text
1706     * @param count    The number of characterss starting with index
1707     * @param x        The x coordinate of the text's origin
1708     * @param y        The y coordinate of the text's origin
1709     * @param path     The path to receive the data describing the text. Must
1710     *                 be allocated by the caller.
1711     */
1712    public void getTextPath(char[] text, int index, int count,
1713                            float x, float y, Path path) {
1714        if ((index | count) < 0 || index + count > text.length) {
1715            throw new ArrayIndexOutOfBoundsException();
1716        }
1717        native_getTextPath(mNativePaint, text, index, count, x, y, path.ni());
1718    }
1719
1720    /**
1721     * Return the path (outline) for the specified text.
1722     * Note: just like Canvas.drawText, this will respect the Align setting
1723     * in the paint.
1724     *
1725     * @param text  The text to retrieve the path from
1726     * @param start The first character in the text
1727     * @param end   1 past the last charcter in the text
1728     * @param x     The x coordinate of the text's origin
1729     * @param y     The y coordinate of the text's origin
1730     * @param path  The path to receive the data describing the text. Must
1731     *              be allocated by the caller.
1732     */
1733    public void getTextPath(String text, int start, int end,
1734                            float x, float y, Path path) {
1735        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1736            throw new IndexOutOfBoundsException();
1737        }
1738        native_getTextPath(mNativePaint, text, start, end, x, y, path.ni());
1739    }
1740
1741    /**
1742     * Return in bounds (allocated by the caller) the smallest rectangle that
1743     * encloses all of the characters, with an implied origin at (0,0).
1744     *
1745     * @param text  String to measure and return its bounds
1746     * @param start Index of the first char in the string to measure
1747     * @param end   1 past the last char in the string measure
1748     * @param bounds Returns the unioned bounds of all the text. Must be
1749     *               allocated by the caller.
1750     */
1751    public void getTextBounds(String text, int start, int end, Rect bounds) {
1752        if ((start | end | (end - start) | (text.length() - end)) < 0) {
1753            throw new IndexOutOfBoundsException();
1754        }
1755        if (bounds == null) {
1756            throw new NullPointerException("need bounds Rect");
1757        }
1758        nativeGetStringBounds(mNativePaint, text, start, end, bounds);
1759    }
1760
1761    /**
1762     * Return in bounds (allocated by the caller) the smallest rectangle that
1763     * encloses all of the characters, with an implied origin at (0,0).
1764     *
1765     * @param text  Array of chars to measure and return their unioned bounds
1766     * @param index Index of the first char in the array to measure
1767     * @param count The number of chars, beginning at index, to measure
1768     * @param bounds Returns the unioned bounds of all the text. Must be
1769     *               allocated by the caller.
1770     */
1771    public void getTextBounds(char[] text, int index, int count, Rect bounds) {
1772        if ((index | count) < 0 || index + count > text.length) {
1773            throw new ArrayIndexOutOfBoundsException();
1774        }
1775        if (bounds == null) {
1776            throw new NullPointerException("need bounds Rect");
1777        }
1778        nativeGetCharArrayBounds(mNativePaint, text, index, count, bounds);
1779    }
1780
1781    protected void finalize() throws Throwable {
1782        finalizer(mNativePaint);
1783    }
1784
1785    private static native int native_init();
1786    private static native int native_initWithPaint(int paint);
1787    private static native void native_reset(int native_object);
1788    private static native void native_set(int native_dst, int native_src);
1789    private static native int native_getStyle(int native_object);
1790    private static native void native_setStyle(int native_object, int style);
1791    private static native int native_getStrokeCap(int native_object);
1792    private static native void native_setStrokeCap(int native_object, int cap);
1793    private static native int native_getStrokeJoin(int native_object);
1794    private static native void native_setStrokeJoin(int native_object,
1795                                                    int join);
1796    private static native boolean native_getFillPath(int native_object,
1797                                                     int src, int dst);
1798    private static native int native_setShader(int native_object, int shader);
1799    private static native int native_setColorFilter(int native_object,
1800                                                    int filter);
1801    private static native int native_setXfermode(int native_object,
1802                                                 int xfermode);
1803    private static native int native_setPathEffect(int native_object,
1804                                                   int effect);
1805    private static native int native_setMaskFilter(int native_object,
1806                                                   int maskfilter);
1807    private static native int native_setTypeface(int native_object,
1808                                                 int typeface);
1809    private static native int native_setRasterizer(int native_object,
1810                                                   int rasterizer);
1811
1812    private static native int native_getTextAlign(int native_object);
1813    private static native void native_setTextAlign(int native_object,
1814                                                   int align);
1815
1816    private static native float native_getFontMetrics(int native_paint,
1817                                                      FontMetrics metrics);
1818    private static native int native_getTextWidths(int native_object,
1819                            char[] text, int index, int count, float[] widths);
1820    private static native int native_getTextWidths(int native_object,
1821                            String text, int start, int end, float[] widths);
1822
1823    private static native float native_getTextRunAdvances(int native_object,
1824            char[] text, int index, int count, int contextIndex, int contextCount,
1825            int flags, float[] advances, int advancesIndex);
1826    private static native float native_getTextRunAdvances(int native_object,
1827            String text, int start, int end, int contextStart, int contextEnd,
1828            int flags, float[] advances, int advancesIndex);
1829
1830    private native int native_getTextRunCursor(int native_object, char[] text,
1831            int contextStart, int contextLength, int flags, int offset, int cursorOpt);
1832    private native int native_getTextRunCursor(int native_object, String text,
1833            int contextStart, int contextEnd, int flags, int offset, int cursorOpt);
1834
1835    private static native void native_getTextPath(int native_object,
1836                char[] text, int index, int count, float x, float y, int path);
1837    private static native void native_getTextPath(int native_object,
1838                String text, int start, int end, float x, float y, int path);
1839    private static native void nativeGetStringBounds(int nativePaint,
1840                                String text, int start, int end, Rect bounds);
1841    private static native void nativeGetCharArrayBounds(int nativePaint,
1842                                char[] text, int index, int count, Rect bounds);
1843    private static native void finalizer(int nativePaint);
1844}
1845