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