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