TimePickerClockDelegate.java revision d9f3fdf45bd3e3b5b02f2d21b6df6598cbaf1c70
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 android.widget;
18
19import android.content.Context;
20import android.content.res.ColorStateList;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.os.Parcel;
25import android.os.Parcelable;
26import android.text.format.DateFormat;
27import android.text.format.DateUtils;
28import android.util.AttributeSet;
29import android.util.Log;
30import android.util.TypedValue;
31import android.view.HapticFeedbackConstants;
32import android.view.KeyCharacterMap;
33import android.view.KeyEvent;
34import android.view.LayoutInflater;
35import android.view.View;
36import android.view.ViewGroup;
37import android.view.accessibility.AccessibilityEvent;
38import android.view.accessibility.AccessibilityNodeInfo;
39
40import com.android.internal.R;
41
42import java.util.ArrayList;
43import java.util.Calendar;
44import java.util.Locale;
45
46/**
47 * A delegate implementing the radial clock-based TimePicker.
48 */
49class TimePickerClockDelegate extends TimePicker.AbstractTimePickerDelegate implements
50        RadialTimePickerView.OnValueSelectedListener {
51
52    private static final String TAG = "TimePickerClockDelegate";
53
54    // Index used by RadialPickerLayout
55    private static final int HOUR_INDEX = 0;
56    private static final int MINUTE_INDEX = 1;
57
58    // NOT a real index for the purpose of what's showing.
59    private static final int AMPM_INDEX = 2;
60
61    // Also NOT a real index, just used for keyboard mode.
62    private static final int ENABLE_PICKER_INDEX = 3;
63
64    static final int AM = 0;
65    static final int PM = 1;
66
67    private static final boolean DEFAULT_ENABLED_STATE = true;
68    private boolean mIsEnabled = DEFAULT_ENABLED_STATE;
69
70    private static final int HOURS_IN_HALF_DAY = 12;
71
72    private final View mHeaderView;
73    private final TextView mHourView;
74    private final TextView mMinuteView;
75    private final View mAmPmLayout;
76    private final CheckedTextView mAmLabel;
77    private final CheckedTextView mPmLabel;
78    private final RadialTimePickerView mRadialTimePickerView;
79    private final TextView mSeparatorView;
80
81    private final String mAmText;
82    private final String mPmText;
83
84    private final float mDisabledAlpha;
85
86    private boolean mAllowAutoAdvance;
87    private int mInitialHourOfDay;
88    private int mInitialMinute;
89    private boolean mIs24HourView;
90
91    // For hardware IME input.
92    private char mPlaceholderText;
93    private String mDoublePlaceholderText;
94    private String mDeletedKeyFormat;
95    private boolean mInKbMode;
96    private ArrayList<Integer> mTypedTimes = new ArrayList<Integer>();
97    private Node mLegalTimesTree;
98    private int mAmKeyCode;
99    private int mPmKeyCode;
100
101    // Accessibility strings.
102    private String mSelectHours;
103    private String mSelectMinutes;
104
105    // Most recent time announcement values for accessibility.
106    private CharSequence mLastAnnouncedText;
107    private boolean mLastAnnouncedIsHour;
108
109    private Calendar mTempCalendar;
110
111    public TimePickerClockDelegate(TimePicker delegator, Context context, AttributeSet attrs,
112            int defStyleAttr, int defStyleRes) {
113        super(delegator, context);
114
115        // process style attributes
116        final TypedArray a = mContext.obtainStyledAttributes(attrs,
117                R.styleable.TimePicker, defStyleAttr, defStyleRes);
118        final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
119                Context.LAYOUT_INFLATER_SERVICE);
120        final Resources res = mContext.getResources();
121
122        mSelectHours = res.getString(R.string.select_hours);
123        mSelectMinutes = res.getString(R.string.select_minutes);
124
125        String[] amPmStrings = TimePickerSpinnerDelegate.getAmPmStrings(context);
126        mAmText = amPmStrings[0];
127        mPmText = amPmStrings[1];
128
129        final int layoutResourceId = a.getResourceId(R.styleable.TimePicker_internalLayout,
130                R.layout.time_picker_holo);
131        final View mainView = inflater.inflate(layoutResourceId, delegator);
132
133        mHeaderView = mainView.findViewById(R.id.time_header);
134        mHeaderView.setBackground(a.getDrawable(R.styleable.TimePicker_headerBackground));
135
136        // Set up hour/minute labels.
137        mHourView = (TextView) mHeaderView.findViewById(R.id.hours);
138        mHourView.setOnClickListener(mClickListener);
139        mSeparatorView = (TextView) mHeaderView.findViewById(R.id.separator);
140        mMinuteView = (TextView) mHeaderView.findViewById(R.id.minutes);
141        mMinuteView.setOnClickListener(mClickListener);
142
143        final int headerTimeTextAppearance = a.getResourceId(
144                R.styleable.TimePicker_headerTimeTextAppearance, 0);
145        if (headerTimeTextAppearance != 0) {
146            mHourView.setTextAppearance(context, headerTimeTextAppearance);
147            mSeparatorView.setTextAppearance(context, headerTimeTextAppearance);
148            mMinuteView.setTextAppearance(context, headerTimeTextAppearance);
149        }
150
151        // Now that we have text appearances out of the way, make sure the hour
152        // and minute views are correctly sized.
153        mHourView.setMinWidth(computeStableWidth(mHourView, 24));
154        mMinuteView.setMinWidth(computeStableWidth(mMinuteView, 60));
155
156        // TODO: This can be removed once we support themed color state lists.
157        final int headerSelectedTextColor = a.getColor(
158                R.styleable.TimePicker_headerSelectedTextColor,
159                res.getColor(R.color.timepicker_default_selector_color_material));
160        mHourView.setTextColor(ColorStateList.addFirstIfMissing(mHourView.getTextColors(),
161                R.attr.state_selected, headerSelectedTextColor));
162        mMinuteView.setTextColor(ColorStateList.addFirstIfMissing(mMinuteView.getTextColors(),
163                R.attr.state_selected, headerSelectedTextColor));
164
165        // Set up AM/PM labels.
166        mAmPmLayout = mHeaderView.findViewById(R.id.ampm_layout);
167        mAmLabel = (CheckedTextView) mAmPmLayout.findViewById(R.id.am_label);
168        mAmLabel.setText(amPmStrings[0]);
169        mAmLabel.setOnClickListener(mClickListener);
170        mPmLabel = (CheckedTextView) mAmPmLayout.findViewById(R.id.pm_label);
171        mPmLabel.setText(amPmStrings[1]);
172        mPmLabel.setOnClickListener(mClickListener);
173
174        final int headerAmPmTextAppearance = a.getResourceId(
175                R.styleable.TimePicker_headerAmPmTextAppearance, 0);
176        if (headerAmPmTextAppearance != 0) {
177            mAmLabel.setTextAppearance(context, headerAmPmTextAppearance);
178            mPmLabel.setTextAppearance(context, headerAmPmTextAppearance);
179        }
180
181        a.recycle();
182
183        // Pull disabled alpha from theme.
184        final TypedValue outValue = new TypedValue();
185        context.getTheme().resolveAttribute(android.R.attr.disabledAlpha, outValue, true);
186        mDisabledAlpha = outValue.getFloat();
187
188        mRadialTimePickerView = (RadialTimePickerView) mainView.findViewById(
189                R.id.radial_picker);
190
191        setupListeners();
192
193        mAllowAutoAdvance = true;
194
195        // Set up for keyboard mode.
196        mDoublePlaceholderText = res.getString(R.string.time_placeholder);
197        mDeletedKeyFormat = res.getString(R.string.deleted_key);
198        mPlaceholderText = mDoublePlaceholderText.charAt(0);
199        mAmKeyCode = mPmKeyCode = -1;
200        generateLegalTimesTree();
201
202        // Initialize with current time
203        final Calendar calendar = Calendar.getInstance(mCurrentLocale);
204        final int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
205        final int currentMinute = calendar.get(Calendar.MINUTE);
206        initialize(currentHour, currentMinute, false /* 12h */, HOUR_INDEX);
207    }
208
209    private int computeStableWidth(TextView v, int maxNumber) {
210        int maxWidth = 0;
211
212        for (int i = 0; i < maxNumber; i++) {
213            final String text = String.format("%02d", i);
214            v.setText(text);
215            v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
216
217            final int width = v.getMeasuredWidth();
218            if (width > maxWidth) {
219                maxWidth = width;
220            }
221        }
222
223        return maxWidth;
224    }
225
226    private void initialize(int hourOfDay, int minute, boolean is24HourView, int index) {
227        mInitialHourOfDay = hourOfDay;
228        mInitialMinute = minute;
229        mIs24HourView = is24HourView;
230        mInKbMode = false;
231        updateUI(index);
232    }
233
234    private void setupListeners() {
235        mHeaderView.setOnKeyListener(mKeyListener);
236        mHeaderView.setOnFocusChangeListener(mFocusListener);
237        mHeaderView.setFocusable(true);
238
239        mRadialTimePickerView.setOnValueSelectedListener(this);
240    }
241
242    private void updateUI(int index) {
243        // Update RadialPicker values
244        updateRadialPicker(index);
245        // Enable or disable the AM/PM view.
246        updateHeaderAmPm();
247        // Update Hour and Minutes
248        updateHeaderHour(mInitialHourOfDay, false);
249        // Update time separator
250        updateHeaderSeparator();
251        // Update Minutes
252        updateHeaderMinute(mInitialMinute, false);
253        // Invalidate everything
254        mDelegator.invalidate();
255    }
256
257    private void updateRadialPicker(int index) {
258        mRadialTimePickerView.initialize(mInitialHourOfDay, mInitialMinute, mIs24HourView);
259        setCurrentItemShowing(index, false, true);
260    }
261
262    private void updateHeaderAmPm() {
263        if (mIs24HourView) {
264            mAmPmLayout.setVisibility(View.GONE);
265        } else {
266            // Ensure that AM/PM layout is in the correct position.
267            final String dateTimePattern = DateFormat.getBestDateTimePattern(mCurrentLocale, "hm");
268            final boolean amPmAtStart = dateTimePattern.startsWith("a");
269            final ViewGroup parent = (ViewGroup) mAmPmLayout.getParent();
270            final int targetIndex = amPmAtStart ? 0 : parent.getChildCount() - 1;
271            final int currentIndex = parent.indexOfChild(mAmPmLayout);
272            if (targetIndex != currentIndex) {
273                parent.removeView(mAmPmLayout);
274                parent.addView(mAmPmLayout, targetIndex);
275            }
276
277            updateAmPmLabelStates(mInitialHourOfDay < 12 ? AM : PM);
278        }
279    }
280
281    /**
282     * Set the current hour.
283     */
284    @Override
285    public void setCurrentHour(Integer currentHour) {
286        if (mInitialHourOfDay == currentHour) {
287            return;
288        }
289        mInitialHourOfDay = currentHour;
290        updateHeaderHour(currentHour, true);
291        updateHeaderAmPm();
292        mRadialTimePickerView.setCurrentHour(currentHour);
293        mRadialTimePickerView.setAmOrPm(mInitialHourOfDay < 12 ? AM : PM);
294        mDelegator.invalidate();
295        onTimeChanged();
296    }
297
298    /**
299     * @return The current hour in the range (0-23).
300     */
301    @Override
302    public Integer getCurrentHour() {
303        int currentHour = mRadialTimePickerView.getCurrentHour();
304        if (mIs24HourView) {
305            return currentHour;
306        } else {
307            switch(mRadialTimePickerView.getAmOrPm()) {
308                case PM:
309                    return (currentHour % HOURS_IN_HALF_DAY) + HOURS_IN_HALF_DAY;
310                case AM:
311                default:
312                    return currentHour % HOURS_IN_HALF_DAY;
313            }
314        }
315    }
316
317    /**
318     * Set the current minute (0-59).
319     */
320    @Override
321    public void setCurrentMinute(Integer currentMinute) {
322        if (mInitialMinute == currentMinute) {
323            return;
324        }
325        mInitialMinute = currentMinute;
326        updateHeaderMinute(currentMinute, true);
327        mRadialTimePickerView.setCurrentMinute(currentMinute);
328        mDelegator.invalidate();
329        onTimeChanged();
330    }
331
332    /**
333     * @return The current minute.
334     */
335    @Override
336    public Integer getCurrentMinute() {
337        return mRadialTimePickerView.getCurrentMinute();
338    }
339
340    /**
341     * Set whether in 24 hour or AM/PM mode.
342     *
343     * @param is24HourView True = 24 hour mode. False = AM/PM.
344     */
345    @Override
346    public void setIs24HourView(Boolean is24HourView) {
347        if (is24HourView == mIs24HourView) {
348            return;
349        }
350        mIs24HourView = is24HourView;
351        generateLegalTimesTree();
352        int hour = mRadialTimePickerView.getCurrentHour();
353        mInitialHourOfDay = hour;
354        updateHeaderHour(hour, false);
355        updateHeaderAmPm();
356        updateRadialPicker(mRadialTimePickerView.getCurrentItemShowing());
357        mDelegator.invalidate();
358    }
359
360    /**
361     * @return true if this is in 24 hour view else false.
362     */
363    @Override
364    public boolean is24HourView() {
365        return mIs24HourView;
366    }
367
368    @Override
369    public void setOnTimeChangedListener(TimePicker.OnTimeChangedListener callback) {
370        mOnTimeChangedListener = callback;
371    }
372
373    @Override
374    public void setEnabled(boolean enabled) {
375        mHourView.setEnabled(enabled);
376        mMinuteView.setEnabled(enabled);
377        mAmLabel.setEnabled(enabled);
378        mPmLabel.setEnabled(enabled);
379        mRadialTimePickerView.setEnabled(enabled);
380        mIsEnabled = enabled;
381    }
382
383    @Override
384    public boolean isEnabled() {
385        return mIsEnabled;
386    }
387
388    @Override
389    public int getBaseline() {
390        // does not support baseline alignment
391        return -1;
392    }
393
394    @Override
395    public void onConfigurationChanged(Configuration newConfig) {
396        updateUI(mRadialTimePickerView.getCurrentItemShowing());
397    }
398
399    @Override
400    public Parcelable onSaveInstanceState(Parcelable superState) {
401        return new SavedState(superState, getCurrentHour(), getCurrentMinute(),
402                is24HourView(), inKbMode(), getTypedTimes(), getCurrentItemShowing());
403    }
404
405    @Override
406    public void onRestoreInstanceState(Parcelable state) {
407        SavedState ss = (SavedState) state;
408        setInKbMode(ss.inKbMode());
409        setTypedTimes(ss.getTypesTimes());
410        initialize(ss.getHour(), ss.getMinute(), ss.is24HourMode(), ss.getCurrentItemShowing());
411        mRadialTimePickerView.invalidate();
412        if (mInKbMode) {
413            tryStartingKbMode(-1);
414            mHourView.invalidate();
415        }
416    }
417
418    @Override
419    public void setCurrentLocale(Locale locale) {
420        super.setCurrentLocale(locale);
421        mTempCalendar = Calendar.getInstance(locale);
422    }
423
424    @Override
425    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
426        onPopulateAccessibilityEvent(event);
427        return true;
428    }
429
430    @Override
431    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
432        int flags = DateUtils.FORMAT_SHOW_TIME;
433        if (mIs24HourView) {
434            flags |= DateUtils.FORMAT_24HOUR;
435        } else {
436            flags |= DateUtils.FORMAT_12HOUR;
437        }
438        mTempCalendar.set(Calendar.HOUR_OF_DAY, getCurrentHour());
439        mTempCalendar.set(Calendar.MINUTE, getCurrentMinute());
440        String selectedDate = DateUtils.formatDateTime(mContext,
441                mTempCalendar.getTimeInMillis(), flags);
442        event.getText().add(selectedDate);
443    }
444
445    @Override
446    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
447        event.setClassName(TimePicker.class.getName());
448    }
449
450    @Override
451    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
452        info.setClassName(TimePicker.class.getName());
453    }
454
455    /**
456     * Set whether in keyboard mode or not.
457     *
458     * @param inKbMode True means in keyboard mode.
459     */
460    private void setInKbMode(boolean inKbMode) {
461        mInKbMode = inKbMode;
462    }
463
464    /**
465     * @return true if in keyboard mode
466     */
467    private boolean inKbMode() {
468        return mInKbMode;
469    }
470
471    private void setTypedTimes(ArrayList<Integer> typeTimes) {
472        mTypedTimes = typeTimes;
473    }
474
475    /**
476     * @return an array of typed times
477     */
478    private ArrayList<Integer> getTypedTimes() {
479        return mTypedTimes;
480    }
481
482    /**
483     * @return the index of the current item showing
484     */
485    private int getCurrentItemShowing() {
486        return mRadialTimePickerView.getCurrentItemShowing();
487    }
488
489    /**
490     * Propagate the time change
491     */
492    private void onTimeChanged() {
493        mDelegator.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
494        if (mOnTimeChangedListener != null) {
495            mOnTimeChangedListener.onTimeChanged(mDelegator,
496                    getCurrentHour(), getCurrentMinute());
497        }
498    }
499
500    /**
501     * Used to save / restore state of time picker
502     */
503    private static class SavedState extends View.BaseSavedState {
504
505        private final int mHour;
506        private final int mMinute;
507        private final boolean mIs24HourMode;
508        private final boolean mInKbMode;
509        private final ArrayList<Integer> mTypedTimes;
510        private final int mCurrentItemShowing;
511
512        private SavedState(Parcelable superState, int hour, int minute, boolean is24HourMode,
513                           boolean isKbMode, ArrayList<Integer> typedTimes,
514                           int currentItemShowing) {
515            super(superState);
516            mHour = hour;
517            mMinute = minute;
518            mIs24HourMode = is24HourMode;
519            mInKbMode = isKbMode;
520            mTypedTimes = typedTimes;
521            mCurrentItemShowing = currentItemShowing;
522        }
523
524        private SavedState(Parcel in) {
525            super(in);
526            mHour = in.readInt();
527            mMinute = in.readInt();
528            mIs24HourMode = (in.readInt() == 1);
529            mInKbMode = (in.readInt() == 1);
530            mTypedTimes = in.readArrayList(getClass().getClassLoader());
531            mCurrentItemShowing = in.readInt();
532        }
533
534        public int getHour() {
535            return mHour;
536        }
537
538        public int getMinute() {
539            return mMinute;
540        }
541
542        public boolean is24HourMode() {
543            return mIs24HourMode;
544        }
545
546        public boolean inKbMode() {
547            return mInKbMode;
548        }
549
550        public ArrayList<Integer> getTypesTimes() {
551            return mTypedTimes;
552        }
553
554        public int getCurrentItemShowing() {
555            return mCurrentItemShowing;
556        }
557
558        @Override
559        public void writeToParcel(Parcel dest, int flags) {
560            super.writeToParcel(dest, flags);
561            dest.writeInt(mHour);
562            dest.writeInt(mMinute);
563            dest.writeInt(mIs24HourMode ? 1 : 0);
564            dest.writeInt(mInKbMode ? 1 : 0);
565            dest.writeList(mTypedTimes);
566            dest.writeInt(mCurrentItemShowing);
567        }
568
569        @SuppressWarnings({"unused", "hiding"})
570        public static final Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() {
571            public SavedState createFromParcel(Parcel in) {
572                return new SavedState(in);
573            }
574
575            public SavedState[] newArray(int size) {
576                return new SavedState[size];
577            }
578        };
579    }
580
581    private void tryVibrate() {
582        mDelegator.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK);
583    }
584
585    private void updateAmPmLabelStates(int amOrPm) {
586        final boolean isAm = amOrPm == AM;
587        mAmLabel.setChecked(isAm);
588        mAmLabel.setAlpha(isAm ? 1 : mDisabledAlpha);
589
590        final boolean isPm = amOrPm == PM;
591        mPmLabel.setChecked(isPm);
592        mPmLabel.setAlpha(isPm ? 1 : mDisabledAlpha);
593    }
594
595    /**
596     * Called by the picker for updating the header display.
597     */
598    @Override
599    public void onValueSelected(int pickerIndex, int newValue, boolean autoAdvance) {
600        if (pickerIndex == HOUR_INDEX) {
601            if (mAllowAutoAdvance && autoAdvance) {
602                updateHeaderHour(newValue, false);
603                setCurrentItemShowing(MINUTE_INDEX, true, false);
604                mDelegator.announceForAccessibility(newValue + ". " + mSelectMinutes);
605            } else {
606                updateHeaderHour(newValue, true);
607            }
608        } else if (pickerIndex == MINUTE_INDEX){
609            updateHeaderMinute(newValue, true);
610        } else if (pickerIndex == AMPM_INDEX) {
611            updateAmPmLabelStates(newValue);
612        } else if (pickerIndex == ENABLE_PICKER_INDEX) {
613            if (!isTypedTimeFullyLegal()) {
614                mTypedTimes.clear();
615            }
616            finishKbMode();
617        }
618    }
619
620    private void updateHeaderHour(int value, boolean announce) {
621        final String bestDateTimePattern = DateFormat.getBestDateTimePattern(mCurrentLocale,
622                (mIs24HourView) ? "Hm" : "hm");
623        final int lengthPattern = bestDateTimePattern.length();
624        boolean hourWithTwoDigit = false;
625        char hourFormat = '\0';
626        // Check if the returned pattern is single or double 'H', 'h', 'K', 'k'. We also save
627        // the hour format that we found.
628        for (int i = 0; i < lengthPattern; i++) {
629            final char c = bestDateTimePattern.charAt(i);
630            if (c == 'H' || c == 'h' || c == 'K' || c == 'k') {
631                hourFormat = c;
632                if (i + 1 < lengthPattern && c == bestDateTimePattern.charAt(i + 1)) {
633                    hourWithTwoDigit = true;
634                }
635                break;
636            }
637        }
638        final String format;
639        if (hourWithTwoDigit) {
640            format = "%02d";
641        } else {
642            format = "%d";
643        }
644        if (mIs24HourView) {
645            // 'k' means 1-24 hour
646            if (hourFormat == 'k' && value == 0) {
647                value = 24;
648            }
649        } else {
650            // 'K' means 0-11 hour
651            value = modulo12(value, hourFormat == 'K');
652        }
653        CharSequence text = String.format(format, value);
654        mHourView.setText(text);
655        if (announce) {
656            tryAnnounceForAccessibility(text, true);
657        }
658    }
659
660    private void tryAnnounceForAccessibility(CharSequence text, boolean isHour) {
661        if (mLastAnnouncedIsHour != isHour || !text.equals(mLastAnnouncedText)) {
662            // TODO: Find a better solution, potentially live regions?
663            mDelegator.announceForAccessibility(text);
664            mLastAnnouncedText = text;
665            mLastAnnouncedIsHour = isHour;
666        }
667    }
668
669    private static int modulo12(int n, boolean startWithZero) {
670        int value = n % 12;
671        if (value == 0 && !startWithZero) {
672            value = 12;
673        }
674        return value;
675    }
676
677    /**
678     * The time separator is defined in the Unicode CLDR and cannot be supposed to be ":".
679     *
680     * See http://unicode.org/cldr/trac/browser/trunk/common/main
681     *
682     * We pass the correct "skeleton" depending on 12 or 24 hours view and then extract the
683     * separator as the character which is just after the hour marker in the returned pattern.
684     */
685    private void updateHeaderSeparator() {
686        final String bestDateTimePattern = DateFormat.getBestDateTimePattern(mCurrentLocale,
687                (mIs24HourView) ? "Hm" : "hm");
688        final String separatorText;
689        // See http://www.unicode.org/reports/tr35/tr35-dates.html for hour formats
690        final char[] hourFormats = {'H', 'h', 'K', 'k'};
691        int hIndex = lastIndexOfAny(bestDateTimePattern, hourFormats);
692        if (hIndex == -1) {
693            // Default case
694            separatorText = ":";
695        } else {
696            separatorText = Character.toString(bestDateTimePattern.charAt(hIndex + 1));
697        }
698        mSeparatorView.setText(separatorText);
699    }
700
701    static private int lastIndexOfAny(String str, char[] any) {
702        final int lengthAny = any.length;
703        if (lengthAny > 0) {
704            for (int i = str.length() - 1; i >= 0; i--) {
705                char c = str.charAt(i);
706                for (int j = 0; j < lengthAny; j++) {
707                    if (c == any[j]) {
708                        return i;
709                    }
710                }
711            }
712        }
713        return -1;
714    }
715
716    private void updateHeaderMinute(int value, boolean announceForAccessibility) {
717        if (value == 60) {
718            value = 0;
719        }
720        final CharSequence text = String.format(mCurrentLocale, "%02d", value);
721        mMinuteView.setText(text);
722        if (announceForAccessibility) {
723            tryAnnounceForAccessibility(text, false);
724        }
725    }
726
727    /**
728     * Show either Hours or Minutes.
729     */
730    private void setCurrentItemShowing(int index, boolean animateCircle, boolean announce) {
731        mRadialTimePickerView.setCurrentItemShowing(index, animateCircle);
732
733        if (index == HOUR_INDEX) {
734            if (announce) {
735                mDelegator.announceForAccessibility(mSelectHours);
736            }
737        } else {
738            if (announce) {
739                mDelegator.announceForAccessibility(mSelectMinutes);
740            }
741        }
742
743        mHourView.setSelected(index == HOUR_INDEX);
744        mMinuteView.setSelected(index == MINUTE_INDEX);
745    }
746
747    private void setAmOrPm(int amOrPm) {
748        updateAmPmLabelStates(amOrPm);
749        mRadialTimePickerView.setAmOrPm(amOrPm);
750    }
751
752    /**
753     * For keyboard mode, processes key events.
754     *
755     * @param keyCode the pressed key.
756     *
757     * @return true if the key was successfully processed, false otherwise.
758     */
759    private boolean processKeyUp(int keyCode) {
760        if (keyCode == KeyEvent.KEYCODE_DEL) {
761            if (mInKbMode) {
762                if (!mTypedTimes.isEmpty()) {
763                    int deleted = deleteLastTypedKey();
764                    String deletedKeyStr;
765                    if (deleted == getAmOrPmKeyCode(AM)) {
766                        deletedKeyStr = mAmText;
767                    } else if (deleted == getAmOrPmKeyCode(PM)) {
768                        deletedKeyStr = mPmText;
769                    } else {
770                        deletedKeyStr = String.format("%d", getValFromKeyCode(deleted));
771                    }
772                    mDelegator.announceForAccessibility(
773                            String.format(mDeletedKeyFormat, deletedKeyStr));
774                    updateDisplay(true);
775                }
776            }
777        } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1
778                || keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3
779                || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
780                || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7
781                || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9
782                || (!mIs24HourView &&
783                (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
784            if (!mInKbMode) {
785                if (mRadialTimePickerView == null) {
786                    // Something's wrong, because time picker should definitely not be null.
787                    Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
788                    return true;
789                }
790                mTypedTimes.clear();
791                tryStartingKbMode(keyCode);
792                return true;
793            }
794            // We're already in keyboard mode.
795            if (addKeyIfLegal(keyCode)) {
796                updateDisplay(false);
797            }
798            return true;
799        }
800        return false;
801    }
802
803    /**
804     * Try to start keyboard mode with the specified key.
805     *
806     * @param keyCode The key to use as the first press. Keyboard mode will not be started if the
807     * key is not legal to start with. Or, pass in -1 to get into keyboard mode without a starting
808     * key.
809     */
810    private void tryStartingKbMode(int keyCode) {
811        if (keyCode == -1 || addKeyIfLegal(keyCode)) {
812            mInKbMode = true;
813            onValidationChanged(false);
814            updateDisplay(false);
815            mRadialTimePickerView.setInputEnabled(false);
816        }
817    }
818
819    private boolean addKeyIfLegal(int keyCode) {
820        // If we're in 24hour mode, we'll need to check if the input is full. If in AM/PM mode,
821        // we'll need to see if AM/PM have been typed.
822        if ((mIs24HourView && mTypedTimes.size() == 4) ||
823                (!mIs24HourView && isTypedTimeFullyLegal())) {
824            return false;
825        }
826
827        mTypedTimes.add(keyCode);
828        if (!isTypedTimeLegalSoFar()) {
829            deleteLastTypedKey();
830            return false;
831        }
832
833        int val = getValFromKeyCode(keyCode);
834        mDelegator.announceForAccessibility(String.format("%d", val));
835        // Automatically fill in 0's if AM or PM was legally entered.
836        if (isTypedTimeFullyLegal()) {
837            if (!mIs24HourView && mTypedTimes.size() <= 3) {
838                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
839                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
840            }
841            onValidationChanged(true);
842        }
843
844        return true;
845    }
846
847    /**
848     * Traverse the tree to see if the keys that have been typed so far are legal as is,
849     * or may become legal as more keys are typed (excluding backspace).
850     */
851    private boolean isTypedTimeLegalSoFar() {
852        Node node = mLegalTimesTree;
853        for (int keyCode : mTypedTimes) {
854            node = node.canReach(keyCode);
855            if (node == null) {
856                return false;
857            }
858        }
859        return true;
860    }
861
862    /**
863     * Check if the time that has been typed so far is completely legal, as is.
864     */
865    private boolean isTypedTimeFullyLegal() {
866        if (mIs24HourView) {
867            // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note:
868            // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode.
869            int[] values = getEnteredTime(null);
870            return (values[0] >= 0 && values[1] >= 0 && values[1] < 60);
871        } else {
872            // For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be
873            // legally added at specific times based on the tree's algorithm.
874            return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) ||
875                    mTypedTimes.contains(getAmOrPmKeyCode(PM)));
876        }
877    }
878
879    private int deleteLastTypedKey() {
880        int deleted = mTypedTimes.remove(mTypedTimes.size() - 1);
881        if (!isTypedTimeFullyLegal()) {
882            onValidationChanged(false);
883        }
884        return deleted;
885    }
886
887    /**
888     * Get out of keyboard mode. If there is nothing in typedTimes, revert to TimePicker's time.
889     */
890    private void finishKbMode() {
891        mInKbMode = false;
892        if (!mTypedTimes.isEmpty()) {
893            int values[] = getEnteredTime(null);
894            mRadialTimePickerView.setCurrentHour(values[0]);
895            mRadialTimePickerView.setCurrentMinute(values[1]);
896            if (!mIs24HourView) {
897                mRadialTimePickerView.setAmOrPm(values[2]);
898            }
899            mTypedTimes.clear();
900        }
901        updateDisplay(false);
902        mRadialTimePickerView.setInputEnabled(true);
903    }
904
905    /**
906     * Update the hours, minutes, and AM/PM displays with the typed times. If the typedTimes is
907     * empty, either show an empty display (filled with the placeholder text), or update from the
908     * timepicker's values.
909     *
910     * @param allowEmptyDisplay if true, then if the typedTimes is empty, use the placeholder text.
911     * Otherwise, revert to the timepicker's values.
912     */
913    private void updateDisplay(boolean allowEmptyDisplay) {
914        if (!allowEmptyDisplay && mTypedTimes.isEmpty()) {
915            int hour = mRadialTimePickerView.getCurrentHour();
916            int minute = mRadialTimePickerView.getCurrentMinute();
917            updateHeaderHour(hour, false);
918            updateHeaderMinute(minute, false);
919            if (!mIs24HourView) {
920                updateAmPmLabelStates(hour < 12 ? AM : PM);
921            }
922            setCurrentItemShowing(mRadialTimePickerView.getCurrentItemShowing(), true, true);
923            onValidationChanged(true);
924        } else {
925            boolean[] enteredZeros = {false, false};
926            int[] values = getEnteredTime(enteredZeros);
927            String hourFormat = enteredZeros[0] ? "%02d" : "%2d";
928            String minuteFormat = (enteredZeros[1]) ? "%02d" : "%2d";
929            String hourStr = (values[0] == -1) ? mDoublePlaceholderText :
930                    String.format(hourFormat, values[0]).replace(' ', mPlaceholderText);
931            String minuteStr = (values[1] == -1) ? mDoublePlaceholderText :
932                    String.format(minuteFormat, values[1]).replace(' ', mPlaceholderText);
933            mHourView.setText(hourStr);
934            mHourView.setSelected(false);
935            mMinuteView.setText(minuteStr);
936            mMinuteView.setSelected(false);
937            if (!mIs24HourView) {
938                updateAmPmLabelStates(values[2]);
939            }
940        }
941    }
942
943    private int getValFromKeyCode(int keyCode) {
944        switch (keyCode) {
945            case KeyEvent.KEYCODE_0:
946                return 0;
947            case KeyEvent.KEYCODE_1:
948                return 1;
949            case KeyEvent.KEYCODE_2:
950                return 2;
951            case KeyEvent.KEYCODE_3:
952                return 3;
953            case KeyEvent.KEYCODE_4:
954                return 4;
955            case KeyEvent.KEYCODE_5:
956                return 5;
957            case KeyEvent.KEYCODE_6:
958                return 6;
959            case KeyEvent.KEYCODE_7:
960                return 7;
961            case KeyEvent.KEYCODE_8:
962                return 8;
963            case KeyEvent.KEYCODE_9:
964                return 9;
965            default:
966                return -1;
967        }
968    }
969
970    /**
971     * Get the currently-entered time, as integer values of the hours and minutes typed.
972     *
973     * @param enteredZeros A size-2 boolean array, which the caller should initialize, and which
974     * may then be used for the caller to know whether zeros had been explicitly entered as either
975     * hours of minutes. This is helpful for deciding whether to show the dashes, or actual 0's.
976     *
977     * @return A size-3 int array. The first value will be the hours, the second value will be the
978     * minutes, and the third will be either AM or PM.
979     */
980    private int[] getEnteredTime(boolean[] enteredZeros) {
981        int amOrPm = -1;
982        int startIndex = 1;
983        if (!mIs24HourView && isTypedTimeFullyLegal()) {
984            int keyCode = mTypedTimes.get(mTypedTimes.size() - 1);
985            if (keyCode == getAmOrPmKeyCode(AM)) {
986                amOrPm = AM;
987            } else if (keyCode == getAmOrPmKeyCode(PM)){
988                amOrPm = PM;
989            }
990            startIndex = 2;
991        }
992        int minute = -1;
993        int hour = -1;
994        for (int i = startIndex; i <= mTypedTimes.size(); i++) {
995            int val = getValFromKeyCode(mTypedTimes.get(mTypedTimes.size() - i));
996            if (i == startIndex) {
997                minute = val;
998            } else if (i == startIndex+1) {
999                minute += 10 * val;
1000                if (enteredZeros != null && val == 0) {
1001                    enteredZeros[1] = true;
1002                }
1003            } else if (i == startIndex+2) {
1004                hour = val;
1005            } else if (i == startIndex+3) {
1006                hour += 10 * val;
1007                if (enteredZeros != null && val == 0) {
1008                    enteredZeros[0] = true;
1009                }
1010            }
1011        }
1012
1013        return new int[] { hour, minute, amOrPm };
1014    }
1015
1016    /**
1017     * Get the keycode value for AM and PM in the current language.
1018     */
1019    private int getAmOrPmKeyCode(int amOrPm) {
1020        // Cache the codes.
1021        if (mAmKeyCode == -1 || mPmKeyCode == -1) {
1022            // Find the first character in the AM/PM text that is unique.
1023            KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
1024            char amChar;
1025            char pmChar;
1026            for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) {
1027                amChar = mAmText.toLowerCase(mCurrentLocale).charAt(i);
1028                pmChar = mPmText.toLowerCase(mCurrentLocale).charAt(i);
1029                if (amChar != pmChar) {
1030                    KeyEvent[] events = kcm.getEvents(new char[]{amChar, pmChar});
1031                    // There should be 4 events: a down and up for both AM and PM.
1032                    if (events != null && events.length == 4) {
1033                        mAmKeyCode = events[0].getKeyCode();
1034                        mPmKeyCode = events[2].getKeyCode();
1035                    } else {
1036                        Log.e(TAG, "Unable to find keycodes for AM and PM.");
1037                    }
1038                    break;
1039                }
1040            }
1041        }
1042        if (amOrPm == AM) {
1043            return mAmKeyCode;
1044        } else if (amOrPm == PM) {
1045            return mPmKeyCode;
1046        }
1047
1048        return -1;
1049    }
1050
1051    /**
1052     * Create a tree for deciding what keys can legally be typed.
1053     */
1054    private void generateLegalTimesTree() {
1055        // Create a quick cache of numbers to their keycodes.
1056        final int k0 = KeyEvent.KEYCODE_0;
1057        final int k1 = KeyEvent.KEYCODE_1;
1058        final int k2 = KeyEvent.KEYCODE_2;
1059        final int k3 = KeyEvent.KEYCODE_3;
1060        final int k4 = KeyEvent.KEYCODE_4;
1061        final int k5 = KeyEvent.KEYCODE_5;
1062        final int k6 = KeyEvent.KEYCODE_6;
1063        final int k7 = KeyEvent.KEYCODE_7;
1064        final int k8 = KeyEvent.KEYCODE_8;
1065        final int k9 = KeyEvent.KEYCODE_9;
1066
1067        // The root of the tree doesn't contain any numbers.
1068        mLegalTimesTree = new Node();
1069        if (mIs24HourView) {
1070            // We'll be re-using these nodes, so we'll save them.
1071            Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
1072            Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
1073            // The first digit must be followed by the second digit.
1074            minuteFirstDigit.addChild(minuteSecondDigit);
1075
1076            // The first digit may be 0-1.
1077            Node firstDigit = new Node(k0, k1);
1078            mLegalTimesTree.addChild(firstDigit);
1079
1080            // When the first digit is 0-1, the second digit may be 0-5.
1081            Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
1082            firstDigit.addChild(secondDigit);
1083            // We may now be followed by the first minute digit. E.g. 00:09, 15:58.
1084            secondDigit.addChild(minuteFirstDigit);
1085
1086            // When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9.
1087            Node thirdDigit = new Node(k6, k7, k8, k9);
1088            // The time must now be finished. E.g. 0:55, 1:08.
1089            secondDigit.addChild(thirdDigit);
1090
1091            // When the first digit is 0-1, the second digit may be 6-9.
1092            secondDigit = new Node(k6, k7, k8, k9);
1093            firstDigit.addChild(secondDigit);
1094            // We must now be followed by the first minute digit. E.g. 06:50, 18:20.
1095            secondDigit.addChild(minuteFirstDigit);
1096
1097            // The first digit may be 2.
1098            firstDigit = new Node(k2);
1099            mLegalTimesTree.addChild(firstDigit);
1100
1101            // When the first digit is 2, the second digit may be 0-3.
1102            secondDigit = new Node(k0, k1, k2, k3);
1103            firstDigit.addChild(secondDigit);
1104            // We must now be followed by the first minute digit. E.g. 20:50, 23:09.
1105            secondDigit.addChild(minuteFirstDigit);
1106
1107            // When the first digit is 2, the second digit may be 4-5.
1108            secondDigit = new Node(k4, k5);
1109            firstDigit.addChild(secondDigit);
1110            // We must now be followd by the last minute digit. E.g. 2:40, 2:53.
1111            secondDigit.addChild(minuteSecondDigit);
1112
1113            // The first digit may be 3-9.
1114            firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
1115            mLegalTimesTree.addChild(firstDigit);
1116            // We must now be followed by the first minute digit. E.g. 3:57, 8:12.
1117            firstDigit.addChild(minuteFirstDigit);
1118        } else {
1119            // We'll need to use the AM/PM node a lot.
1120            // Set up AM and PM to respond to "a" and "p".
1121            Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
1122
1123            // The first hour digit may be 1.
1124            Node firstDigit = new Node(k1);
1125            mLegalTimesTree.addChild(firstDigit);
1126            // We'll allow quick input of on-the-hour times. E.g. 1pm.
1127            firstDigit.addChild(ampm);
1128
1129            // When the first digit is 1, the second digit may be 0-2.
1130            Node secondDigit = new Node(k0, k1, k2);
1131            firstDigit.addChild(secondDigit);
1132            // Also for quick input of on-the-hour times. E.g. 10pm, 12am.
1133            secondDigit.addChild(ampm);
1134
1135            // When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5.
1136            Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
1137            secondDigit.addChild(thirdDigit);
1138            // The time may be finished now. E.g. 1:02pm, 1:25am.
1139            thirdDigit.addChild(ampm);
1140
1141            // When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
1142            // the fourth digit may be 0-9.
1143            Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
1144            thirdDigit.addChild(fourthDigit);
1145            // The time must be finished now. E.g. 10:49am, 12:40pm.
1146            fourthDigit.addChild(ampm);
1147
1148            // When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9.
1149            thirdDigit = new Node(k6, k7, k8, k9);
1150            secondDigit.addChild(thirdDigit);
1151            // The time must be finished now. E.g. 1:08am, 1:26pm.
1152            thirdDigit.addChild(ampm);
1153
1154            // When the first digit is 1, the second digit may be 3-5.
1155            secondDigit = new Node(k3, k4, k5);
1156            firstDigit.addChild(secondDigit);
1157
1158            // When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9.
1159            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
1160            secondDigit.addChild(thirdDigit);
1161            // The time must be finished now. E.g. 1:39am, 1:50pm.
1162            thirdDigit.addChild(ampm);
1163
1164            // The hour digit may be 2-9.
1165            firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
1166            mLegalTimesTree.addChild(firstDigit);
1167            // We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm.
1168            firstDigit.addChild(ampm);
1169
1170            // When the first digit is 2-9, the second digit may be 0-5.
1171            secondDigit = new Node(k0, k1, k2, k3, k4, k5);
1172            firstDigit.addChild(secondDigit);
1173
1174            // When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9.
1175            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
1176            secondDigit.addChild(thirdDigit);
1177            // The time must be finished now. E.g. 2:57am, 9:30pm.
1178            thirdDigit.addChild(ampm);
1179        }
1180    }
1181
1182    /**
1183     * Simple node class to be used for traversal to check for legal times.
1184     * mLegalKeys represents the keys that can be typed to get to the node.
1185     * mChildren are the children that can be reached from this node.
1186     */
1187    private class Node {
1188        private int[] mLegalKeys;
1189        private ArrayList<Node> mChildren;
1190
1191        public Node(int... legalKeys) {
1192            mLegalKeys = legalKeys;
1193            mChildren = new ArrayList<Node>();
1194        }
1195
1196        public void addChild(Node child) {
1197            mChildren.add(child);
1198        }
1199
1200        public boolean containsKey(int key) {
1201            for (int i = 0; i < mLegalKeys.length; i++) {
1202                if (mLegalKeys[i] == key) {
1203                    return true;
1204                }
1205            }
1206            return false;
1207        }
1208
1209        public Node canReach(int key) {
1210            if (mChildren == null) {
1211                return null;
1212            }
1213            for (Node child : mChildren) {
1214                if (child.containsKey(key)) {
1215                    return child;
1216                }
1217            }
1218            return null;
1219        }
1220    }
1221
1222    private final View.OnClickListener mClickListener = new View.OnClickListener() {
1223        @Override
1224        public void onClick(View v) {
1225
1226            final int amOrPm;
1227            switch (v.getId()) {
1228                case R.id.am_label:
1229                    setAmOrPm(AM);
1230                    break;
1231                case R.id.pm_label:
1232                    setAmOrPm(PM);
1233                    break;
1234                case R.id.hours:
1235                    setCurrentItemShowing(HOUR_INDEX, true, true);
1236                    break;
1237                case R.id.minutes:
1238                    setCurrentItemShowing(MINUTE_INDEX, true, true);
1239                    break;
1240                default:
1241                    // Failed to handle this click, don't vibrate.
1242                    return;
1243            }
1244
1245            tryVibrate();
1246        }
1247    };
1248
1249    private final View.OnKeyListener mKeyListener = new View.OnKeyListener() {
1250        @Override
1251        public boolean onKey(View v, int keyCode, KeyEvent event) {
1252            if (event.getAction() == KeyEvent.ACTION_UP) {
1253                return processKeyUp(keyCode);
1254            }
1255            return false;
1256        }
1257    };
1258
1259    private final View.OnFocusChangeListener mFocusListener = new View.OnFocusChangeListener() {
1260        @Override
1261        public void onFocusChange(View v, boolean hasFocus) {
1262            if (!hasFocus && mInKbMode && isTypedTimeFullyLegal()) {
1263                finishKbMode();
1264
1265                if (mOnTimeChangedListener != null) {
1266                    mOnTimeChangedListener.onTimeChanged(mDelegator,
1267                            mRadialTimePickerView.getCurrentHour(),
1268                            mRadialTimePickerView.getCurrentMinute());
1269                }
1270            }
1271        }
1272    };
1273}
1274