SuggestionStripLayoutHelper.java revision 16ed1868a16455ef9f5485696309d518f80aea1c
1/*
2 * Copyright (C) 2013 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 com.android.inputmethod.latin.suggestions;
18
19import android.content.Context;
20import android.content.res.Resources;
21import android.content.res.TypedArray;
22import android.graphics.Bitmap;
23import android.graphics.Canvas;
24import android.graphics.Color;
25import android.graphics.Paint;
26import android.graphics.Paint.Align;
27import android.graphics.Rect;
28import android.graphics.Typeface;
29import android.graphics.drawable.BitmapDrawable;
30import android.graphics.drawable.Drawable;
31import android.text.Spannable;
32import android.text.SpannableString;
33import android.text.Spanned;
34import android.text.TextPaint;
35import android.text.TextUtils;
36import android.text.style.CharacterStyle;
37import android.text.style.StyleSpan;
38import android.text.style.UnderlineSpan;
39import android.util.AttributeSet;
40import android.view.Gravity;
41import android.view.LayoutInflater;
42import android.view.View;
43import android.view.View.OnClickListener;
44import android.view.ViewGroup;
45import android.widget.LinearLayout;
46import android.widget.TextView;
47
48import com.android.inputmethod.latin.LatinImeLogger;
49import com.android.inputmethod.latin.R;
50import com.android.inputmethod.latin.SuggestedWords;
51import com.android.inputmethod.latin.utils.AutoCorrectionUtils;
52import com.android.inputmethod.latin.utils.ResourceUtils;
53import com.android.inputmethod.latin.utils.ViewLayoutUtils;
54
55import java.util.ArrayList;
56
57final class SuggestionStripLayoutHelper {
58    private static final int DEFAULT_SUGGESTIONS_COUNT_IN_STRIP = 3;
59    private static final float DEFAULT_CENTER_SUGGESTION_PERCENTILE = 0.40f;
60    private static final int DEFAULT_MAX_MORE_SUGGESTIONS_ROW = 2;
61    private static final int PUNCTUATIONS_IN_STRIP = 5;
62    private static final float MIN_TEXT_XSCALE = 0.70f;
63
64    public final int mPadding;
65    public final int mDividerWidth;
66    public final int mSuggestionsStripHeight;
67    public final int mSuggestionsCountInStrip;
68    public final int mMoreSuggestionsRowHeight;
69    private int mMaxMoreSuggestionsRow;
70    public final float mMinMoreSuggestionsWidth;
71    public final int mMoreSuggestionsBottomGap;
72    public boolean mMoreSuggestionsAvailable;
73
74    // The index of these {@link ArrayList} is the position in the suggestion strip. The indices
75    // increase towards the right for LTR scripts and the left for RTL scripts, starting with 0.
76    // The position of the most important suggestion is in {@link #mCenterPositionInStrip}
77    private final ArrayList<TextView> mWordViews;
78    private final ArrayList<View> mDividerViews;
79    private final ArrayList<TextView> mDebugInfoViews;
80
81    private final int mColorValidTypedWord;
82    private final int mColorTypedWord;
83    private final int mColorAutoCorrect;
84    private final int mColorSuggested;
85    private final float mAlphaObsoleted;
86    private final float mCenterSuggestionWeight;
87    private final int mCenterPositionInStrip;
88    private final int mTypedWordPositionWhenAutocorrect;
89    private final Drawable mMoreSuggestionsHint;
90    private static final String MORE_SUGGESTIONS_HINT = "\u2026";
91    private static final String LEFTWARDS_ARROW = "\u2190";
92
93    private static final CharacterStyle BOLD_SPAN = new StyleSpan(Typeface.BOLD);
94    private static final CharacterStyle UNDERLINE_SPAN = new UnderlineSpan();
95
96    private final int mSuggestionStripOption;
97    // These constants are the flag values of
98    // {@link R.styleable#SuggestionStripView_suggestionStripOption} attribute.
99    private static final int AUTO_CORRECT_BOLD = 0x01;
100    private static final int AUTO_CORRECT_UNDERLINE = 0x02;
101    private static final int VALID_TYPED_WORD_BOLD = 0x04;
102
103    private final TextView mWordToSaveView;
104    private final TextView mLeftwardsArrowView;
105    private final TextView mHintToSaveView;
106
107    public SuggestionStripLayoutHelper(final Context context, final AttributeSet attrs,
108            final int defStyle, final ArrayList<TextView> wordViews,
109            final ArrayList<View> dividerViews, final ArrayList<TextView> debugInfoViews) {
110        mWordViews = wordViews;
111        mDividerViews = dividerViews;
112        mDebugInfoViews = debugInfoViews;
113
114        final TextView wordView = wordViews.get(0);
115        final View dividerView = dividerViews.get(0);
116        mPadding = wordView.getCompoundPaddingLeft() + wordView.getCompoundPaddingRight();
117        dividerView.measure(
118                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
119        mDividerWidth = dividerView.getMeasuredWidth();
120
121        final Resources res = wordView.getResources();
122        mSuggestionsStripHeight = res.getDimensionPixelSize(R.dimen.suggestions_strip_height);
123
124        final TypedArray a = context.obtainStyledAttributes(attrs,
125                R.styleable.SuggestionStripView, defStyle, R.style.SuggestionStripView);
126        mSuggestionStripOption = a.getInt(
127                R.styleable.SuggestionStripView_suggestionStripOption, 0);
128        mAlphaObsoleted = ResourceUtils.getFraction(a,
129                R.styleable.SuggestionStripView_alphaObsoleted, 1.0f);
130        mColorValidTypedWord = a.getColor(R.styleable.SuggestionStripView_colorValidTypedWord, 0);
131        mColorTypedWord = a.getColor(R.styleable.SuggestionStripView_colorTypedWord, 0);
132        mColorAutoCorrect = a.getColor(R.styleable.SuggestionStripView_colorAutoCorrect, 0);
133        mColorSuggested = a.getColor(R.styleable.SuggestionStripView_colorSuggested, 0);
134        mSuggestionsCountInStrip = a.getInt(
135                R.styleable.SuggestionStripView_suggestionsCountInStrip,
136                DEFAULT_SUGGESTIONS_COUNT_IN_STRIP);
137        mCenterSuggestionWeight = ResourceUtils.getFraction(a,
138                R.styleable.SuggestionStripView_centerSuggestionPercentile,
139                DEFAULT_CENTER_SUGGESTION_PERCENTILE);
140        mMaxMoreSuggestionsRow = a.getInt(
141                R.styleable.SuggestionStripView_maxMoreSuggestionsRow,
142                DEFAULT_MAX_MORE_SUGGESTIONS_ROW);
143        mMinMoreSuggestionsWidth = ResourceUtils.getFraction(a,
144                R.styleable.SuggestionStripView_minMoreSuggestionsWidth, 1.0f);
145        a.recycle();
146
147        mMoreSuggestionsHint = getMoreSuggestionsHint(res,
148                res.getDimension(R.dimen.more_suggestions_hint_text_size), mColorAutoCorrect);
149        mCenterPositionInStrip = mSuggestionsCountInStrip / 2;
150        // Assuming there are at least three suggestions. Also, note that the suggestions are
151        // laid out according to script direction, so this is left of the center for LTR scripts
152        // and right of the center for RTL scripts.
153        mTypedWordPositionWhenAutocorrect = mCenterPositionInStrip - 1;
154        mMoreSuggestionsBottomGap = res.getDimensionPixelOffset(
155                R.dimen.more_suggestions_bottom_gap);
156        mMoreSuggestionsRowHeight = res.getDimensionPixelSize(R.dimen.more_suggestions_row_height);
157
158        final LayoutInflater inflater = LayoutInflater.from(context);
159        mWordToSaveView = (TextView)inflater.inflate(R.layout.suggestion_word, null);
160        mLeftwardsArrowView = (TextView)inflater.inflate(R.layout.hint_add_to_dictionary, null);
161        mHintToSaveView = (TextView)inflater.inflate(R.layout.hint_add_to_dictionary, null);
162    }
163
164    public int getMaxMoreSuggestionsRow() {
165        return mMaxMoreSuggestionsRow;
166    }
167
168    public void setMoreSuggestionsHeight(final int remainingHeight) {
169        mMaxMoreSuggestionsRow = (remainingHeight - mMoreSuggestionsBottomGap)
170                / mMoreSuggestionsRowHeight;
171    }
172
173    private static Drawable getMoreSuggestionsHint(final Resources res, final float textSize,
174            final int color) {
175        final Paint paint = new Paint();
176        paint.setAntiAlias(true);
177        paint.setTextAlign(Align.CENTER);
178        paint.setTextSize(textSize);
179        paint.setColor(color);
180        final Rect bounds = new Rect();
181        paint.getTextBounds(MORE_SUGGESTIONS_HINT, 0, MORE_SUGGESTIONS_HINT.length(), bounds);
182        final int width = Math.round(bounds.width() + 0.5f);
183        final int height = Math.round(bounds.height() + 0.5f);
184        final Bitmap buffer = Bitmap.createBitmap(width, (height * 3 / 2), Bitmap.Config.ARGB_8888);
185        final Canvas canvas = new Canvas(buffer);
186        canvas.drawText(MORE_SUGGESTIONS_HINT, width / 2, height, paint);
187        return new BitmapDrawable(res, buffer);
188    }
189
190    private CharSequence getStyledSuggestedWord(final SuggestedWords suggestedWords,
191            final int indexInSuggestedWords) {
192        if (indexInSuggestedWords >= suggestedWords.size()) {
193            return null;
194        }
195        final String word = suggestedWords.getWord(indexInSuggestedWords);
196        final boolean isAutoCorrect = indexInSuggestedWords == 1
197                && suggestedWords.willAutoCorrect();
198        final boolean isTypedWordValid = indexInSuggestedWords == 0
199                && suggestedWords.mTypedWordValid;
200        if (!isAutoCorrect && !isTypedWordValid) {
201            return word;
202        }
203
204        final int len = word.length();
205        final Spannable spannedWord = new SpannableString(word);
206        final int option = mSuggestionStripOption;
207        if ((isAutoCorrect && (option & AUTO_CORRECT_BOLD) != 0)
208                || (isTypedWordValid && (option & VALID_TYPED_WORD_BOLD) != 0)) {
209            spannedWord.setSpan(BOLD_SPAN, 0, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
210        }
211        if (isAutoCorrect && (option & AUTO_CORRECT_UNDERLINE) != 0) {
212            spannedWord.setSpan(UNDERLINE_SPAN, 0, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
213        }
214        return spannedWord;
215    }
216
217    private int getPositionInSuggestionStrip(final int indexInSuggestedWords,
218            final SuggestedWords suggestedWords) {
219        final int indexToDisplayMostImportantSuggestion;
220        final int indexToDisplaySecondMostImportantSuggestion;
221        if (suggestedWords.willAutoCorrect()) {
222            indexToDisplayMostImportantSuggestion = SuggestedWords.INDEX_OF_AUTO_CORRECTION;
223            indexToDisplaySecondMostImportantSuggestion = SuggestedWords.INDEX_OF_TYPED_WORD;
224        } else {
225            indexToDisplayMostImportantSuggestion = SuggestedWords.INDEX_OF_TYPED_WORD;
226            indexToDisplaySecondMostImportantSuggestion = SuggestedWords.INDEX_OF_AUTO_CORRECTION;
227        }
228        if (indexInSuggestedWords == indexToDisplayMostImportantSuggestion) {
229            return mCenterPositionInStrip;
230        }
231        if (indexInSuggestedWords == indexToDisplaySecondMostImportantSuggestion) {
232            return mTypedWordPositionWhenAutocorrect;
233        }
234        // If neither of those, the order in the suggestion strip is the same as in SuggestedWords.
235        return indexInSuggestedWords;
236    }
237
238    private int getSuggestionTextColor(final int indexInSuggestedWords,
239            final SuggestedWords suggestedWords) {
240        final int positionInStrip =
241                getPositionInSuggestionStrip(indexInSuggestedWords, suggestedWords);
242        // TODO: Need to revisit this logic with bigram suggestions
243        final boolean isSuggested = (indexInSuggestedWords != SuggestedWords.INDEX_OF_TYPED_WORD);
244
245        final int color;
246        if (positionInStrip == mCenterPositionInStrip && suggestedWords.willAutoCorrect()) {
247            color = mColorAutoCorrect;
248        } else if (positionInStrip == mCenterPositionInStrip && suggestedWords.mTypedWordValid) {
249            color = mColorValidTypedWord;
250        } else if (isSuggested) {
251            color = mColorSuggested;
252        } else {
253            color = mColorTypedWord;
254        }
255        if (LatinImeLogger.sDBG && suggestedWords.size() > 1) {
256            // If we auto-correct, then the autocorrection is in slot 0 and the typed word
257            // is in slot 1.
258            if (positionInStrip == mCenterPositionInStrip
259                    && AutoCorrectionUtils.shouldBlockAutoCorrectionBySafetyNet(
260                            suggestedWords.getWord(SuggestedWords.INDEX_OF_AUTO_CORRECTION),
261                            suggestedWords.getWord(SuggestedWords.INDEX_OF_TYPED_WORD))) {
262                return 0xFFFF0000;
263            }
264        }
265
266        if (suggestedWords.mIsObsoleteSuggestions && isSuggested) {
267            return applyAlpha(color, mAlphaObsoleted);
268        }
269        return color;
270    }
271
272    private static int applyAlpha(final int color, final float alpha) {
273        final int newAlpha = (int)(Color.alpha(color) * alpha);
274        return Color.argb(newAlpha, Color.red(color), Color.green(color), Color.blue(color));
275    }
276
277    private static void addDivider(final ViewGroup stripView, final View dividerView) {
278        stripView.addView(dividerView);
279        final LinearLayout.LayoutParams params =
280                (LinearLayout.LayoutParams)dividerView.getLayoutParams();
281        params.gravity = Gravity.CENTER;
282    }
283
284    public void layout(final SuggestedWords suggestedWords, final ViewGroup stripView,
285            final ViewGroup placerView) {
286        if (suggestedWords.mIsPunctuationSuggestions) {
287            layoutPunctuationSuggestions(suggestedWords, stripView);
288            return;
289        }
290
291        final int countInStrip = mSuggestionsCountInStrip;
292        setupWordViewsTextAndColor(suggestedWords, countInStrip);
293        final TextView centerWordView = mWordViews.get(mCenterPositionInStrip);
294        final int stripWidth = placerView.getWidth();
295        final int centerWidth = getSuggestionWidth(mCenterPositionInStrip, stripWidth);
296        if (getTextScaleX(centerWordView.getText(), centerWidth, centerWordView.getPaint())
297                < MIN_TEXT_XSCALE) {
298            // Layout only the most relevant suggested word at the center of the suggestion strip
299            // by consolidating all slots in the strip.
300            mMoreSuggestionsAvailable = (suggestedWords.size() > 1);
301            layoutWord(mCenterPositionInStrip, stripWidth);
302            stripView.addView(centerWordView);
303            setLayoutWeight(centerWordView, 1.0f, ViewGroup.LayoutParams.MATCH_PARENT);
304            if (SuggestionStripView.DBG) {
305                layoutDebugInfo(mCenterPositionInStrip, placerView, stripWidth);
306            }
307            return;
308        }
309
310        mMoreSuggestionsAvailable = (suggestedWords.size() > countInStrip);
311        int x = 0;
312        for (int positionInStrip = 0; positionInStrip < countInStrip; positionInStrip++) {
313            if (positionInStrip != 0) {
314                final View divider = mDividerViews.get(positionInStrip);
315                // Add divider if this isn't the left most suggestion in suggestions strip.
316                addDivider(stripView, divider);
317                x += divider.getMeasuredWidth();
318            }
319
320            final int width = getSuggestionWidth(positionInStrip, stripWidth);
321            final TextView wordView = layoutWord(positionInStrip, width);
322            stripView.addView(wordView);
323            setLayoutWeight(wordView, getSuggestionWeight(positionInStrip),
324                    ViewGroup.LayoutParams.MATCH_PARENT);
325            x += wordView.getMeasuredWidth();
326
327            if (SuggestionStripView.DBG) {
328                layoutDebugInfo(positionInStrip, placerView, x);
329            }
330        }
331    }
332
333    /**
334     * Format appropriately the suggested word in {@link #mWordViews} specified by
335     * <code>positionInStrip</code>. When the suggested word doesn't exist, the corresponding
336     * {@link TextView} will be disabled and never respond to user interaction. The suggested word
337     * may be shrunk or ellipsized to fit in the specified width.
338     *
339     * The <code>positionInStrip</code> argument is the index in the suggestion strip. The indices
340     * increase towards the right for LTR scripts and the left for RTL scripts, starting with 0.
341     * The position of the most important suggestion is in {@link #mCenterPositionInStrip}. This
342     * usually doesn't match the index in <code>suggedtedWords</code> -- see
343     * {@link #getPositionInSuggestionStrip(int,SuggestedWords)}.
344     *
345     * @param positionInStrip the position in the suggestion strip.
346     * @param width the maximum width for layout in pixels.
347     * @return the {@link TextView} containing the suggested word appropriately formatted.
348     */
349    private TextView layoutWord(final int positionInStrip, final int width) {
350        final TextView wordView = mWordViews.get(positionInStrip);
351        final CharSequence word = wordView.getText();
352        if (positionInStrip == mCenterPositionInStrip && mMoreSuggestionsAvailable) {
353            // TODO: This "more suggestions hint" should have a nicely designed icon.
354            wordView.setCompoundDrawablesWithIntrinsicBounds(
355                    null, null, null, mMoreSuggestionsHint);
356            // HACK: Align with other TextViews that have no compound drawables.
357            wordView.setCompoundDrawablePadding(-mMoreSuggestionsHint.getIntrinsicHeight());
358        } else {
359            wordView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
360        }
361
362        // Disable this suggestion if the suggestion is null or empty.
363        wordView.setEnabled(!TextUtils.isEmpty(word));
364        final CharSequence text = getEllipsizedText(word, width, wordView.getPaint());
365        final float scaleX = wordView.getTextScaleX();
366        wordView.setText(text); // TextView.setText() resets text scale x to 1.0.
367        wordView.setTextScaleX(scaleX);
368        return wordView;
369    }
370
371    private void layoutDebugInfo(final int positionInStrip, final ViewGroup placerView,
372            final int x) {
373        final TextView debugInfoView = mDebugInfoViews.get(positionInStrip);
374        final CharSequence debugInfo = debugInfoView.getText();
375        if (debugInfo == null) {
376            return;
377        }
378        placerView.addView(debugInfoView);
379        debugInfoView.measure(
380                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
381        final int infoWidth = debugInfoView.getMeasuredWidth();
382        final int y = debugInfoView.getMeasuredHeight();
383        ViewLayoutUtils.placeViewAt(
384                debugInfoView, x - infoWidth, y, infoWidth, debugInfoView.getMeasuredHeight());
385    }
386
387    private int getSuggestionWidth(final int positionInStrip, final int maxWidth) {
388        final int paddings = mPadding * mSuggestionsCountInStrip;
389        final int dividers = mDividerWidth * (mSuggestionsCountInStrip - 1);
390        final int availableWidth = maxWidth - paddings - dividers;
391        return (int)(availableWidth * getSuggestionWeight(positionInStrip));
392    }
393
394    private float getSuggestionWeight(final int positionInStrip) {
395        if (positionInStrip == mCenterPositionInStrip) {
396            return mCenterSuggestionWeight;
397        }
398        // TODO: Revisit this for cases of 5 or more suggestions
399        return (1.0f - mCenterSuggestionWeight) / (mSuggestionsCountInStrip - 1);
400    }
401
402    private void setupWordViewsTextAndColor(final SuggestedWords suggestedWords,
403            final int countInStrip) {
404        // Clear all suggestions first
405        for (int positionInStrip = 0; positionInStrip < countInStrip; ++positionInStrip) {
406            mWordViews.get(positionInStrip).setText(null);
407            // Make this inactive for touches in {@link #layoutWord(int,int)}.
408            if (SuggestionStripView.DBG) {
409                mDebugInfoViews.get(positionInStrip).setText(null);
410            }
411        }
412        final int count = Math.min(suggestedWords.size(), countInStrip);
413        for (int indexInSuggestedWords = 0; indexInSuggestedWords < count;
414                indexInSuggestedWords++) {
415            final int positionInStrip =
416                    getPositionInSuggestionStrip(indexInSuggestedWords, suggestedWords);
417            final TextView wordView = mWordViews.get(positionInStrip);
418            // {@link TextView#getTag()} is used to get the index in suggestedWords at
419            // {@link SuggestionStripView#onClick(View)}.
420            wordView.setTag(indexInSuggestedWords);
421            wordView.setText(getStyledSuggestedWord(suggestedWords, indexInSuggestedWords));
422            wordView.setTextColor(getSuggestionTextColor(positionInStrip, suggestedWords));
423            if (SuggestionStripView.DBG) {
424                mDebugInfoViews.get(positionInStrip).setText(
425                        suggestedWords.getDebugString(indexInSuggestedWords));
426            }
427        }
428    }
429
430    private void layoutPunctuationSuggestions(final SuggestedWords suggestedWords,
431            final ViewGroup stripView) {
432        final int countInStrip = Math.min(suggestedWords.size(), PUNCTUATIONS_IN_STRIP);
433        for (int positionInStrip = 0; positionInStrip < countInStrip; positionInStrip++) {
434            if (positionInStrip != 0) {
435                // Add divider if this isn't the left most suggestion in suggestions strip.
436                addDivider(stripView, mDividerViews.get(positionInStrip));
437            }
438
439            final TextView wordView = mWordViews.get(positionInStrip);
440            wordView.setEnabled(true);
441            wordView.setTextColor(mColorAutoCorrect);
442            // {@link TextView#getTag()} is used to get the index in suggestedWords at
443            // {@link SuggestionStripView#onClick(View)}.
444            wordView.setTag(positionInStrip);
445            wordView.setText(suggestedWords.getWord(positionInStrip));
446            wordView.setTextScaleX(1.0f);
447            wordView.setCompoundDrawables(null, null, null, null);
448            stripView.addView(wordView);
449            setLayoutWeight(wordView, 1.0f, mSuggestionsStripHeight);
450        }
451        mMoreSuggestionsAvailable = (suggestedWords.size() > countInStrip);
452    }
453
454    public void layoutAddToDictionaryHint(final String word, final ViewGroup stripView,
455            final int stripWidth, final CharSequence hintText, final OnClickListener listener) {
456        final int width = stripWidth - mDividerWidth - mPadding * 2;
457
458        final TextView wordView = mWordToSaveView;
459        wordView.setTextColor(mColorTypedWord);
460        final int wordWidth = (int)(width * mCenterSuggestionWeight);
461        final CharSequence text = getEllipsizedText(word, wordWidth, wordView.getPaint());
462        final float wordScaleX = wordView.getTextScaleX();
463        // {@link TextView#setTag()} is used to hold the word to be added to dictionary. The word
464        // will be extracted at {@link #getAddToDictionaryWord()}.
465        wordView.setTag(word);
466        wordView.setText(text);
467        wordView.setTextScaleX(wordScaleX);
468        stripView.addView(wordView);
469        setLayoutWeight(wordView, mCenterSuggestionWeight, ViewGroup.LayoutParams.MATCH_PARENT);
470
471        stripView.addView(mDividerViews.get(0));
472
473        final TextView leftArrowView = mLeftwardsArrowView;
474        leftArrowView.setTextColor(mColorAutoCorrect);
475        leftArrowView.setText(LEFTWARDS_ARROW);
476        stripView.addView(leftArrowView);
477
478        final TextView hintView = mHintToSaveView;
479        hintView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
480        hintView.setTextColor(mColorAutoCorrect);
481        final int hintWidth = width - wordWidth - leftArrowView.getWidth();
482        final float hintScaleX = getTextScaleX(hintText, hintWidth, hintView.getPaint());
483        hintView.setText(hintText);
484        hintView.setTextScaleX(hintScaleX);
485        stripView.addView(hintView);
486        setLayoutWeight(
487                hintView, 1.0f - mCenterSuggestionWeight, ViewGroup.LayoutParams.MATCH_PARENT);
488
489        wordView.setOnClickListener(listener);
490        leftArrowView.setOnClickListener(listener);
491        hintView.setOnClickListener(listener);
492    }
493
494    public String getAddToDictionaryWord() {
495        // String tag is set at
496        // {@link #layoutAddToDictionaryHint(String,ViewGroup,int,CharSequence,OnClickListener}.
497        return (String)mWordToSaveView.getTag();
498    }
499
500    public boolean isAddToDictionaryShowing(final View v) {
501        return v == mWordToSaveView || v == mHintToSaveView || v == mLeftwardsArrowView;
502    }
503
504    private static void setLayoutWeight(final View v, final float weight, final int height) {
505        final ViewGroup.LayoutParams lp = v.getLayoutParams();
506        if (lp instanceof LinearLayout.LayoutParams) {
507            final LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams)lp;
508            llp.weight = weight;
509            llp.width = 0;
510            llp.height = height;
511        }
512    }
513
514    private static float getTextScaleX(final CharSequence text, final int maxWidth,
515            final TextPaint paint) {
516        paint.setTextScaleX(1.0f);
517        final int width = getTextWidth(text, paint);
518        if (width <= maxWidth) {
519            return 1.0f;
520        }
521        return maxWidth / (float)width;
522    }
523
524    private static CharSequence getEllipsizedText(final CharSequence text, final int maxWidth,
525            final TextPaint paint) {
526        if (text == null) {
527            return null;
528        }
529        final float scaleX = getTextScaleX(text, maxWidth, paint);
530        if (scaleX >= MIN_TEXT_XSCALE) {
531            paint.setTextScaleX(scaleX);
532            return text;
533        }
534
535        // Note that TextUtils.ellipsize() use text-x-scale as 1.0 if ellipsize is needed. To
536        // get squeezed and ellipsized text, passes enlarged width (maxWidth / MIN_TEXT_XSCALE).
537        final CharSequence ellipsized = TextUtils.ellipsize(
538                text, paint, maxWidth / MIN_TEXT_XSCALE, TextUtils.TruncateAt.MIDDLE);
539        paint.setTextScaleX(MIN_TEXT_XSCALE);
540        return ellipsized;
541    }
542
543    private static int getTextWidth(final CharSequence text, final TextPaint paint) {
544        if (TextUtils.isEmpty(text)) {
545            return 0;
546        }
547        final Typeface savedTypeface = paint.getTypeface();
548        paint.setTypeface(getTextTypeface(text));
549        final int len = text.length();
550        final float[] widths = new float[len];
551        final int count = paint.getTextWidths(text, 0, len, widths);
552        int width = 0;
553        for (int i = 0; i < count; i++) {
554            width += Math.round(widths[i] + 0.5f);
555        }
556        paint.setTypeface(savedTypeface);
557        return width;
558    }
559
560    private static Typeface getTextTypeface(final CharSequence text) {
561        if (!(text instanceof SpannableString)) {
562            return Typeface.DEFAULT;
563        }
564
565        final SpannableString ss = (SpannableString)text;
566        final StyleSpan[] styles = ss.getSpans(0, text.length(), StyleSpan.class);
567        if (styles.length == 0) {
568            return Typeface.DEFAULT;
569        }
570
571        if (styles[0].getStyle() == Typeface.BOLD) {
572            return Typeface.DEFAULT_BOLD;
573        }
574        // TODO: BOLD_ITALIC, ITALIC case?
575        return Typeface.DEFAULT;
576    }
577}
578