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.text.style;
18
19import android.graphics.Paint;
20import android.graphics.Typeface;
21import android.os.Parcel;
22import android.text.ParcelableSpan;
23import android.text.TextPaint;
24import android.text.TextUtils;
25
26/**
27 * Changes the typeface family of the text to which the span is attached.
28 */
29public class TypefaceSpan extends MetricAffectingSpan implements ParcelableSpan {
30    private final String mFamily;
31
32    /**
33     * @param family The font family for this typeface.  Examples include
34     * "monospace", "serif", and "sans-serif".
35     */
36    public TypefaceSpan(String family) {
37        mFamily = family;
38    }
39
40    public TypefaceSpan(Parcel src) {
41        mFamily = src.readString();
42    }
43
44    public int getSpanTypeId() {
45        return getSpanTypeIdInternal();
46    }
47
48    /** @hide */
49    public int getSpanTypeIdInternal() {
50        return TextUtils.TYPEFACE_SPAN;
51    }
52
53    public int describeContents() {
54        return 0;
55    }
56
57    public void writeToParcel(Parcel dest, int flags) {
58        writeToParcelInternal(dest, flags);
59    }
60
61    /** @hide */
62    public void writeToParcelInternal(Parcel dest, int flags) {
63        dest.writeString(mFamily);
64    }
65
66    /**
67     * Returns the font family name.
68     */
69    public String getFamily() {
70        return mFamily;
71    }
72
73    @Override
74    public void updateDrawState(TextPaint ds) {
75        apply(ds, mFamily);
76    }
77
78    @Override
79    public void updateMeasureState(TextPaint paint) {
80        apply(paint, mFamily);
81    }
82
83    private static void apply(Paint paint, String family) {
84        int oldStyle;
85
86        Typeface old = paint.getTypeface();
87        if (old == null) {
88            oldStyle = 0;
89        } else {
90            oldStyle = old.getStyle();
91        }
92
93        Typeface tf = Typeface.create(family, oldStyle);
94        int fake = oldStyle & ~tf.getStyle();
95
96        if ((fake & Typeface.BOLD) != 0) {
97            paint.setFakeBoldText(true);
98        }
99
100        if ((fake & Typeface.ITALIC) != 0) {
101            paint.setTextSkewX(-0.25f);
102        }
103
104        paint.setTypeface(tf);
105    }
106}
107