AsYouTypeFormatter.java revision b9d4ba8e38b0ade7c7942f05e436f20c709ca760
1/*
2 * Copyright (C) 2009 The Libphonenumber Authors
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.i18n.phonenumbers;
18
19import com.android.i18n.phonenumbers.Phonemetadata.NumberFormat;
20import com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
21
22import java.util.ArrayList;
23import java.util.Iterator;
24import java.util.List;
25import java.util.regex.Matcher;
26import java.util.regex.Pattern;
27
28/**
29 * A formatter which formats phone numbers as they are entered.
30 *
31 * <p>An AsYouTypeFormatter can be created by invoking
32 * {@link PhoneNumberUtil#getAsYouTypeFormatter}. After that, digits can be added by invoking
33 * {@link #inputDigit} on the formatter instance, and the partially formatted phone number will be
34 * returned each time a digit is added. {@link #clear} can be invoked before formatting a new
35 * number.
36 *
37 * <p>See the unittests for more details on how the formatter is to be used.
38 *
39 * @author Shaopeng Jia
40 */
41public class AsYouTypeFormatter {
42  private String currentOutput = "";
43  private StringBuilder formattingTemplate = new StringBuilder();
44  // The pattern from numberFormat that is currently used to create formattingTemplate.
45  private String currentFormattingPattern = "";
46  private StringBuilder accruedInput = new StringBuilder();
47  private StringBuilder accruedInputWithoutFormatting = new StringBuilder();
48  // This indicates whether AsYouTypeFormatter is currently doing the formatting.
49  private boolean ableToFormat = true;
50  // Set to true when users enter their own formatting. AsYouTypeFormatter will do no formatting at
51  // all when this is set to true.
52  private boolean inputHasFormatting = false;
53  // This is set to true when we know the user is entering a full national significant number, since
54  // we have either detected a national prefix or an international dialing prefix. When this is
55  // true, we will no longer use local number formatting patterns.
56  private boolean isCompleteNumber = false;
57  private boolean isExpectingCountryCallingCode = false;
58  private final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
59  private String defaultCountry;
60
61  // Character used when appropriate to separate a prefix, such as a long NDD or a country calling
62  // code, from the national number.
63  private static final char SEPARATOR_BEFORE_NATIONAL_NUMBER = ' ';
64  private static final PhoneMetadata EMPTY_METADATA =
65      new PhoneMetadata().setInternationalPrefix("NA");
66  private PhoneMetadata defaultMetaData;
67  private PhoneMetadata currentMetaData;
68
69  // A pattern that is used to match character classes in regular expressions. An example of a
70  // character class is [1-4].
71  private static final Pattern CHARACTER_CLASS_PATTERN = Pattern.compile("\\[([^\\[\\]])*\\]");
72  // Any digit in a regular expression that actually denotes a digit. For example, in the regular
73  // expression 80[0-2]\d{6,10}, the first 2 digits (8 and 0) are standalone digits, but the rest
74  // are not.
75  // Two look-aheads are needed because the number following \\d could be a two-digit number, since
76  // the phone number can be as long as 15 digits.
77  private static final Pattern STANDALONE_DIGIT_PATTERN = Pattern.compile("\\d(?=[^,}][^,}])");
78
79  // A pattern that is used to determine if a numberFormat under availableFormats is eligible to be
80  // used by the AYTF. It is eligible when the format element under numberFormat contains groups of
81  // the dollar sign followed by a single digit, separated by valid phone number punctuation. This
82  // prevents invalid punctuation (such as the star sign in Israeli star numbers) getting into the
83  // output of the AYTF.
84  private static final Pattern ELIGIBLE_FORMAT_PATTERN =
85      Pattern.compile("[" + PhoneNumberUtil.VALID_PUNCTUATION + "]*" +
86          "(\\$\\d" + "[" + PhoneNumberUtil.VALID_PUNCTUATION + "]*)+");
87  // A set of characters that, if found in a national prefix formatting rules, are an indicator to
88  // us that we should separate the national prefix from the number when formatting.
89  private static final Pattern NATIONAL_PREFIX_SEPARATORS_PATTERN = Pattern.compile("[- ]");
90
91  // This is the minimum length of national number accrued that is required to trigger the
92  // formatter. The first element of the leadingDigitsPattern of each numberFormat contains a
93  // regular expression that matches up to this number of digits.
94  private static final int MIN_LEADING_DIGITS_LENGTH = 3;
95
96  // The digits that have not been entered yet will be represented by a \u2008, the punctuation
97  // space.
98  private static final String DIGIT_PLACEHOLDER = "\u2008";
99  private static final Pattern DIGIT_PATTERN = Pattern.compile(DIGIT_PLACEHOLDER);
100  private int lastMatchPosition = 0;
101  // The position of a digit upon which inputDigitAndRememberPosition is most recently invoked, as
102  // found in the original sequence of characters the user entered.
103  private int originalPosition = 0;
104  // The position of a digit upon which inputDigitAndRememberPosition is most recently invoked, as
105  // found in accruedInputWithoutFormatting.
106  private int positionToRemember = 0;
107  // This contains anything that has been entered so far preceding the national significant number,
108  // and it is formatted (e.g. with space inserted). For example, this can contain IDD, country
109  // code, and/or NDD, etc.
110  private StringBuilder prefixBeforeNationalNumber = new StringBuilder();
111  private boolean shouldAddSpaceAfterNationalPrefix = false;
112  // This contains the national prefix that has been extracted. It contains only digits without
113  // formatting.
114  private String nationalPrefixExtracted = "";
115  private StringBuilder nationalNumber = new StringBuilder();
116  private List<NumberFormat> possibleFormats = new ArrayList<NumberFormat>();
117
118    // A cache for frequently used country-specific regular expressions.
119  private RegexCache regexCache = new RegexCache(64);
120
121  /**
122   * Constructs an as-you-type formatter. Should be obtained from {@link
123   * PhoneNumberUtil#getAsYouTypeFormatter}.
124   *
125   * @param regionCode  the country/region where the phone number is being entered
126   */
127  AsYouTypeFormatter(String regionCode) {
128    defaultCountry = regionCode;
129    currentMetaData = getMetadataForRegion(defaultCountry);
130    defaultMetaData = currentMetaData;
131  }
132
133  // The metadata needed by this class is the same for all regions sharing the same country calling
134  // code. Therefore, we return the metadata for "main" region for this country calling code.
135  private PhoneMetadata getMetadataForRegion(String regionCode) {
136    int countryCallingCode = phoneUtil.getCountryCodeForRegion(regionCode);
137    String mainCountry = phoneUtil.getRegionCodeForCountryCode(countryCallingCode);
138    PhoneMetadata metadata = phoneUtil.getMetadataForRegion(mainCountry);
139    if (metadata != null) {
140      return metadata;
141    }
142    // Set to a default instance of the metadata. This allows us to function with an incorrect
143    // region code, even if formatting only works for numbers specified with "+".
144    return EMPTY_METADATA;
145  }
146
147  // Returns true if a new template is created as opposed to reusing the existing template.
148  private boolean maybeCreateNewTemplate() {
149    // When there are multiple available formats, the formatter uses the first format where a
150    // formatting template could be created.
151    Iterator<NumberFormat> it = possibleFormats.iterator();
152    while (it.hasNext()) {
153      NumberFormat numberFormat = it.next();
154      String pattern = numberFormat.getPattern();
155      if (currentFormattingPattern.equals(pattern)) {
156        return false;
157      }
158      if (createFormattingTemplate(numberFormat)) {
159        currentFormattingPattern = pattern;
160        shouldAddSpaceAfterNationalPrefix =
161            NATIONAL_PREFIX_SEPARATORS_PATTERN.matcher(
162                numberFormat.getNationalPrefixFormattingRule()).find();
163        // With a new formatting template, the matched position using the old template needs to be
164        // reset.
165        lastMatchPosition = 0;
166        return true;
167      } else {  // Remove the current number format from possibleFormats.
168        it.remove();
169      }
170    }
171    ableToFormat = false;
172    return false;
173  }
174
175  private void getAvailableFormats(String leadingThreeDigits) {
176    List<NumberFormat> formatList =
177        (isCompleteNumber && currentMetaData.intlNumberFormatSize() > 0)
178        ? currentMetaData.intlNumberFormats()
179        : currentMetaData.numberFormats();
180    boolean nationalPrefixIsUsedByCountry = currentMetaData.hasNationalPrefix();
181    for (NumberFormat format : formatList) {
182      if (!nationalPrefixIsUsedByCountry || isCompleteNumber ||
183          format.isNationalPrefixOptionalWhenFormatting() ||
184          phoneUtil.formattingRuleHasFirstGroupOnly(format.getNationalPrefixFormattingRule())) {
185        if (isFormatEligible(format.getFormat())) {
186          possibleFormats.add(format);
187        }
188      }
189    }
190    narrowDownPossibleFormats(leadingThreeDigits);
191  }
192
193  private boolean isFormatEligible(String format) {
194    return ELIGIBLE_FORMAT_PATTERN.matcher(format).matches();
195  }
196
197  private void narrowDownPossibleFormats(String leadingDigits) {
198    int indexOfLeadingDigitsPattern = leadingDigits.length() - MIN_LEADING_DIGITS_LENGTH;
199    Iterator<NumberFormat> it = possibleFormats.iterator();
200    while (it.hasNext()) {
201      NumberFormat format = it.next();
202      if (format.leadingDigitsPatternSize() > indexOfLeadingDigitsPattern) {
203        Pattern leadingDigitsPattern =
204            regexCache.getPatternForRegex(
205                format.getLeadingDigitsPattern(indexOfLeadingDigitsPattern));
206        Matcher m = leadingDigitsPattern.matcher(leadingDigits);
207        if (!m.lookingAt()) {
208          it.remove();
209        }
210      } // else the particular format has no more specific leadingDigitsPattern, and it should be
211        // retained.
212    }
213  }
214
215  private boolean createFormattingTemplate(NumberFormat format) {
216    String numberPattern = format.getPattern();
217
218    // The formatter doesn't format numbers when numberPattern contains "|", e.g.
219    // (20|3)\d{4}. In those cases we quickly return.
220    if (numberPattern.indexOf('|') != -1) {
221      return false;
222    }
223
224    // Replace anything in the form of [..] with \d
225    numberPattern = CHARACTER_CLASS_PATTERN.matcher(numberPattern).replaceAll("\\\\d");
226
227    // Replace any standalone digit (not the one in d{}) with \d
228    numberPattern = STANDALONE_DIGIT_PATTERN.matcher(numberPattern).replaceAll("\\\\d");
229    formattingTemplate.setLength(0);
230    String tempTemplate = getFormattingTemplate(numberPattern, format.getFormat());
231    if (tempTemplate.length() > 0) {
232      formattingTemplate.append(tempTemplate);
233      return true;
234    }
235    return false;
236  }
237
238  // Gets a formatting template which can be used to efficiently format a partial number where
239  // digits are added one by one.
240  private String getFormattingTemplate(String numberPattern, String numberFormat) {
241    // Creates a phone number consisting only of the digit 9 that matches the
242    // numberPattern by applying the pattern to the longestPhoneNumber string.
243    String longestPhoneNumber = "999999999999999";
244    Matcher m = regexCache.getPatternForRegex(numberPattern).matcher(longestPhoneNumber);
245    m.find();  // this will always succeed
246    String aPhoneNumber = m.group();
247    // No formatting template can be created if the number of digits entered so far is longer than
248    // the maximum the current formatting rule can accommodate.
249    if (aPhoneNumber.length() < nationalNumber.length()) {
250      return "";
251    }
252    // Formats the number according to numberFormat
253    String template = aPhoneNumber.replaceAll(numberPattern, numberFormat);
254    // Replaces each digit with character DIGIT_PLACEHOLDER
255    template = template.replaceAll("9", DIGIT_PLACEHOLDER);
256    return template;
257  }
258
259  /**
260   * Clears the internal state of the formatter, so it can be reused.
261   */
262  public void clear() {
263    currentOutput = "";
264    accruedInput.setLength(0);
265    accruedInputWithoutFormatting.setLength(0);
266    formattingTemplate.setLength(0);
267    lastMatchPosition = 0;
268    currentFormattingPattern = "";
269    prefixBeforeNationalNumber.setLength(0);
270    nationalPrefixExtracted = "";
271    nationalNumber.setLength(0);
272    ableToFormat = true;
273    inputHasFormatting = false;
274    positionToRemember = 0;
275    originalPosition = 0;
276    isCompleteNumber = false;
277    isExpectingCountryCallingCode = false;
278    possibleFormats.clear();
279    shouldAddSpaceAfterNationalPrefix = false;
280    if (!currentMetaData.equals(defaultMetaData)) {
281      currentMetaData = getMetadataForRegion(defaultCountry);
282    }
283  }
284
285  /**
286   * Formats a phone number on-the-fly as each digit is entered.
287   *
288   * @param nextChar  the most recently entered digit of a phone number. Formatting characters are
289   *     allowed, but as soon as they are encountered this method formats the number as entered and
290   *     not "as you type" anymore. Full width digits and Arabic-indic digits are allowed, and will
291   *     be shown as they are.
292   * @return  the partially formatted phone number.
293   */
294  public String inputDigit(char nextChar) {
295    currentOutput = inputDigitWithOptionToRememberPosition(nextChar, false);
296    return currentOutput;
297  }
298
299  /**
300   * Same as {@link #inputDigit}, but remembers the position where {@code nextChar} is inserted, so
301   * that it can be retrieved later by using {@link #getRememberedPosition}. The remembered
302   * position will be automatically adjusted if additional formatting characters are later
303   * inserted/removed in front of {@code nextChar}.
304   */
305  public String inputDigitAndRememberPosition(char nextChar) {
306    currentOutput = inputDigitWithOptionToRememberPosition(nextChar, true);
307    return currentOutput;
308  }
309
310  @SuppressWarnings("fallthrough")
311  private String inputDigitWithOptionToRememberPosition(char nextChar, boolean rememberPosition) {
312    accruedInput.append(nextChar);
313    if (rememberPosition) {
314      originalPosition = accruedInput.length();
315    }
316    // We do formatting on-the-fly only when each character entered is either a digit, or a plus
317    // sign (accepted at the start of the number only).
318    if (!isDigitOrLeadingPlusSign(nextChar)) {
319      ableToFormat = false;
320      inputHasFormatting = true;
321    } else {
322      nextChar = normalizeAndAccrueDigitsAndPlusSign(nextChar, rememberPosition);
323    }
324    if (!ableToFormat) {
325      // When we are unable to format because of reasons other than that formatting chars have been
326      // entered, it can be due to really long IDDs or NDDs. If that is the case, we might be able
327      // to do formatting again after extracting them.
328      if (inputHasFormatting) {
329        return accruedInput.toString();
330      } else if (attemptToExtractIdd()) {
331        if (attemptToExtractCountryCallingCode()) {
332          return attemptToChoosePatternWithPrefixExtracted();
333        }
334      } else if (ableToExtractLongerNdd()) {
335        // Add an additional space to separate long NDD and national significant number for
336        // readability. We don't set shouldAddSpaceAfterNationalPrefix to true, since we don't want
337        // this to change later when we choose formatting templates.
338        prefixBeforeNationalNumber.append(SEPARATOR_BEFORE_NATIONAL_NUMBER);
339        return attemptToChoosePatternWithPrefixExtracted();
340      }
341      return accruedInput.toString();
342    }
343
344    // We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits (the plus
345    // sign is counted as a digit as well for this purpose) have been entered.
346    switch (accruedInputWithoutFormatting.length()) {
347      case 0:
348      case 1:
349      case 2:
350        return accruedInput.toString();
351      case 3:
352        if (attemptToExtractIdd()) {
353          isExpectingCountryCallingCode = true;
354        } else {  // No IDD or plus sign is found, might be entering in national format.
355          nationalPrefixExtracted = removeNationalPrefixFromNationalNumber();
356          return attemptToChooseFormattingPattern();
357        }
358      default:
359        if (isExpectingCountryCallingCode) {
360          if (attemptToExtractCountryCallingCode()) {
361            isExpectingCountryCallingCode = false;
362          }
363          return prefixBeforeNationalNumber + nationalNumber.toString();
364        }
365        if (possibleFormats.size() > 0) {  // The formatting pattern is already chosen.
366          String tempNationalNumber = inputDigitHelper(nextChar);
367          // See if the accrued digits can be formatted properly already. If not, use the results
368          // from inputDigitHelper, which does formatting based on the formatting pattern chosen.
369          String formattedNumber = attemptToFormatAccruedDigits();
370          if (formattedNumber.length() > 0) {
371            return formattedNumber;
372          }
373          narrowDownPossibleFormats(nationalNumber.toString());
374          if (maybeCreateNewTemplate()) {
375            return inputAccruedNationalNumber();
376          }
377          return ableToFormat
378             ? appendNationalNumber(tempNationalNumber)
379             : accruedInput.toString();
380        } else {
381          return attemptToChooseFormattingPattern();
382        }
383    }
384  }
385
386  private String attemptToChoosePatternWithPrefixExtracted() {
387    ableToFormat = true;
388    isExpectingCountryCallingCode = false;
389    possibleFormats.clear();
390    return attemptToChooseFormattingPattern();
391  }
392
393  // Some national prefixes are a substring of others. If extracting the shorter NDD doesn't result
394  // in a number we can format, we try to see if we can extract a longer version here.
395  private boolean ableToExtractLongerNdd() {
396    if (nationalPrefixExtracted.length() > 0) {
397      // Put the extracted NDD back to the national number before attempting to extract a new NDD.
398      nationalNumber.insert(0, nationalPrefixExtracted);
399      // Remove the previously extracted NDD from prefixBeforeNationalNumber. We cannot simply set
400      // it to empty string because people sometimes incorrectly enter national prefix after the
401      // country code, e.g. +44 (0)20-1234-5678.
402      int indexOfPreviousNdd = prefixBeforeNationalNumber.lastIndexOf(nationalPrefixExtracted);
403      prefixBeforeNationalNumber.setLength(indexOfPreviousNdd);
404    }
405    return !nationalPrefixExtracted.equals(removeNationalPrefixFromNationalNumber());
406  }
407
408  private boolean isDigitOrLeadingPlusSign(char nextChar) {
409    return Character.isDigit(nextChar) ||
410        (accruedInput.length() == 1 &&
411         PhoneNumberUtil.PLUS_CHARS_PATTERN.matcher(Character.toString(nextChar)).matches());
412  }
413
414  /**
415   * Check to see if there is an exact pattern match for these digits. If so, we should use this
416   * instead of any other formatting template whose leadingDigitsPattern also matches the input.
417   */
418  String attemptToFormatAccruedDigits() {
419    for (NumberFormat numberFormat : possibleFormats) {
420      Matcher m = regexCache.getPatternForRegex(numberFormat.getPattern()).matcher(nationalNumber);
421      if (m.matches()) {
422        shouldAddSpaceAfterNationalPrefix =
423            NATIONAL_PREFIX_SEPARATORS_PATTERN.matcher(
424                numberFormat.getNationalPrefixFormattingRule()).find();
425        String formattedNumber = m.replaceAll(numberFormat.getFormat());
426        return appendNationalNumber(formattedNumber);
427      }
428    }
429    return "";
430  }
431
432  /**
433   * Returns the current position in the partially formatted phone number of the character which was
434   * previously passed in as the parameter of {@link #inputDigitAndRememberPosition}.
435   */
436  public int getRememberedPosition() {
437    if (!ableToFormat) {
438      return originalPosition;
439    }
440    int accruedInputIndex = 0, currentOutputIndex = 0;
441    while (accruedInputIndex < positionToRemember && currentOutputIndex < currentOutput.length()) {
442      if (accruedInputWithoutFormatting.charAt(accruedInputIndex) ==
443          currentOutput.charAt(currentOutputIndex)) {
444        accruedInputIndex++;
445      }
446      currentOutputIndex++;
447    }
448    return currentOutputIndex;
449  }
450
451  /**
452   * Combines the national number with any prefix (IDD/+ and country code or national prefix) that
453   * was collected. A space will be inserted between them if the current formatting template
454   * indicates this to be suitable.
455   */
456  private String appendNationalNumber(String nationalNumber) {
457    int prefixBeforeNationalNumberLength = prefixBeforeNationalNumber.length();
458    if (shouldAddSpaceAfterNationalPrefix && prefixBeforeNationalNumberLength > 0 &&
459        prefixBeforeNationalNumber.charAt(prefixBeforeNationalNumberLength - 1)
460            != SEPARATOR_BEFORE_NATIONAL_NUMBER) {
461      // We want to add a space after the national prefix if the national prefix formatting rule
462      // indicates that this would normally be done, with the exception of the case where we already
463      // appended a space because the NDD was surprisingly long.
464      return new String(prefixBeforeNationalNumber) + SEPARATOR_BEFORE_NATIONAL_NUMBER
465          + nationalNumber;
466    } else {
467      return prefixBeforeNationalNumber + nationalNumber;
468    }
469  }
470
471  /**
472   * Attempts to set the formatting template and returns a string which contains the formatted
473   * version of the digits entered so far.
474   */
475  private String attemptToChooseFormattingPattern() {
476    // We start to attempt to format only when as least MIN_LEADING_DIGITS_LENGTH digits of national
477    // number (excluding national prefix) have been entered.
478    if (nationalNumber.length() >= MIN_LEADING_DIGITS_LENGTH) {
479      getAvailableFormats(nationalNumber.substring(0, MIN_LEADING_DIGITS_LENGTH));
480      return maybeCreateNewTemplate() ? inputAccruedNationalNumber() : accruedInput.toString();
481    } else {
482      return appendNationalNumber(nationalNumber.toString());
483    }
484  }
485
486  /**
487   * Invokes inputDigitHelper on each digit of the national number accrued, and returns a formatted
488   * string in the end.
489   */
490  private String inputAccruedNationalNumber() {
491    int lengthOfNationalNumber = nationalNumber.length();
492    if (lengthOfNationalNumber > 0) {
493      String tempNationalNumber = "";
494      for (int i = 0; i < lengthOfNationalNumber; i++) {
495        tempNationalNumber = inputDigitHelper(nationalNumber.charAt(i));
496      }
497      return ableToFormat ? appendNationalNumber(tempNationalNumber) : accruedInput.toString();
498    } else {
499      return prefixBeforeNationalNumber.toString();
500    }
501  }
502
503  /**
504   * Returns true if the current country is a NANPA country and the national number begins with
505   * the national prefix.
506   */
507  private boolean isNanpaNumberWithNationalPrefix() {
508    // For NANPA numbers beginning with 1[2-9], treat the 1 as the national prefix. The reason is
509    // that national significant numbers in NANPA always start with [2-9] after the national prefix.
510    // Numbers beginning with 1[01] can only be short/emergency numbers, which don't need the
511    // national prefix.
512    return (currentMetaData.getCountryCode() == 1) && (nationalNumber.charAt(0) == '1') &&
513           (nationalNumber.charAt(1) != '0') && (nationalNumber.charAt(1) != '1');
514  }
515
516  // Returns the national prefix extracted, or an empty string if it is not present.
517  private String removeNationalPrefixFromNationalNumber() {
518    int startOfNationalNumber = 0;
519    if (isNanpaNumberWithNationalPrefix()) {
520      startOfNationalNumber = 1;
521      prefixBeforeNationalNumber.append('1').append(SEPARATOR_BEFORE_NATIONAL_NUMBER);
522      isCompleteNumber = true;
523    } else if (currentMetaData.hasNationalPrefixForParsing()) {
524      Pattern nationalPrefixForParsing =
525          regexCache.getPatternForRegex(currentMetaData.getNationalPrefixForParsing());
526      Matcher m = nationalPrefixForParsing.matcher(nationalNumber);
527      if (m.lookingAt()) {
528        // When the national prefix is detected, we use international formatting rules instead of
529        // national ones, because national formatting rules could contain local formatting rules
530        // for numbers entered without area code.
531        isCompleteNumber = true;
532        startOfNationalNumber = m.end();
533        prefixBeforeNationalNumber.append(nationalNumber.substring(0, startOfNationalNumber));
534      }
535    }
536    String nationalPrefix = nationalNumber.substring(0, startOfNationalNumber);
537    nationalNumber.delete(0, startOfNationalNumber);
538    return nationalPrefix;
539  }
540
541  /**
542   * Extracts IDD and plus sign to prefixBeforeNationalNumber when they are available, and places
543   * the remaining input into nationalNumber.
544   *
545   * @return  true when accruedInputWithoutFormatting begins with the plus sign or valid IDD for
546   *     defaultCountry.
547   */
548  private boolean attemptToExtractIdd() {
549    Pattern internationalPrefix =
550        regexCache.getPatternForRegex("\\" + PhoneNumberUtil.PLUS_SIGN + "|" +
551            currentMetaData.getInternationalPrefix());
552    Matcher iddMatcher = internationalPrefix.matcher(accruedInputWithoutFormatting);
553    if (iddMatcher.lookingAt()) {
554      isCompleteNumber = true;
555      int startOfCountryCallingCode = iddMatcher.end();
556      nationalNumber.setLength(0);
557      nationalNumber.append(accruedInputWithoutFormatting.substring(startOfCountryCallingCode));
558      prefixBeforeNationalNumber.setLength(0);
559      prefixBeforeNationalNumber.append(
560          accruedInputWithoutFormatting.substring(0, startOfCountryCallingCode));
561      if (accruedInputWithoutFormatting.charAt(0) != PhoneNumberUtil.PLUS_SIGN) {
562        prefixBeforeNationalNumber.append(SEPARATOR_BEFORE_NATIONAL_NUMBER);
563      }
564      return true;
565    }
566    return false;
567  }
568
569  /**
570   * Extracts the country calling code from the beginning of nationalNumber to
571   * prefixBeforeNationalNumber when they are available, and places the remaining input into
572   * nationalNumber.
573   *
574   * @return  true when a valid country calling code can be found.
575   */
576  private boolean attemptToExtractCountryCallingCode() {
577    if (nationalNumber.length() == 0) {
578      return false;
579    }
580    StringBuilder numberWithoutCountryCallingCode = new StringBuilder();
581    int countryCode = phoneUtil.extractCountryCode(nationalNumber, numberWithoutCountryCallingCode);
582    if (countryCode == 0) {
583      return false;
584    }
585    nationalNumber.setLength(0);
586    nationalNumber.append(numberWithoutCountryCallingCode);
587    String newRegionCode = phoneUtil.getRegionCodeForCountryCode(countryCode);
588    if (PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY.equals(newRegionCode)) {
589      currentMetaData = phoneUtil.getMetadataForNonGeographicalRegion(countryCode);
590    } else if (!newRegionCode.equals(defaultCountry)) {
591      currentMetaData = getMetadataForRegion(newRegionCode);
592    }
593    String countryCodeString = Integer.toString(countryCode);
594    prefixBeforeNationalNumber.append(countryCodeString).append(SEPARATOR_BEFORE_NATIONAL_NUMBER);
595    nationalPrefixExtracted = "";
596    return true;
597  }
598
599  // Accrues digits and the plus sign to accruedInputWithoutFormatting for later use. If nextChar
600  // contains a digit in non-ASCII format (e.g. the full-width version of digits), it is first
601  // normalized to the ASCII version. The return value is nextChar itself, or its normalized
602  // version, if nextChar is a digit in non-ASCII format. This method assumes its input is either a
603  // digit or the plus sign.
604  private char normalizeAndAccrueDigitsAndPlusSign(char nextChar, boolean rememberPosition) {
605    char normalizedChar;
606    if (nextChar == PhoneNumberUtil.PLUS_SIGN) {
607      normalizedChar = nextChar;
608      accruedInputWithoutFormatting.append(nextChar);
609    } else {
610      int radix = 10;
611      normalizedChar = Character.forDigit(Character.digit(nextChar, radix), radix);
612      accruedInputWithoutFormatting.append(normalizedChar);
613      nationalNumber.append(normalizedChar);
614    }
615    if (rememberPosition) {
616      positionToRemember = accruedInputWithoutFormatting.length();
617    }
618    return normalizedChar;
619  }
620
621  private String inputDigitHelper(char nextChar) {
622    Matcher digitMatcher = DIGIT_PATTERN.matcher(formattingTemplate);
623    if (digitMatcher.find(lastMatchPosition)) {
624      String tempTemplate = digitMatcher.replaceFirst(Character.toString(nextChar));
625      formattingTemplate.replace(0, tempTemplate.length(), tempTemplate);
626      lastMatchPosition = digitMatcher.start();
627      return formattingTemplate.substring(0, lastMatchPosition + 1);
628    } else {
629      if (possibleFormats.size() == 1) {
630        // More digits are entered than we could handle, and there are no other valid patterns to
631        // try.
632        ableToFormat = false;
633      }  // else, we just reset the formatting pattern.
634      currentFormattingPattern = "";
635      return accruedInput.toString();
636    }
637  }
638}
639