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.datetimepicker.time;
18
19import android.animation.ObjectAnimator;
20import android.app.ActionBar.LayoutParams;
21import android.app.DialogFragment;
22import android.content.Context;
23import android.content.res.ColorStateList;
24import android.content.res.Resources;
25import android.os.Bundle;
26import android.util.Log;
27import android.view.KeyCharacterMap;
28import android.view.KeyEvent;
29import android.view.LayoutInflater;
30import android.view.View;
31import android.view.View.OnClickListener;
32import android.view.View.OnKeyListener;
33import android.view.ViewGroup;
34import android.view.Window;
35import android.widget.RelativeLayout;
36import android.widget.TextView;
37
38import com.android.datetimepicker.HapticFeedbackController;
39import com.android.datetimepicker.R;
40import com.android.datetimepicker.Utils;
41import com.android.datetimepicker.time.RadialPickerLayout.OnValueSelectedListener;
42
43import java.text.DateFormatSymbols;
44import java.util.ArrayList;
45import java.util.Locale;
46
47/**
48 * Dialog to set a time.
49 */
50public class TimePickerDialog extends DialogFragment implements OnValueSelectedListener{
51    private static final String TAG = "TimePickerDialog";
52
53    private static final String KEY_HOUR_OF_DAY = "hour_of_day";
54    private static final String KEY_MINUTE = "minute";
55    private static final String KEY_IS_24_HOUR_VIEW = "is_24_hour_view";
56    private static final String KEY_CURRENT_ITEM_SHOWING = "current_item_showing";
57    private static final String KEY_IN_KB_MODE = "in_kb_mode";
58    private static final String KEY_TYPED_TIMES = "typed_times";
59    private static final String KEY_DARK_THEME = "dark_theme";
60
61    public static final int HOUR_INDEX = 0;
62    public static final int MINUTE_INDEX = 1;
63    // NOT a real index for the purpose of what's showing.
64    public static final int AMPM_INDEX = 2;
65    // Also NOT a real index, just used for keyboard mode.
66    public static final int ENABLE_PICKER_INDEX = 3;
67    public static final int AM = 0;
68    public static final int PM = 1;
69
70    // Delay before starting the pulse animation, in ms.
71    private static final int PULSE_ANIMATOR_DELAY = 300;
72
73    private OnTimeSetListener mCallback;
74
75    private HapticFeedbackController mHapticFeedbackController;
76
77    private TextView mDoneButton;
78    private TextView mHourView;
79    private TextView mHourSpaceView;
80    private TextView mMinuteView;
81    private TextView mMinuteSpaceView;
82    private TextView mAmPmTextView;
83    private View mAmPmHitspace;
84    private RadialPickerLayout mTimePicker;
85
86    private int mSelectedColor;
87    private int mUnselectedColor;
88    private String mAmText;
89    private String mPmText;
90
91    private boolean mAllowAutoAdvance;
92    private int mInitialHourOfDay;
93    private int mInitialMinute;
94    private boolean mIs24HourMode;
95    private boolean mThemeDark;
96
97    // For hardware IME input.
98    private char mPlaceholderText;
99    private String mDoublePlaceholderText;
100    private String mDeletedKeyFormat;
101    private boolean mInKbMode;
102    private ArrayList<Integer> mTypedTimes;
103    private Node mLegalTimesTree;
104    private int mAmKeyCode;
105    private int mPmKeyCode;
106
107    // Accessibility strings.
108    private String mHourPickerDescription;
109    private String mSelectHours;
110    private String mMinutePickerDescription;
111    private String mSelectMinutes;
112
113    /**
114     * The callback interface used to indicate the user is done filling in
115     * the time (they clicked on the 'Set' button).
116     */
117    public interface OnTimeSetListener {
118
119        /**
120         * @param view The view associated with this listener.
121         * @param hourOfDay The hour that was set.
122         * @param minute The minute that was set.
123         */
124        void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute);
125    }
126
127    public TimePickerDialog() {
128        // Empty constructor required for dialog fragment.
129    }
130
131    public TimePickerDialog(Context context, int theme, OnTimeSetListener callback,
132            int hourOfDay, int minute, boolean is24HourMode) {
133        // Empty constructor required for dialog fragment.
134    }
135
136    public static TimePickerDialog newInstance(OnTimeSetListener callback,
137            int hourOfDay, int minute, boolean is24HourMode) {
138        TimePickerDialog ret = new TimePickerDialog();
139        ret.initialize(callback, hourOfDay, minute, is24HourMode);
140        return ret;
141    }
142
143    public void initialize(OnTimeSetListener callback,
144            int hourOfDay, int minute, boolean is24HourMode) {
145        mCallback = callback;
146
147        mInitialHourOfDay = hourOfDay;
148        mInitialMinute = minute;
149        mIs24HourMode = is24HourMode;
150        mInKbMode = false;
151        mThemeDark = false;
152    }
153
154    /**
155     * Set a dark or light theme. NOTE: this will only take effect for the next onCreateView.
156     */
157    public void setThemeDark(boolean dark) {
158        mThemeDark = dark;
159    }
160
161    public boolean isThemeDark() {
162        return mThemeDark;
163    }
164
165    public void setOnTimeSetListener(OnTimeSetListener callback) {
166        mCallback = callback;
167    }
168
169    public void setStartTime(int hourOfDay, int minute) {
170        mInitialHourOfDay = hourOfDay;
171        mInitialMinute = minute;
172        mInKbMode = false;
173    }
174
175    @Override
176    public void onCreate(Bundle savedInstanceState) {
177        super.onCreate(savedInstanceState);
178        if (savedInstanceState != null && savedInstanceState.containsKey(KEY_HOUR_OF_DAY)
179                    && savedInstanceState.containsKey(KEY_MINUTE)
180                    && savedInstanceState.containsKey(KEY_IS_24_HOUR_VIEW)) {
181            mInitialHourOfDay = savedInstanceState.getInt(KEY_HOUR_OF_DAY);
182            mInitialMinute = savedInstanceState.getInt(KEY_MINUTE);
183            mIs24HourMode = savedInstanceState.getBoolean(KEY_IS_24_HOUR_VIEW);
184            mInKbMode = savedInstanceState.getBoolean(KEY_IN_KB_MODE);
185            mThemeDark = savedInstanceState.getBoolean(KEY_DARK_THEME);
186        }
187    }
188
189    @Override
190    public View onCreateView(LayoutInflater inflater, ViewGroup container,
191            Bundle savedInstanceState) {
192        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
193
194        View view = inflater.inflate(R.layout.time_picker_dialog, null);
195        KeyboardListener keyboardListener = new KeyboardListener();
196        view.findViewById(R.id.time_picker_dialog).setOnKeyListener(keyboardListener);
197
198        Resources res = getResources();
199        mHourPickerDescription = res.getString(R.string.hour_picker_description);
200        mSelectHours = res.getString(R.string.select_hours);
201        mMinutePickerDescription = res.getString(R.string.minute_picker_description);
202        mSelectMinutes = res.getString(R.string.select_minutes);
203        mSelectedColor = res.getColor(mThemeDark? R.color.red : R.color.blue);
204        mUnselectedColor = res.getColor(mThemeDark? R.color.white : R.color.numbers_text_color);
205
206        mHourView = (TextView) view.findViewById(R.id.hours);
207        mHourView.setOnKeyListener(keyboardListener);
208        mHourSpaceView = (TextView) view.findViewById(R.id.hour_space);
209        mMinuteSpaceView = (TextView) view.findViewById(R.id.minutes_space);
210        mMinuteView = (TextView) view.findViewById(R.id.minutes);
211        mMinuteView.setOnKeyListener(keyboardListener);
212        mAmPmTextView = (TextView) view.findViewById(R.id.ampm_label);
213        mAmPmTextView.setOnKeyListener(keyboardListener);
214        String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
215        mAmText = amPmTexts[0];
216        mPmText = amPmTexts[1];
217
218        mHapticFeedbackController = new HapticFeedbackController(getActivity());
219
220        mTimePicker = (RadialPickerLayout) view.findViewById(R.id.time_picker);
221        mTimePicker.setOnValueSelectedListener(this);
222        mTimePicker.setOnKeyListener(keyboardListener);
223        mTimePicker.initialize(getActivity(), mHapticFeedbackController, mInitialHourOfDay,
224            mInitialMinute, mIs24HourMode);
225
226        int currentItemShowing = HOUR_INDEX;
227        if (savedInstanceState != null &&
228                savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING)) {
229            currentItemShowing = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING);
230        }
231        setCurrentItemShowing(currentItemShowing, false, true, true);
232        mTimePicker.invalidate();
233
234        mHourView.setOnClickListener(new OnClickListener() {
235            @Override
236            public void onClick(View v) {
237                setCurrentItemShowing(HOUR_INDEX, true, false, true);
238                tryVibrate();
239            }
240        });
241        mMinuteView.setOnClickListener(new OnClickListener() {
242            @Override
243            public void onClick(View v) {
244                setCurrentItemShowing(MINUTE_INDEX, true, false, true);
245                tryVibrate();
246            }
247        });
248
249        mDoneButton = (TextView) view.findViewById(R.id.done_button);
250        mDoneButton.setOnClickListener(new OnClickListener() {
251            @Override
252            public void onClick(View v) {
253                if (mInKbMode && isTypedTimeFullyLegal()) {
254                    finishKbMode(false);
255                } else {
256                    tryVibrate();
257                }
258                if (mCallback != null) {
259                    mCallback.onTimeSet(mTimePicker,
260                            mTimePicker.getHours(), mTimePicker.getMinutes());
261                }
262                dismiss();
263            }
264        });
265        mDoneButton.setOnKeyListener(keyboardListener);
266
267        // Enable or disable the AM/PM view.
268        mAmPmHitspace = view.findViewById(R.id.ampm_hitspace);
269        if (mIs24HourMode) {
270            mAmPmTextView.setVisibility(View.GONE);
271
272            RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(
273                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
274            paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT);
275            TextView separatorView = (TextView) view.findViewById(R.id.separator);
276            separatorView.setLayoutParams(paramsSeparator);
277        } else {
278            mAmPmTextView.setVisibility(View.VISIBLE);
279            updateAmPmDisplay(mInitialHourOfDay < 12? AM : PM);
280            mAmPmHitspace.setOnClickListener(new OnClickListener() {
281                @Override
282                public void onClick(View v) {
283                    tryVibrate();
284                    int amOrPm = mTimePicker.getIsCurrentlyAmOrPm();
285                    if (amOrPm == AM) {
286                        amOrPm = PM;
287                    } else if (amOrPm == PM){
288                        amOrPm = AM;
289                    }
290                    updateAmPmDisplay(amOrPm);
291                    mTimePicker.setAmOrPm(amOrPm);
292                }
293            });
294        }
295
296        mAllowAutoAdvance = true;
297        setHour(mInitialHourOfDay, true);
298        setMinute(mInitialMinute);
299
300        // Set up for keyboard mode.
301        mDoublePlaceholderText = res.getString(R.string.time_placeholder);
302        mDeletedKeyFormat = res.getString(R.string.deleted_key);
303        mPlaceholderText = mDoublePlaceholderText.charAt(0);
304        mAmKeyCode = mPmKeyCode = -1;
305        generateLegalTimesTree();
306        if (mInKbMode) {
307            mTypedTimes = savedInstanceState.getIntegerArrayList(KEY_TYPED_TIMES);
308            tryStartingKbMode(-1);
309            mHourView.invalidate();
310        } else if (mTypedTimes == null) {
311            mTypedTimes = new ArrayList<Integer>();
312        }
313
314        // Set the theme at the end so that the initialize()s above don't counteract the theme.
315        mTimePicker.setTheme(getActivity().getApplicationContext(), mThemeDark);
316        // Prepare some colors to use.
317        int white = res.getColor(R.color.white);
318        int circleBackground = res.getColor(R.color.circle_background);
319        int line = res.getColor(R.color.line_background);
320        int timeDisplay = res.getColor(R.color.numbers_text_color);
321        ColorStateList doneTextColor = res.getColorStateList(R.color.done_text_color);
322        int doneBackground = R.drawable.done_background_color;
323
324        int darkGray = res.getColor(R.color.dark_gray);
325        int lightGray = res.getColor(R.color.light_gray);
326        int darkLine = res.getColor(R.color.line_dark);
327        ColorStateList darkDoneTextColor = res.getColorStateList(R.color.done_text_color_dark);
328        int darkDoneBackground = R.drawable.done_background_color_dark;
329
330        // Set the colors for each view based on the theme.
331        view.findViewById(R.id.time_display_background).setBackgroundColor(mThemeDark? darkGray : white);
332        view.findViewById(R.id.time_display).setBackgroundColor(mThemeDark? darkGray : white);
333        ((TextView) view.findViewById(R.id.separator)).setTextColor(mThemeDark? white : timeDisplay);
334        ((TextView) view.findViewById(R.id.ampm_label)).setTextColor(mThemeDark? white : timeDisplay);
335        view.findViewById(R.id.line).setBackgroundColor(mThemeDark? darkLine : line);
336        mDoneButton.setTextColor(mThemeDark? darkDoneTextColor : doneTextColor);
337        mTimePicker.setBackgroundColor(mThemeDark? lightGray : circleBackground);
338        mDoneButton.setBackgroundResource(mThemeDark? darkDoneBackground : doneBackground);
339        return view;
340    }
341
342    @Override
343    public void onResume() {
344        super.onResume();
345        mHapticFeedbackController.start();
346    }
347
348    @Override
349    public void onPause() {
350        super.onPause();
351        mHapticFeedbackController.stop();
352    }
353
354    public void tryVibrate() {
355        mHapticFeedbackController.tryVibrate();
356    }
357
358    private void updateAmPmDisplay(int amOrPm) {
359        if (amOrPm == AM) {
360            mAmPmTextView.setText(mAmText);
361            Utils.tryAccessibilityAnnounce(mTimePicker, mAmText);
362            mAmPmHitspace.setContentDescription(mAmText);
363        } else if (amOrPm == PM){
364            mAmPmTextView.setText(mPmText);
365            Utils.tryAccessibilityAnnounce(mTimePicker, mPmText);
366            mAmPmHitspace.setContentDescription(mPmText);
367        } else {
368            mAmPmTextView.setText(mDoublePlaceholderText);
369        }
370    }
371
372    @Override
373    public void onSaveInstanceState(Bundle outState) {
374        if (mTimePicker != null) {
375            outState.putInt(KEY_HOUR_OF_DAY, mTimePicker.getHours());
376            outState.putInt(KEY_MINUTE, mTimePicker.getMinutes());
377            outState.putBoolean(KEY_IS_24_HOUR_VIEW, mIs24HourMode);
378            outState.putInt(KEY_CURRENT_ITEM_SHOWING, mTimePicker.getCurrentItemShowing());
379            outState.putBoolean(KEY_IN_KB_MODE, mInKbMode);
380            if (mInKbMode) {
381                outState.putIntegerArrayList(KEY_TYPED_TIMES, mTypedTimes);
382            }
383            outState.putBoolean(KEY_DARK_THEME, mThemeDark);
384        }
385    }
386
387    /**
388     * Called by the picker for updating the header display.
389     */
390    @Override
391    public void onValueSelected(int pickerIndex, int newValue, boolean autoAdvance) {
392        if (pickerIndex == HOUR_INDEX) {
393            setHour(newValue, false);
394            String announcement = String.format("%d", newValue);
395            if (mAllowAutoAdvance && autoAdvance) {
396                setCurrentItemShowing(MINUTE_INDEX, true, true, false);
397                announcement += ". " + mSelectMinutes;
398            } else {
399                mTimePicker.setContentDescription(mHourPickerDescription + ": " + newValue);
400            }
401
402            Utils.tryAccessibilityAnnounce(mTimePicker, announcement);
403        } else if (pickerIndex == MINUTE_INDEX){
404            setMinute(newValue);
405            mTimePicker.setContentDescription(mMinutePickerDescription + ": " + newValue);
406        } else if (pickerIndex == AMPM_INDEX) {
407            updateAmPmDisplay(newValue);
408        } else if (pickerIndex == ENABLE_PICKER_INDEX) {
409            if (!isTypedTimeFullyLegal()) {
410                mTypedTimes.clear();
411            }
412            finishKbMode(true);
413        }
414    }
415
416    private void setHour(int value, boolean announce) {
417        String format;
418        if (mIs24HourMode) {
419            format = "%02d";
420        } else {
421            format = "%d";
422            value = value % 12;
423            if (value == 0) {
424                value = 12;
425            }
426        }
427
428        CharSequence text = String.format(format, value);
429        mHourView.setText(text);
430        mHourSpaceView.setText(text);
431        if (announce) {
432            Utils.tryAccessibilityAnnounce(mTimePicker, text);
433        }
434    }
435
436    private void setMinute(int value) {
437        if (value == 60) {
438            value = 0;
439        }
440        CharSequence text = String.format(Locale.getDefault(), "%02d", value);
441        Utils.tryAccessibilityAnnounce(mTimePicker, text);
442        mMinuteView.setText(text);
443        mMinuteSpaceView.setText(text);
444    }
445
446    // Show either Hours or Minutes.
447    private void setCurrentItemShowing(int index, boolean animateCircle, boolean delayLabelAnimate,
448            boolean announce) {
449        mTimePicker.setCurrentItemShowing(index, animateCircle);
450
451        TextView labelToAnimate;
452        if (index == HOUR_INDEX) {
453            int hours = mTimePicker.getHours();
454            if (!mIs24HourMode) {
455                hours = hours % 12;
456            }
457            mTimePicker.setContentDescription(mHourPickerDescription + ": " + hours);
458            if (announce) {
459                Utils.tryAccessibilityAnnounce(mTimePicker, mSelectHours);
460            }
461            labelToAnimate = mHourView;
462        } else {
463            int minutes = mTimePicker.getMinutes();
464            mTimePicker.setContentDescription(mMinutePickerDescription + ": " + minutes);
465            if (announce) {
466                Utils.tryAccessibilityAnnounce(mTimePicker, mSelectMinutes);
467            }
468            labelToAnimate = mMinuteView;
469        }
470
471        int hourColor = (index == HOUR_INDEX)? mSelectedColor : mUnselectedColor;
472        int minuteColor = (index == MINUTE_INDEX)? mSelectedColor : mUnselectedColor;
473        mHourView.setTextColor(hourColor);
474        mMinuteView.setTextColor(minuteColor);
475
476        ObjectAnimator pulseAnimator = Utils.getPulseAnimator(labelToAnimate, 0.85f, 1.1f);
477        if (delayLabelAnimate) {
478            pulseAnimator.setStartDelay(PULSE_ANIMATOR_DELAY);
479        }
480        pulseAnimator.start();
481    }
482
483    /**
484     * For keyboard mode, processes key events.
485     * @param keyCode the pressed key.
486     * @return true if the key was successfully processed, false otherwise.
487     */
488    private boolean processKeyUp(int keyCode) {
489        if (keyCode == KeyEvent.KEYCODE_ESCAPE || keyCode == KeyEvent.KEYCODE_BACK) {
490            dismiss();
491            return true;
492        } else if (keyCode == KeyEvent.KEYCODE_TAB) {
493            if(mInKbMode) {
494                if (isTypedTimeFullyLegal()) {
495                    finishKbMode(true);
496                }
497                return true;
498            }
499        } else if (keyCode == KeyEvent.KEYCODE_ENTER) {
500            if (mInKbMode) {
501                if (!isTypedTimeFullyLegal()) {
502                    return true;
503                }
504                finishKbMode(false);
505            }
506            if (mCallback != null) {
507                mCallback.onTimeSet(mTimePicker,
508                        mTimePicker.getHours(), mTimePicker.getMinutes());
509            }
510            dismiss();
511            return true;
512        } else if (keyCode == KeyEvent.KEYCODE_DEL) {
513            if (mInKbMode) {
514                if (!mTypedTimes.isEmpty()) {
515                    int deleted = deleteLastTypedKey();
516                    String deletedKeyStr;
517                    if (deleted == getAmOrPmKeyCode(AM)) {
518                        deletedKeyStr = mAmText;
519                    } else if (deleted == getAmOrPmKeyCode(PM)) {
520                        deletedKeyStr = mPmText;
521                    } else {
522                        deletedKeyStr = String.format("%d", getValFromKeyCode(deleted));
523                    }
524                    Utils.tryAccessibilityAnnounce(mTimePicker,
525                            String.format(mDeletedKeyFormat, deletedKeyStr));
526                    updateDisplay(true);
527                }
528            }
529        } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1
530                || keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3
531                || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
532                || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7
533                || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9
534                || (!mIs24HourMode &&
535                        (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
536            if (!mInKbMode) {
537                if (mTimePicker == null) {
538                    // Something's wrong, because time picker should definitely not be null.
539                    Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
540                    return true;
541                }
542                mTypedTimes.clear();
543                tryStartingKbMode(keyCode);
544                return true;
545            }
546            // We're already in keyboard mode.
547            if (addKeyIfLegal(keyCode)) {
548                updateDisplay(false);
549            }
550            return true;
551        }
552        return false;
553    }
554
555    /**
556     * Try to start keyboard mode with the specified key, as long as the timepicker is not in the
557     * middle of a touch-event.
558     * @param keyCode The key to use as the first press. Keyboard mode will not be started if the
559     * key is not legal to start with. Or, pass in -1 to get into keyboard mode without a starting
560     * key.
561     */
562    private void tryStartingKbMode(int keyCode) {
563        if (mTimePicker.trySettingInputEnabled(false) &&
564                (keyCode == -1 || addKeyIfLegal(keyCode))) {
565            mInKbMode = true;
566            mDoneButton.setEnabled(false);
567            updateDisplay(false);
568        }
569    }
570
571    private boolean addKeyIfLegal(int keyCode) {
572        // If we're in 24hour mode, we'll need to check if the input is full. If in AM/PM mode,
573        // we'll need to see if AM/PM have been typed.
574        if ((mIs24HourMode && mTypedTimes.size() == 4) ||
575                (!mIs24HourMode && isTypedTimeFullyLegal())) {
576            return false;
577        }
578
579        mTypedTimes.add(keyCode);
580        if (!isTypedTimeLegalSoFar()) {
581            deleteLastTypedKey();
582            return false;
583        }
584
585        int val = getValFromKeyCode(keyCode);
586        Utils.tryAccessibilityAnnounce(mTimePicker, String.format("%d", val));
587        // Automatically fill in 0's if AM or PM was legally entered.
588        if (isTypedTimeFullyLegal()) {
589            if (!mIs24HourMode && mTypedTimes.size() <= 3) {
590                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
591                mTypedTimes.add(mTypedTimes.size() - 1, KeyEvent.KEYCODE_0);
592            }
593            mDoneButton.setEnabled(true);
594        }
595
596        return true;
597    }
598
599    /**
600     * Traverse the tree to see if the keys that have been typed so far are legal as is,
601     * or may become legal as more keys are typed (excluding backspace).
602     */
603    private boolean isTypedTimeLegalSoFar() {
604        Node node = mLegalTimesTree;
605        for (int keyCode : mTypedTimes) {
606            node = node.canReach(keyCode);
607            if (node == null) {
608                return false;
609            }
610        }
611        return true;
612    }
613
614    /**
615     * Check if the time that has been typed so far is completely legal, as is.
616     */
617    private boolean isTypedTimeFullyLegal() {
618        if (mIs24HourMode) {
619            // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note:
620            // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode.
621            int[] values = getEnteredTime(null);
622            return (values[0] >= 0 && values[1] >= 0 && values[1] < 60);
623        } else {
624            // For AM/PM mode, the time is legal if it contains an AM or PM, as those can only be
625            // legally added at specific times based on the tree's algorithm.
626            return (mTypedTimes.contains(getAmOrPmKeyCode(AM)) ||
627                    mTypedTimes.contains(getAmOrPmKeyCode(PM)));
628        }
629    }
630
631    private int deleteLastTypedKey() {
632        int deleted = mTypedTimes.remove(mTypedTimes.size() - 1);
633        if (!isTypedTimeFullyLegal()) {
634            mDoneButton.setEnabled(false);
635        }
636        return deleted;
637    }
638
639    /**
640     * Get out of keyboard mode. If there is nothing in typedTimes, revert to TimePicker's time.
641     * @param changeDisplays If true, update the displays with the relevant time.
642     */
643    private void finishKbMode(boolean updateDisplays) {
644        mInKbMode = false;
645        if (!mTypedTimes.isEmpty()) {
646            int values[] = getEnteredTime(null);
647            mTimePicker.setTime(values[0], values[1]);
648            if (!mIs24HourMode) {
649                mTimePicker.setAmOrPm(values[2]);
650            }
651            mTypedTimes.clear();
652        }
653        if (updateDisplays) {
654            updateDisplay(false);
655            mTimePicker.trySettingInputEnabled(true);
656        }
657    }
658
659    /**
660     * Update the hours, minutes, and AM/PM displays with the typed times. If the typedTimes is
661     * empty, either show an empty display (filled with the placeholder text), or update from the
662     * timepicker's values.
663     * @param allowEmptyDisplay if true, then if the typedTimes is empty, use the placeholder text.
664     * Otherwise, revert to the timepicker's values.
665     */
666    private void updateDisplay(boolean allowEmptyDisplay) {
667        if (!allowEmptyDisplay && mTypedTimes.isEmpty()) {
668            int hour = mTimePicker.getHours();
669            int minute = mTimePicker.getMinutes();
670            setHour(hour, true);
671            setMinute(minute);
672            if (!mIs24HourMode) {
673                updateAmPmDisplay(hour < 12? AM : PM);
674            }
675            setCurrentItemShowing(mTimePicker.getCurrentItemShowing(), true, true, true);
676            mDoneButton.setEnabled(true);
677        } else {
678            Boolean[] enteredZeros = {false, false};
679            int[] values = getEnteredTime(enteredZeros);
680            String hourFormat = enteredZeros[0]? "%02d" : "%2d";
681            String minuteFormat = (enteredZeros[1])? "%02d" : "%2d";
682            String hourStr = (values[0] == -1)? mDoublePlaceholderText :
683                String.format(hourFormat, values[0]).replace(' ', mPlaceholderText);
684            String minuteStr = (values[1] == -1)? mDoublePlaceholderText :
685                String.format(minuteFormat, values[1]).replace(' ', mPlaceholderText);
686            mHourView.setText(hourStr);
687            mHourSpaceView.setText(hourStr);
688            mHourView.setTextColor(mUnselectedColor);
689            mMinuteView.setText(minuteStr);
690            mMinuteSpaceView.setText(minuteStr);
691            mMinuteView.setTextColor(mUnselectedColor);
692            if (!mIs24HourMode) {
693                updateAmPmDisplay(values[2]);
694            }
695        }
696    }
697
698    private static int getValFromKeyCode(int keyCode) {
699        switch (keyCode) {
700            case KeyEvent.KEYCODE_0:
701                return 0;
702            case KeyEvent.KEYCODE_1:
703                return 1;
704            case KeyEvent.KEYCODE_2:
705                return 2;
706            case KeyEvent.KEYCODE_3:
707                return 3;
708            case KeyEvent.KEYCODE_4:
709                return 4;
710            case KeyEvent.KEYCODE_5:
711                return 5;
712            case KeyEvent.KEYCODE_6:
713                return 6;
714            case KeyEvent.KEYCODE_7:
715                return 7;
716            case KeyEvent.KEYCODE_8:
717                return 8;
718            case KeyEvent.KEYCODE_9:
719                return 9;
720            default:
721                return -1;
722        }
723    }
724
725    /**
726     * Get the currently-entered time, as integer values of the hours and minutes typed.
727     * @param enteredZeros A size-2 boolean array, which the caller should initialize, and which
728     * may then be used for the caller to know whether zeros had been explicitly entered as either
729     * hours of minutes. This is helpful for deciding whether to show the dashes, or actual 0's.
730     * @return A size-3 int array. The first value will be the hours, the second value will be the
731     * minutes, and the third will be either TimePickerDialog.AM or TimePickerDialog.PM.
732     */
733    private int[] getEnteredTime(Boolean[] enteredZeros) {
734        int amOrPm = -1;
735        int startIndex = 1;
736        if (!mIs24HourMode && isTypedTimeFullyLegal()) {
737            int keyCode = mTypedTimes.get(mTypedTimes.size() - 1);
738            if (keyCode == getAmOrPmKeyCode(AM)) {
739                amOrPm = AM;
740            } else if (keyCode == getAmOrPmKeyCode(PM)){
741                amOrPm = PM;
742            }
743            startIndex = 2;
744        }
745        int minute = -1;
746        int hour = -1;
747        for (int i = startIndex; i <= mTypedTimes.size(); i++) {
748            int val = getValFromKeyCode(mTypedTimes.get(mTypedTimes.size() - i));
749            if (i == startIndex) {
750                minute = val;
751            } else if (i == startIndex+1) {
752                minute += 10*val;
753                if (enteredZeros != null && val == 0) {
754                    enteredZeros[1] = true;
755                }
756            } else if (i == startIndex+2) {
757                hour = val;
758            } else if (i == startIndex+3) {
759                hour += 10*val;
760                if (enteredZeros != null && val == 0) {
761                    enteredZeros[0] = true;
762                }
763            }
764        }
765
766        int[] ret = {hour, minute, amOrPm};
767        return ret;
768    }
769
770    /**
771     * Get the keycode value for AM and PM in the current language.
772     */
773    private int getAmOrPmKeyCode(int amOrPm) {
774        // Cache the codes.
775        if (mAmKeyCode == -1 || mPmKeyCode == -1) {
776            // Find the first character in the AM/PM text that is unique.
777            KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
778            char amChar;
779            char pmChar;
780            for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) {
781                amChar = mAmText.toLowerCase(Locale.getDefault()).charAt(i);
782                pmChar = mPmText.toLowerCase(Locale.getDefault()).charAt(i);
783                if (amChar != pmChar) {
784                    KeyEvent[] events = kcm.getEvents(new char[]{amChar, pmChar});
785                    // There should be 4 events: a down and up for both AM and PM.
786                    if (events != null && events.length == 4) {
787                        mAmKeyCode = events[0].getKeyCode();
788                        mPmKeyCode = events[2].getKeyCode();
789                    } else {
790                        Log.e(TAG, "Unable to find keycodes for AM and PM.");
791                    }
792                    break;
793                }
794            }
795        }
796        if (amOrPm == AM) {
797            return mAmKeyCode;
798        } else if (amOrPm == PM) {
799            return mPmKeyCode;
800        }
801
802        return -1;
803    }
804
805    /**
806     * Create a tree for deciding what keys can legally be typed.
807     */
808    private void generateLegalTimesTree() {
809        // Create a quick cache of numbers to their keycodes.
810        int k0 = KeyEvent.KEYCODE_0;
811        int k1 = KeyEvent.KEYCODE_1;
812        int k2 = KeyEvent.KEYCODE_2;
813        int k3 = KeyEvent.KEYCODE_3;
814        int k4 = KeyEvent.KEYCODE_4;
815        int k5 = KeyEvent.KEYCODE_5;
816        int k6 = KeyEvent.KEYCODE_6;
817        int k7 = KeyEvent.KEYCODE_7;
818        int k8 = KeyEvent.KEYCODE_8;
819        int k9 = KeyEvent.KEYCODE_9;
820
821        // The root of the tree doesn't contain any numbers.
822        mLegalTimesTree = new Node();
823        if (mIs24HourMode) {
824            // We'll be re-using these nodes, so we'll save them.
825            Node minuteFirstDigit = new Node(k0, k1, k2, k3, k4, k5);
826            Node minuteSecondDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
827            // The first digit must be followed by the second digit.
828            minuteFirstDigit.addChild(minuteSecondDigit);
829
830            // The first digit may be 0-1.
831            Node firstDigit = new Node(k0, k1);
832            mLegalTimesTree.addChild(firstDigit);
833
834            // When the first digit is 0-1, the second digit may be 0-5.
835            Node secondDigit = new Node(k0, k1, k2, k3, k4, k5);
836            firstDigit.addChild(secondDigit);
837            // We may now be followed by the first minute digit. E.g. 00:09, 15:58.
838            secondDigit.addChild(minuteFirstDigit);
839
840            // When the first digit is 0-1, and the second digit is 0-5, the third digit may be 6-9.
841            Node thirdDigit = new Node(k6, k7, k8, k9);
842            // The time must now be finished. E.g. 0:55, 1:08.
843            secondDigit.addChild(thirdDigit);
844
845            // When the first digit is 0-1, the second digit may be 6-9.
846            secondDigit = new Node(k6, k7, k8, k9);
847            firstDigit.addChild(secondDigit);
848            // We must now be followed by the first minute digit. E.g. 06:50, 18:20.
849            secondDigit.addChild(minuteFirstDigit);
850
851            // The first digit may be 2.
852            firstDigit = new Node(k2);
853            mLegalTimesTree.addChild(firstDigit);
854
855            // When the first digit is 2, the second digit may be 0-3.
856            secondDigit = new Node(k0, k1, k2, k3);
857            firstDigit.addChild(secondDigit);
858            // We must now be followed by the first minute digit. E.g. 20:50, 23:09.
859            secondDigit.addChild(minuteFirstDigit);
860
861            // When the first digit is 2, the second digit may be 4-5.
862            secondDigit = new Node(k4, k5);
863            firstDigit.addChild(secondDigit);
864            // We must now be followd by the last minute digit. E.g. 2:40, 2:53.
865            secondDigit.addChild(minuteSecondDigit);
866
867            // The first digit may be 3-9.
868            firstDigit = new Node(k3, k4, k5, k6, k7, k8, k9);
869            mLegalTimesTree.addChild(firstDigit);
870            // We must now be followed by the first minute digit. E.g. 3:57, 8:12.
871            firstDigit.addChild(minuteFirstDigit);
872        } else {
873            // We'll need to use the AM/PM node a lot.
874            // Set up AM and PM to respond to "a" and "p".
875            Node ampm = new Node(getAmOrPmKeyCode(AM), getAmOrPmKeyCode(PM));
876
877            // The first hour digit may be 1.
878            Node firstDigit = new Node(k1);
879            mLegalTimesTree.addChild(firstDigit);
880            // We'll allow quick input of on-the-hour times. E.g. 1pm.
881            firstDigit.addChild(ampm);
882
883            // When the first digit is 1, the second digit may be 0-2.
884            Node secondDigit = new Node(k0, k1, k2);
885            firstDigit.addChild(secondDigit);
886            // Also for quick input of on-the-hour times. E.g. 10pm, 12am.
887            secondDigit.addChild(ampm);
888
889            // When the first digit is 1, and the second digit is 0-2, the third digit may be 0-5.
890            Node thirdDigit = new Node(k0, k1, k2, k3, k4, k5);
891            secondDigit.addChild(thirdDigit);
892            // The time may be finished now. E.g. 1:02pm, 1:25am.
893            thirdDigit.addChild(ampm);
894
895            // When the first digit is 1, the second digit is 0-2, and the third digit is 0-5,
896            // the fourth digit may be 0-9.
897            Node fourthDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
898            thirdDigit.addChild(fourthDigit);
899            // The time must be finished now. E.g. 10:49am, 12:40pm.
900            fourthDigit.addChild(ampm);
901
902            // When the first digit is 1, and the second digit is 0-2, the third digit may be 6-9.
903            thirdDigit = new Node(k6, k7, k8, k9);
904            secondDigit.addChild(thirdDigit);
905            // The time must be finished now. E.g. 1:08am, 1:26pm.
906            thirdDigit.addChild(ampm);
907
908            // When the first digit is 1, the second digit may be 3-5.
909            secondDigit = new Node(k3, k4, k5);
910            firstDigit.addChild(secondDigit);
911
912            // When the first digit is 1, and the second digit is 3-5, the third digit may be 0-9.
913            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
914            secondDigit.addChild(thirdDigit);
915            // The time must be finished now. E.g. 1:39am, 1:50pm.
916            thirdDigit.addChild(ampm);
917
918            // The hour digit may be 2-9.
919            firstDigit = new Node(k2, k3, k4, k5, k6, k7, k8, k9);
920            mLegalTimesTree.addChild(firstDigit);
921            // We'll allow quick input of on-the-hour-times. E.g. 2am, 5pm.
922            firstDigit.addChild(ampm);
923
924            // When the first digit is 2-9, the second digit may be 0-5.
925            secondDigit = new Node(k0, k1, k2, k3, k4, k5);
926            firstDigit.addChild(secondDigit);
927
928            // When the first digit is 2-9, and the second digit is 0-5, the third digit may be 0-9.
929            thirdDigit = new Node(k0, k1, k2, k3, k4, k5, k6, k7, k8, k9);
930            secondDigit.addChild(thirdDigit);
931            // The time must be finished now. E.g. 2:57am, 9:30pm.
932            thirdDigit.addChild(ampm);
933        }
934    }
935
936    /**
937     * Simple node class to be used for traversal to check for legal times.
938     * mLegalKeys represents the keys that can be typed to get to the node.
939     * mChildren are the children that can be reached from this node.
940     */
941    private class Node {
942        private int[] mLegalKeys;
943        private ArrayList<Node> mChildren;
944
945        public Node(int... legalKeys) {
946            mLegalKeys = legalKeys;
947            mChildren = new ArrayList<Node>();
948        }
949
950        public void addChild(Node child) {
951            mChildren.add(child);
952        }
953
954        public boolean containsKey(int key) {
955            for (int i = 0; i < mLegalKeys.length; i++) {
956                if (mLegalKeys[i] == key) {
957                    return true;
958                }
959            }
960            return false;
961        }
962
963        public Node canReach(int key) {
964            if (mChildren == null) {
965                return null;
966            }
967            for (Node child : mChildren) {
968                if (child.containsKey(key)) {
969                    return child;
970                }
971            }
972            return null;
973        }
974    }
975
976    private class KeyboardListener implements OnKeyListener {
977        @Override
978        public boolean onKey(View v, int keyCode, KeyEvent event) {
979            if (event.getAction() == KeyEvent.ACTION_UP) {
980                return processKeyUp(keyCode);
981            }
982            return false;
983        }
984    }
985}
986