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