1. /*
  2. * @(#)MaskFormatter.java 1.12 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing.text;
  8. import java.io.*;
  9. import java.text.*;
  10. import java.util.*;
  11. import javax.swing.*;
  12. import javax.swing.text.*;
  13. /**
  14. * <code>MaskFormatter</code> is used to format and edit strings. The behavior
  15. * of a <code>MaskFormatter</code> is controlled by way of a String mask
  16. * that specifies the valid characters that can be contained at a particular
  17. * location in the <code>Document</code> model. The following characters can
  18. * be specified:
  19. *
  20. * <table border=1 summary="Valid characters and their descriptions">
  21. * <tr>
  22. * <th>Character </th>
  23. * <th><p align="left">Description</p></th>
  24. * </tr>
  25. * <tr>
  26. * <td>#</td>
  27. * <td>Any valid number, uses <code>Character.isDigit</code>.</td>
  28. * </tr>
  29. * <tr>
  30. * <td>'</td>
  31. * <td>Escape character, used to escape any of the
  32. * special formatting characters.</td>
  33. * </tr>
  34. * <tr>
  35. * <td>U</td><td>Any character (<code>Character.isLetter</code>). All
  36. * lowercase letters are mapped to upper case.</td>
  37. * </tr>
  38. * <tr><td>L</td><td>Any character (<code>Character.isLetter</code>). All
  39. * upper case letters are mapped to lower case.</td>
  40. * </tr>
  41. * <tr><td>A</td><td>Any character or number (<code>Character.isLetter</code>
  42. * or <code>Character.isDigit</code>)</td>
  43. * </tr>
  44. * <tr><td>?</td><td>Any character
  45. * (<code>Character.isLetter</code>).</td>
  46. * </tr>
  47. * <tr><td>*</td><td>Anything.</td></tr>
  48. * <tr><td>H</td><td>Any hex character (0-9, a-f or A-F).</td></tr>
  49. * </table>
  50. *
  51. * <p>
  52. * Typically characters correspond to one char, but in certain languages this
  53. * is not the case. The mask is on a per character basis, and will thus
  54. * adjust to fit as many chars as are needed.
  55. * <p>
  56. * You can further restrict the characters that can be input by the
  57. * <code>setInvalidCharacters</code> and <code>setValidCharacters</code>
  58. * methods. <code>setInvalidCharacters</code> allows you to specify
  59. * which characters are not legal. <code>setValidCharacters</code> allows
  60. * you to specify which characters are valid. For example, the following
  61. * code block is equivalent to a mask of '0xHHH' with no invalid/valid
  62. * characters:
  63. * <pre>
  64. * MaskFormatter formatter = new MaskFormatter("0x***");
  65. * formatter.setValidCharacters("0123456789abcdefABCDEF");
  66. * </pre>
  67. * <p>
  68. * When initially formatting a value if the length of the string is
  69. * less than the length of the mask, two things can happen. Either
  70. * the placeholder string will be used, or the placeholder character will
  71. * be used. Precedence is given to the placeholder string. For example:
  72. * <pre>
  73. * MaskFormatter formatter = new MaskFormatter("###-####");
  74. * formatter.setPlaceholderCharacter('_');
  75. * formatter.getDisplayValue(tf, "123");
  76. * </pre>
  77. * <p>
  78. * Would result in the string '123-____'. If
  79. * <code>setPlaceholder("555-1212")</code> was invoked '123-1212' would
  80. * result. The placeholder String is only used on the initial format,
  81. * on subsequent formats only the placeholder character will be used.
  82. * <p>
  83. * If a <code>MaskFormatter</code> is configured to only allow valid characters
  84. * (<code>setAllowsInvalid(false)</code>) literal characters will be skipped as
  85. * necessary when editing. Consider a <code>MaskFormatter</code> with
  86. * the mask "###-####" and current value "555-1212". Using the right
  87. * arrow key to navigate through the field will result in (| indicates the
  88. * position of the caret):
  89. * <pre>
  90. * |555-1212
  91. * 5|55-1212
  92. * 55|5-1212
  93. * 555-|1212
  94. * 555-1|212
  95. * </pre>
  96. * The '-' is a literal (non-editable) character, and is skipped.
  97. * <p>
  98. * Similar behavior will result when editing. Consider inserting the string
  99. * '123-45' and '12345' into the <code>MaskFormatter</code> in the
  100. * previous example. Both inserts will result in the same String,
  101. * '123-45__'. When <code>MaskFormatter</code>
  102. * is processing the insert at character position 3 (the '-'), two things can
  103. * happen:
  104. * <ol>
  105. * <li>If the inserted character is '-', it is accepted.
  106. * <li>If the inserted character matches the mask for the next non-literal
  107. * character, it is accepted at the new location.
  108. * <li>Anything else results in an invalid edit
  109. * </ol>
  110. * <p>
  111. * By default <code>MaskFormatter</code> will not allow invalid edits, you can
  112. * change this with the <code>setAllowsInvalid</code> method, and will
  113. * commit edits on valid edits (use the <code>setCommitsOnValidEdit</code> to
  114. * change this).
  115. * <p>
  116. * By default, <code>MaskFormatter</code> is in overwrite mode. That is as
  117. * characters are typed a new character is not inserted, rather the character
  118. * at the current location is replaced with the newly typed character. You
  119. * can change this behavior by way of the method <code>setOverwriteMode</code>.
  120. * <p>
  121. * <strong>Warning:</strong>
  122. * Serialized objects of this class will not be compatible with
  123. * future Swing releases. The current serialization support is
  124. * appropriate for short term storage or RMI between applications running
  125. * the same version of Swing. As of 1.4, support for long term storage
  126. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  127. * has been added to the <code>java.beans</code> package.
  128. * Please see {@link java.beans.XMLEncoder}.
  129. *
  130. * @version 1.12 12/19/03
  131. * @since 1.4
  132. */
  133. public class MaskFormatter extends DefaultFormatter {
  134. // Potential values in mask.
  135. private static final char DIGIT_KEY = '#';
  136. private static final char LITERAL_KEY = '\'';
  137. private static final char UPPERCASE_KEY = 'U';
  138. private static final char LOWERCASE_KEY = 'L';
  139. private static final char ALPHA_NUMERIC_KEY = 'A';
  140. private static final char CHARACTER_KEY = '?';
  141. private static final char ANYTHING_KEY = '*';
  142. private static final char HEX_KEY = 'H';
  143. private static final MaskCharacter[] EmptyMaskChars = new MaskCharacter[0];
  144. /** The user specified mask. */
  145. private String mask;
  146. private transient MaskCharacter[] maskChars;
  147. /** List of valid characters. */
  148. private String validCharacters;
  149. /** List of invalid characters. */
  150. private String invalidCharacters;
  151. /** String used for the passed in value if it does not completely
  152. * fill the mask. */
  153. private String placeholderString;
  154. /** String used to represent characters not present. */
  155. private char placeholder;
  156. /** Indicates if the value contains the literal characters. */
  157. private boolean containsLiteralChars;
  158. /**
  159. * Creates a MaskFormatter with no mask.
  160. */
  161. public MaskFormatter() {
  162. setAllowsInvalid(false);
  163. containsLiteralChars = true;
  164. maskChars = EmptyMaskChars;
  165. placeholder = ' ';
  166. }
  167. /**
  168. * Creates a <code>MaskFormatter</code> with the specified mask.
  169. * A <code>ParseException</code>
  170. * will be thrown if <code>mask</code> is an invalid mask.
  171. *
  172. * @throws ParseException if mask does not contain valid mask characters
  173. */
  174. public MaskFormatter(String mask) throws ParseException {
  175. this();
  176. setMask(mask);
  177. }
  178. /**
  179. * Sets the mask dictating the legal characters.
  180. * This will throw a <code>ParseException</code> if <code>mask</code> is
  181. * not valid.
  182. *
  183. * @throws ParseException if mask does not contain valid mask characters
  184. */
  185. public void setMask(String mask) throws ParseException {
  186. this.mask = mask;
  187. updateInternalMask();
  188. }
  189. /**
  190. * Returns the formatting mask.
  191. *
  192. * @return Mask dictating legal character values.
  193. */
  194. public String getMask() {
  195. return mask;
  196. }
  197. /**
  198. * Allows for further restricting of the characters that can be input.
  199. * Only characters specified in the mask, not in the
  200. * <code>invalidCharacters</code>, and in
  201. * <code>validCharacters</code> will be allowed to be input. Passing
  202. * in null (the default) implies the valid characters are only bound
  203. * by the mask and the invalid characters.
  204. *
  205. * @param validCharacters If non-null, specifies legal characters.
  206. */
  207. public void setValidCharacters(String validCharacters) {
  208. this.validCharacters = validCharacters;
  209. }
  210. /**
  211. * Returns the valid characters that can be input.
  212. *
  213. * @return Legal characters
  214. */
  215. public String getValidCharacters() {
  216. return validCharacters;
  217. }
  218. /**
  219. * Allows for further restricting of the characters that can be input.
  220. * Only characters specified in the mask, not in the
  221. * <code>invalidCharacters</code>, and in
  222. * <code>validCharacters</code> will be allowed to be input. Passing
  223. * in null (the default) implies the valid characters are only bound
  224. * by the mask and the valid characters.
  225. *
  226. * @param invalidCharacters If non-null, specifies illegal characters.
  227. */
  228. public void setInvalidCharacters(String invalidCharacters) {
  229. this.invalidCharacters = invalidCharacters;
  230. }
  231. /**
  232. * Returns the characters that are not valid for input.
  233. *
  234. * @return illegal characters.
  235. */
  236. public String getInvalidCharacters() {
  237. return invalidCharacters;
  238. }
  239. /**
  240. * Sets the string to use if the value does not completely fill in
  241. * the mask. A null value implies the placeholder char should be used.
  242. *
  243. * @param placeholder String used when formatting if the value does not
  244. * completely fill the mask
  245. */
  246. public void setPlaceholder(String placeholder) {
  247. this.placeholderString = placeholder;
  248. }
  249. /**
  250. * Returns the String to use if the value does not completely fill
  251. * in the mask.
  252. *
  253. * @return String used when formatting if the value does not
  254. * completely fill the mask
  255. */
  256. public String getPlaceholder() {
  257. return placeholderString;
  258. }
  259. /**
  260. * Sets the character to use in place of characters that are not present
  261. * in the value, ie the user must fill them in. The default value is
  262. * a space.
  263. * <p>
  264. * This is only applicable if the placeholder string has not been
  265. * specified, or does not completely fill in the mask.
  266. *
  267. * @param placeholder Character used when formatting if the value does not
  268. * completely fill the mask
  269. */
  270. public void setPlaceholderCharacter(char placeholder) {
  271. this.placeholder = placeholder;
  272. }
  273. /**
  274. * Returns the character to use in place of characters that are not present
  275. * in the value, ie the user must fill them in.
  276. *
  277. * @return Character used when formatting if the value does not
  278. * completely fill the mask
  279. */
  280. public char getPlaceholderCharacter() {
  281. return placeholder;
  282. }
  283. /**
  284. * If true, the returned value and set value will also contain the literal
  285. * characters in mask.
  286. * <p>
  287. * For example, if the mask is <code>'(###) ###-####'</code>, the
  288. * current value is <code>'(415) 555-1212'</code>, and
  289. * <code>valueContainsLiteralCharacters</code> is
  290. * true <code>stringToValue</code> will return
  291. * <code>'(415) 555-1212'</code>. On the other hand, if
  292. * <code>valueContainsLiteralCharacters</code> is false,
  293. * <code>stringToValue</code> will return <code>'4155551212'</code>.
  294. *
  295. * @param containsLiteralChars Used to indicate if literal characters in
  296. * mask should be returned in stringToValue
  297. */
  298. public void setValueContainsLiteralCharacters(
  299. boolean containsLiteralChars) {
  300. this.containsLiteralChars = containsLiteralChars;
  301. }
  302. /**
  303. * Returns true if <code>stringToValue</code> should return literal
  304. * characters in the mask.
  305. *
  306. * @return True if literal characters in mask should be returned in
  307. * stringToValue
  308. */
  309. public boolean getValueContainsLiteralCharacters() {
  310. return containsLiteralChars;
  311. }
  312. /**
  313. * Parses the text, returning the appropriate Object representation of
  314. * the String <code>value</code>. This strips the literal characters as
  315. * necessary and invokes supers <code>stringToValue</code>, so that if
  316. * you have specified a value class (<code>setValueClass</code>) an
  317. * instance of it will be created. This will throw a
  318. * <code>ParseException</code> if the value does not match the current
  319. * mask. Refer to {@link #setValueContainsLiteralCharacters} for details
  320. * on how literals are treated.
  321. *
  322. * @throws ParseException if there is an error in the conversion
  323. * @param value String to convert
  324. * @see #setValueContainsLiteralCharacters
  325. * @return Object representation of text
  326. */
  327. public Object stringToValue(String value) throws ParseException {
  328. return stringToValue(value, true);
  329. }
  330. /**
  331. * Returns a String representation of the Object <code>value</code>
  332. * based on the mask. Refer to
  333. * {@link #setValueContainsLiteralCharacters} for details
  334. * on how literals are treated.
  335. *
  336. * @throws ParseException if there is an error in the conversion
  337. * @param value Value to convert
  338. * @see #setValueContainsLiteralCharacters
  339. * @return String representation of value
  340. */
  341. public String valueToString(Object value) throws ParseException {
  342. String sValue = (value == null) ? "" : value.toString();
  343. StringBuffer result = new StringBuffer();
  344. String placeholder = getPlaceholder();
  345. int[] valueCounter = { 0 };
  346. append(result, sValue, valueCounter, placeholder, maskChars);
  347. return result.toString();
  348. }
  349. /**
  350. * Installs the <code>DefaultFormatter</code> onto a particular
  351. * <code>JFormattedTextField</code>.
  352. * This will invoke <code>valueToString</code> to convert the
  353. * current value from the <code>JFormattedTextField</code> to
  354. * a String. This will then install the <code>Action</code>s from
  355. * <code>getActions</code>, the <code>DocumentFilter</code>
  356. * returned from <code>getDocumentFilter</code> and the
  357. * <code>NavigationFilter</code> returned from
  358. * <code>getNavigationFilter</code> onto the
  359. * <code>JFormattedTextField</code>.
  360. * <p>
  361. * Subclasses will typically only need to override this if they
  362. * wish to install additional listeners on the
  363. * <code>JFormattedTextField</code>.
  364. * <p>
  365. * If there is a <code>ParseException</code> in converting the
  366. * current value to a String, this will set the text to an empty
  367. * String, and mark the <code>JFormattedTextField</code> as being
  368. * in an invalid state.
  369. * <p>
  370. * While this is a public method, this is typically only useful
  371. * for subclassers of <code>JFormattedTextField</code>.
  372. * <code>JFormattedTextField</code> will invoke this method at
  373. * the appropriate times when the value changes, or its internal
  374. * state changes.
  375. *
  376. * @param ftf JFormattedTextField to format for, may be null indicating
  377. * uninstall from current JFormattedTextField.
  378. */
  379. public void install(JFormattedTextField ftf) {
  380. super.install(ftf);
  381. // valueToString doesn't throw, but stringToValue does, need to
  382. // update the editValid state appropriately
  383. if (ftf != null) {
  384. Object value = ftf.getValue();
  385. try {
  386. stringToValue(valueToString(value));
  387. } catch (ParseException pe) {
  388. setEditValid(false);
  389. }
  390. }
  391. }
  392. /**
  393. * Actual <code>stringToValue</code> implementation.
  394. * If <code>completeMatch</code> is true, the value must exactly match
  395. * the mask, on the other hand if <code>completeMatch</code> is false
  396. * the string must match the mask or the placeholder string.
  397. */
  398. private Object stringToValue(String value, boolean completeMatch) throws
  399. ParseException {
  400. int errorOffset = -1;
  401. if ((errorOffset = getInvalidOffset(value, completeMatch)) == -1) {
  402. if (!getValueContainsLiteralCharacters()) {
  403. value = stripLiteralChars(value);
  404. }
  405. return super.stringToValue(value);
  406. }
  407. throw new ParseException("stringToValue passed invalid value",
  408. errorOffset);
  409. }
  410. /**
  411. * Returns -1 if the passed in string is valid, otherwise the index of
  412. * the first bogus character is returned.
  413. */
  414. private int getInvalidOffset(String string, boolean completeMatch) {
  415. int iLength = string.length();
  416. if (iLength != getMaxLength()) {
  417. // trivially false
  418. return iLength;
  419. }
  420. for (int counter = 0, max = string.length(); counter < max; counter++){
  421. char aChar = string.charAt(counter);
  422. if (!isValidCharacter(counter, aChar) &&
  423. (completeMatch || !isPlaceholder(counter, aChar))) {
  424. return counter;
  425. }
  426. }
  427. return -1;
  428. }
  429. /**
  430. * Invokes <code>append</code> on the mask characters in
  431. * <code>mask</code>.
  432. */
  433. private void append(StringBuffer result, String value, int[] index,
  434. String placeholder, MaskCharacter[] mask)
  435. throws ParseException {
  436. for (int counter = 0, maxCounter = mask.length;
  437. counter < maxCounter; counter++) {
  438. mask[counter].append(result, value, index, placeholder);
  439. }
  440. }
  441. /**
  442. * Updates the internal representation of the mask.
  443. */
  444. private void updateInternalMask() throws ParseException {
  445. String mask = getMask();
  446. ArrayList fixed = new ArrayList();
  447. ArrayList temp = fixed;
  448. if (mask != null) {
  449. for (int counter = 0, maxCounter = mask.length();
  450. counter < maxCounter; counter++) {
  451. char maskChar = mask.charAt(counter);
  452. switch (maskChar) {
  453. case DIGIT_KEY:
  454. temp.add(new DigitMaskCharacter());
  455. break;
  456. case LITERAL_KEY:
  457. if (++counter < maxCounter) {
  458. maskChar = mask.charAt(counter);
  459. temp.add(new LiteralCharacter(maskChar));
  460. }
  461. // else: Could actually throw if else
  462. break;
  463. case UPPERCASE_KEY:
  464. temp.add(new UpperCaseCharacter());
  465. break;
  466. case LOWERCASE_KEY:
  467. temp.add(new LowerCaseCharacter());
  468. break;
  469. case ALPHA_NUMERIC_KEY:
  470. temp.add(new AlphaNumericCharacter());
  471. break;
  472. case CHARACTER_KEY:
  473. temp.add(new CharCharacter());
  474. break;
  475. case ANYTHING_KEY:
  476. temp.add(new MaskCharacter());
  477. break;
  478. case HEX_KEY:
  479. temp.add(new HexCharacter());
  480. break;
  481. default:
  482. temp.add(new LiteralCharacter(maskChar));
  483. break;
  484. }
  485. }
  486. }
  487. if (fixed.size() == 0) {
  488. maskChars = EmptyMaskChars;
  489. }
  490. else {
  491. maskChars = new MaskCharacter[fixed.size()];
  492. fixed.toArray(maskChars);
  493. }
  494. }
  495. /**
  496. * Returns the MaskCharacter at the specified location.
  497. */
  498. private MaskCharacter getMaskCharacter(int index) {
  499. if (index >= maskChars.length) {
  500. return null;
  501. }
  502. return maskChars[index];
  503. }
  504. /**
  505. * Returns true if the placeholder character matches aChar.
  506. */
  507. private boolean isPlaceholder(int index, char aChar) {
  508. return (getPlaceholderCharacter() == aChar);
  509. }
  510. /**
  511. * Returns true if the passed in character matches the mask at the
  512. * specified location.
  513. */
  514. private boolean isValidCharacter(int index, char aChar) {
  515. return getMaskCharacter(index).isValidCharacter(aChar);
  516. }
  517. /**
  518. * Returns true if the character at the specified location is a literal,
  519. * that is it can not be edited.
  520. */
  521. private boolean isLiteral(int index) {
  522. return getMaskCharacter(index).isLiteral();
  523. }
  524. /**
  525. * Returns the maximum length the text can be.
  526. */
  527. private int getMaxLength() {
  528. return maskChars.length;
  529. }
  530. /**
  531. * Returns the literal character at the specified location.
  532. */
  533. private char getLiteral(int index) {
  534. return getMaskCharacter(index).getChar((char)0);
  535. }
  536. /**
  537. * Returns the character to insert at the specified location based on
  538. * the passed in character. This provides a way to map certain sets
  539. * of characters to alternative values (lowercase to
  540. * uppercase...).
  541. */
  542. private char getCharacter(int index, char aChar) {
  543. return getMaskCharacter(index).getChar(aChar);
  544. }
  545. /**
  546. * Removes the literal characters from the passed in string.
  547. */
  548. private String stripLiteralChars(String string) {
  549. StringBuffer sb = null;
  550. int last = 0;
  551. for (int counter = 0, max = string.length(); counter < max; counter++){
  552. if (isLiteral(counter)) {
  553. if (sb == null) {
  554. sb = new StringBuffer();
  555. if (counter > 0) {
  556. sb.append(string.substring(0, counter));
  557. }
  558. last = counter + 1;
  559. }
  560. else if (last != counter) {
  561. sb.append(string.substring(last, counter));
  562. }
  563. last = counter + 1;
  564. }
  565. }
  566. if (sb == null) {
  567. // Assume the mask isn't all literals.
  568. return string;
  569. }
  570. else if (last != string.length()) {
  571. if (sb == null) {
  572. return string.substring(last);
  573. }
  574. sb.append(string.substring(last));
  575. }
  576. return sb.toString();
  577. }
  578. /**
  579. * Subclassed to update the internal representation of the mask after
  580. * the default read operation has completed.
  581. */
  582. private void readObject(ObjectInputStream s)
  583. throws IOException, ClassNotFoundException {
  584. s.defaultReadObject();
  585. try {
  586. updateInternalMask();
  587. } catch (ParseException pe) {
  588. // assert();
  589. }
  590. }
  591. /**
  592. * Returns true if the MaskFormatter allows invalid, or
  593. * the offset is less than the max length and the character at
  594. * <code>offset</code> is a literal.
  595. */
  596. boolean isNavigatable(int offset) {
  597. if (!getAllowsInvalid()) {
  598. return (offset < getMaxLength() && !isLiteral(offset));
  599. }
  600. return true;
  601. }
  602. /*
  603. * Returns true if the operation described by <code>rh</code> will
  604. * result in a legal edit. This may set the <code>value</code>
  605. * field of <code>rh</code>.
  606. * <p>
  607. * This is overriden to return true for a partial match.
  608. */
  609. boolean isValidEdit(ReplaceHolder rh) {
  610. if (!getAllowsInvalid()) {
  611. String newString = getReplaceString(rh.offset, rh.length, rh.text);
  612. try {
  613. rh.value = stringToValue(newString, false);
  614. return true;
  615. } catch (ParseException pe) {
  616. return false;
  617. }
  618. }
  619. return true;
  620. }
  621. /**
  622. * This method does the following (assuming !getAllowsInvalid()):
  623. * iterate over the max of the deleted region or the text length, for
  624. * each character:
  625. * <ol>
  626. * <li>If it is valid (matches the mask at the particular position, or
  627. * matches the literal character at the position), allow it
  628. * <li>Else if the position identifies a literal character, add it. This
  629. * allows for the user to paste in text that may/may not contain
  630. * the literals. For example, in pasing in 5551212 into ###-####
  631. * when the 1 is evaluated it is illegal (by the first test), but there
  632. * is a literal at this position (-), so it is used. NOTE: This has
  633. * a problem that you can't tell (without looking ahead) if you should
  634. * eat literals in the text. For example, if you paste '555' into
  635. * #5##, should it result in '5555' or '555 '? The current code will
  636. * result in the latter, which feels a little better as selecting
  637. * text than pasting will always result in the same thing.
  638. * <li>Else if at the end of the inserted text, the replace the item with
  639. * the placeholder
  640. * <li>Otherwise the insert is bogus and false is returned.
  641. * </ol>
  642. */
  643. boolean canReplace(ReplaceHolder rh) {
  644. // This method is rather long, but much of the burden is in
  645. // maintaining a String and swapping to a StringBuffer only if
  646. // absolutely necessary.
  647. if (!getAllowsInvalid()) {
  648. StringBuffer replace = null;
  649. String text = rh.text;
  650. int tl = (text != null) ? text.length() : 0;
  651. if (tl == 0 && rh.length == 1 && getFormattedTextField().
  652. getSelectionStart() != rh.offset) {
  653. // Backspace, adjust to actually delete next non-literal.
  654. while (rh.offset > 0 && isLiteral(rh.offset)) {
  655. rh.offset--;
  656. }
  657. }
  658. int max = Math.min(getMaxLength() - rh.offset,
  659. Math.max(tl, rh.length));
  660. for (int counter = 0, textIndex = 0; counter < max; counter++) {
  661. if (textIndex < tl && isValidCharacter(rh.offset + counter,
  662. text.charAt(textIndex))) {
  663. char aChar = text.charAt(textIndex);
  664. if (aChar != getCharacter(rh.offset + counter, aChar)) {
  665. if (replace == null) {
  666. replace = new StringBuffer();
  667. if (textIndex > 0) {
  668. replace.append(text.substring(0, textIndex));
  669. }
  670. }
  671. }
  672. if (replace != null) {
  673. replace.append(getCharacter(rh.offset + counter,
  674. aChar));
  675. }
  676. textIndex++;
  677. }
  678. else if (isLiteral(rh.offset + counter)) {
  679. if (replace != null) {
  680. replace.append(getLiteral(rh.offset + counter));
  681. if (textIndex < tl) {
  682. max = Math.min(max + 1, getMaxLength() -
  683. rh.offset);
  684. }
  685. }
  686. else if (textIndex > 0) {
  687. replace = new StringBuffer(max);
  688. replace.append(text.substring(0, textIndex));
  689. replace.append(getLiteral(rh.offset + counter));
  690. if (textIndex < tl) {
  691. // Evaluate the character in text again.
  692. max = Math.min(max + 1, getMaxLength() -
  693. rh.offset);
  694. }
  695. else if (rh.cursorPosition == -1) {
  696. rh.cursorPosition = rh.offset + counter;
  697. }
  698. }
  699. else {
  700. rh.offset++;
  701. rh.length--;
  702. counter--;
  703. max--;
  704. }
  705. }
  706. else if (textIndex >= tl) {
  707. // placeholder
  708. if (replace == null) {
  709. replace = new StringBuffer();
  710. if (text != null) {
  711. replace.append(text);
  712. }
  713. }
  714. replace.append(getPlaceholderCharacter());
  715. if (tl > 0 && rh.cursorPosition == -1) {
  716. rh.cursorPosition = rh.offset + counter;
  717. }
  718. }
  719. else {
  720. // Bogus character.
  721. return false;
  722. }
  723. }
  724. if (replace != null) {
  725. rh.text = replace.toString();
  726. }
  727. else if (text != null && rh.offset + tl > getMaxLength()) {
  728. rh.text = text.substring(0, getMaxLength() - rh.offset);
  729. }
  730. if (getOverwriteMode() && rh.text != null) {
  731. rh.length = rh.text.length();
  732. }
  733. }
  734. return super.canReplace(rh);
  735. }
  736. //
  737. // Interal classes used to represent the mask.
  738. //
  739. private class MaskCharacter {
  740. /**
  741. * Subclasses should override this returning true if the instance
  742. * represents a literal character. The default implementation
  743. * returns false.
  744. */
  745. public boolean isLiteral() {
  746. return false;
  747. }
  748. /**
  749. * Returns true if <code>aChar</code> is a valid reprensentation of
  750. * the receiver. The default implementation returns true if the
  751. * receiver represents a literal character and <code>getChar</code>
  752. * == aChar. Otherwise, this will return true is <code>aChar</code>
  753. * is contained in the valid characters and not contained
  754. * in the invalid characters.
  755. */
  756. public boolean isValidCharacter(char aChar) {
  757. if (isLiteral()) {
  758. return (getChar(aChar) == aChar);
  759. }
  760. aChar = getChar(aChar);
  761. String filter = getValidCharacters();
  762. if (filter != null && filter.indexOf(aChar) == -1) {
  763. return false;
  764. }
  765. filter = getInvalidCharacters();
  766. if (filter != null && filter.indexOf(aChar) != -1) {
  767. return false;
  768. }
  769. return true;
  770. }
  771. /**
  772. * Returns the character to insert for <code>aChar</code>. The
  773. * default implementation returns <code>aChar</code>. Subclasses
  774. * that wish to do some sort of mapping, perhaps lower case to upper
  775. * case should override this and do the necessary mapping.
  776. */
  777. public char getChar(char aChar) {
  778. return aChar;
  779. }
  780. /**
  781. * Appends the necessary character in <code>formatting</code> at
  782. * <code>index</code> to <code>buff</code>.
  783. */
  784. public void append(StringBuffer buff, String formatting, int[] index,
  785. String placeholder)
  786. throws ParseException {
  787. boolean inString = index[0] < formatting.length();
  788. char aChar = inString ? formatting.charAt(index[0]) : 0;
  789. if (isLiteral()) {
  790. buff.append(getChar(aChar));
  791. if (getValueContainsLiteralCharacters()) {
  792. if (inString && aChar != getChar(aChar)) {
  793. throw new ParseException("Invalid character: " +
  794. aChar, index[0]);
  795. }
  796. index[0] = index[0] + 1;
  797. }
  798. }
  799. else if (index[0] >= formatting.length()) {
  800. if (placeholder != null && index[0] < placeholder.length()) {
  801. buff.append(placeholder.charAt(index[0]));
  802. }
  803. else {
  804. buff.append(getPlaceholderCharacter());
  805. }
  806. index[0] = index[0] + 1;
  807. }
  808. else if (isValidCharacter(aChar)) {
  809. buff.append(getChar(aChar));
  810. index[0] = index[0] + 1;
  811. }
  812. else {
  813. throw new ParseException("Invalid character: " + aChar,
  814. index[0]);
  815. }
  816. }
  817. }
  818. /**
  819. * Used to represent a fixed character in the mask.
  820. */
  821. private class LiteralCharacter extends MaskCharacter {
  822. private char fixedChar;
  823. public LiteralCharacter(char fixedChar) {
  824. this.fixedChar = fixedChar;
  825. }
  826. public boolean isLiteral() {
  827. return true;
  828. }
  829. public char getChar(char aChar) {
  830. return fixedChar;
  831. }
  832. }
  833. /**
  834. * Represents a number, uses <code>Character.isDigit</code>.
  835. */
  836. private class DigitMaskCharacter extends MaskCharacter {
  837. public boolean isValidCharacter(char aChar) {
  838. return (Character.isDigit(aChar) &&
  839. super.isValidCharacter(aChar));
  840. }
  841. }
  842. /**
  843. * Represents a character, lower case letters are mapped to upper case
  844. * using <code>Character.toUpperCase</code>.
  845. */
  846. private class UpperCaseCharacter extends MaskCharacter {
  847. public boolean isValidCharacter(char aChar) {
  848. return (Character.isLetter(aChar) &&
  849. super.isValidCharacter(aChar));
  850. }
  851. public char getChar(char aChar) {
  852. return Character.toUpperCase(aChar);
  853. }
  854. }
  855. /**
  856. * Represents a character, upper case letters are mapped to lower case
  857. * using <code>Character.toLowerCase</code>.
  858. */
  859. private class LowerCaseCharacter extends MaskCharacter {
  860. public boolean isValidCharacter(char aChar) {
  861. return (Character.isLetter(aChar) &&
  862. super.isValidCharacter(aChar));
  863. }
  864. public char getChar(char aChar) {
  865. return Character.toLowerCase(aChar);
  866. }
  867. }
  868. /**
  869. * Represents either a character or digit, uses
  870. * <code>Character.isLetterOrDigit</code>.
  871. */
  872. private class AlphaNumericCharacter extends MaskCharacter {
  873. public boolean isValidCharacter(char aChar) {
  874. return (Character.isLetterOrDigit(aChar) &&
  875. super.isValidCharacter(aChar));
  876. }
  877. }
  878. /**
  879. * Represents a letter, uses <code>Character.isLetter</code>.
  880. */
  881. private class CharCharacter extends MaskCharacter {
  882. public boolean isValidCharacter(char aChar) {
  883. return (Character.isLetter(aChar) &&
  884. super.isValidCharacter(aChar));
  885. }
  886. }
  887. /**
  888. * Represents a hex character, 0-9a-fA-F. a-f is mapped to A-F
  889. */
  890. private class HexCharacter extends MaskCharacter {
  891. public boolean isValidCharacter(char aChar) {
  892. return ((aChar == '0' || aChar == '1' ||
  893. aChar == '2' || aChar == '3' ||
  894. aChar == '4' || aChar == '5' ||
  895. aChar == '6' || aChar == '7' ||
  896. aChar == '8' || aChar == '9' ||
  897. aChar == 'a' || aChar == 'A' ||
  898. aChar == 'b' || aChar == 'B' ||
  899. aChar == 'c' || aChar == 'C' ||
  900. aChar == 'd' || aChar == 'D' ||
  901. aChar == 'e' || aChar == 'E' ||
  902. aChar == 'f' || aChar == 'F') &&
  903. super.isValidCharacter(aChar));
  904. }
  905. public char getChar(char aChar) {
  906. if (Character.isDigit(aChar)) {
  907. return aChar;
  908. }
  909. return Character.toUpperCase(aChar);
  910. }
  911. }
  912. }