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