1. /*
  2. * @(#)MaskFormatter.java 1.8 03/01/23
  3. *
  4. * Copyright 2003 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.8 01/23/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 thrown a
  318. * <code>ParseException</code> if the value does not match the current
  319. * mask.
  320. *
  321. * @throws ParseException if there is an error in the conversion
  322. * @param value String to convert
  323. * @return Object representation of text
  324. */
  325. public Object stringToValue(String value) throws ParseException {
  326. return stringToValue(value, true);
  327. }
  328. /**
  329. * Returns a String representation of the Object <code>value</code>
  330. * based on the mask.
  331. *
  332. * @throws ParseException if there is an error in the conversion
  333. * @param value Value to convert
  334. * @return String representation of value
  335. */
  336. public String valueToString(Object value) throws ParseException {
  337. String sValue = (value == null) ? "" : value.toString();
  338. StringBuffer result = new StringBuffer();
  339. String placeholder = getPlaceholder();
  340. int[] valueCounter = { 0 };
  341. append(result, sValue, valueCounter, placeholder, maskChars);
  342. return result.toString();
  343. }
  344. /**
  345. * Installs the <code>DefaultFormatter</code> onto a particular
  346. * <code>JFormattedTextField</code>.
  347. * This will invoke <code>valueToString</code> to convert the
  348. * current value from the <code>JFormattedTextField</code> to
  349. * a String. This will then install the <code>Action</code>s from
  350. * <code>getActions</code>, the <code>DocumentFilter</code>
  351. * returned from <code>getDocumentFilter</code> and the
  352. * <code>NavigationFilter</code> returned from
  353. * <code>getNavigationFilter</code> onto the
  354. * <code>JFormattedTextField</code>.
  355. * <p>
  356. * Subclasses will typically only need to override this if they
  357. * wish to install additional listeners on the
  358. * <code>JFormattedTextField</code>.
  359. * <p>
  360. * If there is a <code>ParseException</code> in converting the
  361. * current value to a String, this will set the text to an empty
  362. * String, and mark the <code>JFormattedTextField</code> as being
  363. * in an invalid state.
  364. * <p>
  365. * While this is a public method, this is typically only useful
  366. * for subclassers of <code>JFormattedTextField</code>.
  367. * <code>JFormattedTextField</code> will invoke this method at
  368. * the appropriate times when the value changes, or its internal
  369. * state changes.
  370. *
  371. * @param ftf JFormattedTextField to format for, may be null indicating
  372. * uninstall from current JFormattedTextField.
  373. */
  374. public void install(JFormattedTextField ftf) {
  375. super.install(ftf);
  376. // valueToString doesn't throw, but stringToValue does, need to
  377. // update the editValid state appropriately
  378. if (ftf != null) {
  379. Object value = ftf.getValue();
  380. try {
  381. stringToValue(valueToString(value));
  382. } catch (ParseException pe) {
  383. setEditValid(false);
  384. }
  385. }
  386. }
  387. /**
  388. * Actual <code>stringToValue</code> implementation.
  389. * If <code>completeMatch</code> is true, the value must exactly match
  390. * the mask, on the other hand if <code>completeMatch</code> is false
  391. * the string must match the mask or the placeholder string.
  392. */
  393. private Object stringToValue(String value, boolean completeMatch) throws
  394. ParseException {
  395. int errorOffset = -1;
  396. if ((errorOffset = getInvalidOffset(value, completeMatch)) == -1) {
  397. if (!getValueContainsLiteralCharacters()) {
  398. value = stripLiteralChars(value);
  399. }
  400. return super.stringToValue(value);
  401. }
  402. throw new ParseException("stringToValue passed invalid value",
  403. errorOffset);
  404. }
  405. /**
  406. * Returns -1 if the passed in string is valid, otherwise the index of
  407. * the first bogus character is returned.
  408. */
  409. private int getInvalidOffset(String string, boolean completeMatch) {
  410. int iLength = string.length();
  411. if (iLength != getMaxLength()) {
  412. // trivially false
  413. return iLength;
  414. }
  415. for (int counter = 0, max = string.length(); counter < max; counter++){
  416. char aChar = string.charAt(counter);
  417. if (!isValidCharacter(counter, aChar) &&
  418. (completeMatch || !isPlaceholder(counter, aChar))) {
  419. return counter;
  420. }
  421. }
  422. return -1;
  423. }
  424. /**
  425. * Invokes <code>append</code> on the mask characters in
  426. * <code>mask</code>.
  427. */
  428. private void append(StringBuffer result, String value, int[] index,
  429. String placeholder, MaskCharacter[] mask)
  430. throws ParseException {
  431. for (int counter = 0, maxCounter = mask.length;
  432. counter < maxCounter; counter++) {
  433. mask[counter].append(result, value, index, placeholder);
  434. }
  435. }
  436. /**
  437. * Updates the internal representation of the mask.
  438. */
  439. private void updateInternalMask() throws ParseException {
  440. String mask = getMask();
  441. ArrayList fixed = new ArrayList();
  442. ArrayList temp = fixed;
  443. if (mask != null) {
  444. for (int counter = 0, maxCounter = mask.length();
  445. counter < maxCounter; counter++) {
  446. char maskChar = mask.charAt(counter);
  447. switch (maskChar) {
  448. case DIGIT_KEY:
  449. temp.add(new DigitMaskCharacter());
  450. break;
  451. case LITERAL_KEY:
  452. if (++counter < maxCounter) {
  453. maskChar = mask.charAt(counter);
  454. temp.add(new LiteralCharacter(maskChar));
  455. }
  456. // else: Could actually throw if else
  457. break;
  458. case UPPERCASE_KEY:
  459. temp.add(new UpperCaseCharacter());
  460. break;
  461. case LOWERCASE_KEY:
  462. temp.add(new LowerCaseCharacter());
  463. break;
  464. case ALPHA_NUMERIC_KEY:
  465. temp.add(new AlphaNumericCharacter());
  466. break;
  467. case CHARACTER_KEY:
  468. temp.add(new CharCharacter());
  469. break;
  470. case ANYTHING_KEY:
  471. temp.add(new MaskCharacter());
  472. break;
  473. case HEX_KEY:
  474. temp.add(new HexCharacter());
  475. break;
  476. default:
  477. temp.add(new LiteralCharacter(maskChar));
  478. break;
  479. }
  480. }
  481. }
  482. if (fixed.size() == 0) {
  483. maskChars = EmptyMaskChars;
  484. }
  485. else {
  486. maskChars = new MaskCharacter[fixed.size()];
  487. fixed.toArray(maskChars);
  488. }
  489. }
  490. /**
  491. * Returns the MaskCharacter at the specified location.
  492. */
  493. private MaskCharacter getMaskCharacter(int index) {
  494. if (index >= maskChars.length) {
  495. return null;
  496. }
  497. return maskChars[index];
  498. }
  499. /**
  500. * Returns true if the placeholder character matches aChar.
  501. */
  502. private boolean isPlaceholder(int index, char aChar) {
  503. return (getPlaceholderCharacter() == aChar);
  504. }
  505. /**
  506. * Returns true if the passed in character matches the mask at the
  507. * specified location.
  508. */
  509. private boolean isValidCharacter(int index, char aChar) {
  510. return getMaskCharacter(index).isValidCharacter(aChar);
  511. }
  512. /**
  513. * Returns true if the character at the specified location is a literal,
  514. * that is it can not be edited.
  515. */
  516. private boolean isLiteral(int index) {
  517. return getMaskCharacter(index).isLiteral();
  518. }
  519. /**
  520. * Returns the maximum length the text can be.
  521. */
  522. private int getMaxLength() {
  523. return maskChars.length;
  524. }
  525. /**
  526. * Returns the literal character at the specified location.
  527. */
  528. private char getLiteral(int index) {
  529. return getMaskCharacter(index).getChar((char)0);
  530. }
  531. /**
  532. * Returns the character to insert at the specified location based on
  533. * the passed in character. This provides a way to map certain sets
  534. * of characters to alternative values (lowercase to
  535. * uppercase...).
  536. */
  537. private char getCharacter(int index, char aChar) {
  538. return getMaskCharacter(index).getChar(aChar);
  539. }
  540. /**
  541. * Removes the literal characters from the passed in string.
  542. */
  543. private String stripLiteralChars(String string) {
  544. StringBuffer sb = null;
  545. int last = 0;
  546. for (int counter = 0, max = string.length(); counter < max; counter++){
  547. if (isLiteral(counter)) {
  548. if (sb == null) {
  549. sb = new StringBuffer();
  550. if (counter > 0) {
  551. sb.append(string.substring(0, counter));
  552. }
  553. last = counter + 1;
  554. }
  555. else if (last != counter) {
  556. sb.append(string.substring(last, counter));
  557. }
  558. last = counter + 1;
  559. }
  560. }
  561. if (sb == null) {
  562. // Assume the mask isn't all literals.
  563. return string;
  564. }
  565. else if (last != string.length()) {
  566. if (sb == null) {
  567. return string.substring(last);
  568. }
  569. sb.append(string.substring(last));
  570. }
  571. return sb.toString();
  572. }
  573. /**
  574. * Subclassed to update the internal representation of the mask after
  575. * the default read operation has completed.
  576. */
  577. private void readObject(ObjectInputStream s)
  578. throws IOException, ClassNotFoundException {
  579. s.defaultReadObject();
  580. try {
  581. updateInternalMask();
  582. } catch (ParseException pe) {
  583. // assert();
  584. }
  585. }
  586. /**
  587. * Returns true if the MaskFormatter allows invalid, or
  588. * the offset is less than the max length and the character at
  589. * <code>offset</code> is a literal.
  590. */
  591. boolean isNavigatable(int offset) {
  592. if (!getAllowsInvalid()) {
  593. return (offset < getMaxLength() && !isLiteral(offset));
  594. }
  595. return true;
  596. }
  597. /*
  598. * Returns true if the operation described by <code>rh</code> will
  599. * result in a legal edit. This may set the <code>value</code>
  600. * field of <code>rh</code>.
  601. * <p>
  602. * This is overriden to return true for a partial match.
  603. */
  604. boolean isValidEdit(ReplaceHolder rh) {
  605. if (!getAllowsInvalid()) {
  606. String newString = getReplaceString(rh.offset, rh.length, rh.text);
  607. try {
  608. rh.value = stringToValue(newString, false);
  609. return true;
  610. } catch (ParseException pe) {
  611. return false;
  612. }
  613. }
  614. return true;
  615. }
  616. /**
  617. * This method does the following (assuming !getAllowsInvalid()):
  618. * iterate over the max of the deleted region or the text length, for
  619. * each character:
  620. * <ol>
  621. * <li>If it is valid (matches the mask at the particular position, or
  622. * matches the literal character at the position), allow it
  623. * <li>Else if the position identifies a literal character, add it. This
  624. * allows for the user to paste in text that may/may not contain
  625. * the literals. For example, in pasing in 5551212 into ###-####
  626. * when the 1 is evaluated it is illegal (by the first test), but there
  627. * is a literal at this position (-), so it is used. NOTE: This has
  628. * a problem that you can't tell (without looking ahead) if you should
  629. * eat literals in the text. For example, if you paste '555' into
  630. * #5##, should it result in '5555' or '555 '? The current code will
  631. * result in the latter, which feels a little better as selecting
  632. * text than pasting will always result in the same thing.
  633. * <li>Else if at the end of the inserted text, the replace the item with
  634. * the placeholder
  635. * <li>Otherwise the insert is bogus and false is returned.
  636. * </ol>
  637. */
  638. boolean canReplace(ReplaceHolder rh) {
  639. // This method is rather long, but much of the burden is in
  640. // maintaining a String and swapping to a StringBuffer only if
  641. // absolutely necessary.
  642. if (!getAllowsInvalid()) {
  643. StringBuffer replace = null;
  644. String text = rh.text;
  645. int tl = (text != null) ? text.length() : 0;
  646. if (tl == 0 && rh.length == 1 && getFormattedTextField().
  647. getSelectionStart() != rh.offset) {
  648. // Backspace, adjust to actually delete next non-literal.
  649. while (rh.offset > 0 && isLiteral(rh.offset)) {
  650. rh.offset--;
  651. }
  652. }
  653. int max = Math.min(getMaxLength() - rh.offset,
  654. Math.max(tl, rh.length));
  655. for (int counter = 0, textIndex = 0; counter < max; counter++) {
  656. if (textIndex < tl && isValidCharacter(rh.offset + counter,
  657. text.charAt(textIndex))) {
  658. char aChar = text.charAt(textIndex);
  659. if (aChar != getCharacter(rh.offset + counter, aChar)) {
  660. if (replace == null) {
  661. replace = new StringBuffer();
  662. if (textIndex > 0) {
  663. replace.append(text.substring(0, textIndex));
  664. }
  665. }
  666. }
  667. if (replace != null) {
  668. replace.append(getCharacter(rh.offset + counter,
  669. aChar));
  670. }
  671. textIndex++;
  672. }
  673. else if (isLiteral(rh.offset + counter)) {
  674. if (replace != null) {
  675. replace.append(getLiteral(rh.offset + counter));
  676. }
  677. else if (textIndex > 0) {
  678. replace = new StringBuffer(max);
  679. replace.append(text.substring(0, textIndex));
  680. replace.append(getLiteral(rh.offset + counter));
  681. if (textIndex < tl) {
  682. // Evaluate the character in text again.
  683. max = Math.min(max + 1, getMaxLength() -
  684. rh.offset);
  685. }
  686. else if (rh.cursorPosition == -1) {
  687. rh.cursorPosition = rh.offset + counter;
  688. }
  689. }
  690. else {
  691. rh.offset++;
  692. rh.length--;
  693. counter--;
  694. max--;
  695. }
  696. }
  697. else if (textIndex >= tl) {
  698. // placeholder
  699. if (replace == null) {
  700. replace = new StringBuffer();
  701. if (text != null) {
  702. replace.append(text);
  703. }
  704. }
  705. replace.append(getPlaceholderCharacter());
  706. if (tl > 0 && rh.cursorPosition == -1) {
  707. rh.cursorPosition = rh.offset + counter;
  708. }
  709. }
  710. else {
  711. // Bogus character.
  712. return false;
  713. }
  714. }
  715. if (replace != null) {
  716. rh.text = replace.toString();
  717. }
  718. else if (text != null && rh.offset + tl > getMaxLength()) {
  719. rh.text = text.substring(0, getMaxLength() - rh.offset);
  720. }
  721. if (getOverwriteMode() && rh.text != null) {
  722. rh.length = rh.text.length();
  723. }
  724. }
  725. return super.canReplace(rh);
  726. }
  727. //
  728. // Interal classes used to represent the mask.
  729. //
  730. private class MaskCharacter {
  731. /**
  732. * Subclasses should override this returning true if the instance
  733. * represents a literal character. The default implementation
  734. * returns false.
  735. */
  736. public boolean isLiteral() {
  737. return false;
  738. }
  739. /**
  740. * Returns true if <code>aChar</code> is a valid reprensentation of
  741. * the receiver. The default implementation returns true if the
  742. * receiver represents a literal character and <code>getChar</code>
  743. * == aChar. Otherwise, this will return true is <code>aChar</code>
  744. * is contained in the valid characters and not contained
  745. * in the invalid characters.
  746. */
  747. public boolean isValidCharacter(char aChar) {
  748. if (isLiteral()) {
  749. return (getChar(aChar) == aChar);
  750. }
  751. aChar = getChar(aChar);
  752. String filter = getValidCharacters();
  753. if (filter != null && filter.indexOf(aChar) == -1) {
  754. return false;
  755. }
  756. filter = getInvalidCharacters();
  757. if (filter != null && filter.indexOf(aChar) != -1) {
  758. return false;
  759. }
  760. return true;
  761. }
  762. /**
  763. * Returns the character to insert for <code>aChar</code>. The
  764. * default implementation returns <code>aChar</code>. Subclasses
  765. * that wish to do some sort of mapping, perhaps lower case to upper
  766. * case should override this and do the necessary mapping.
  767. */
  768. public char getChar(char aChar) {
  769. return aChar;
  770. }
  771. /**
  772. * Appends the necessary character in <code>formatting</code> at
  773. * <code>index</code> to <code>buff</code>.
  774. */
  775. public void append(StringBuffer buff, String formatting, int[] index,
  776. String placeholder)
  777. throws ParseException {
  778. boolean inString = index[0] < formatting.length();
  779. char aChar = inString ? formatting.charAt(index[0]) : 0;
  780. if (isLiteral()) {
  781. buff.append(getChar(aChar));
  782. if (getValueContainsLiteralCharacters()) {
  783. if (inString && aChar != getChar(aChar)) {
  784. throw new ParseException("Invalid character: " +
  785. aChar, index[0]);
  786. }
  787. index[0] = index[0] + 1;
  788. }
  789. }
  790. else if (index[0] >= formatting.length()) {
  791. if (placeholder != null && index[0] < placeholder.length()) {
  792. buff.append(placeholder.charAt(index[0]));
  793. }
  794. else {
  795. buff.append(getPlaceholderCharacter());
  796. }
  797. index[0] = index[0] + 1;
  798. }
  799. else if (isValidCharacter(aChar)) {
  800. buff.append(getChar(aChar));
  801. index[0] = index[0] + 1;
  802. }
  803. else {
  804. throw new ParseException("Invalid character: " + aChar,
  805. index[0]);
  806. }
  807. }
  808. }
  809. /**
  810. * Used to represent a fixed character in the mask.
  811. */
  812. private class LiteralCharacter extends MaskCharacter {
  813. private char fixedChar;
  814. public LiteralCharacter(char fixedChar) {
  815. this.fixedChar = fixedChar;
  816. }
  817. public boolean isLiteral() {
  818. return true;
  819. }
  820. public char getChar(char aChar) {
  821. return fixedChar;
  822. }
  823. }
  824. /**
  825. * Represents a number, uses <code>Character.isDigit</code>.
  826. */
  827. private class DigitMaskCharacter extends MaskCharacter {
  828. public boolean isValidCharacter(char aChar) {
  829. return (Character.isDigit(aChar) &&
  830. super.isValidCharacter(aChar));
  831. }
  832. }
  833. /**
  834. * Represents a character, lower case letters are mapped to upper case
  835. * using <code>Character.toUpperCase</code>.
  836. */
  837. private class UpperCaseCharacter extends MaskCharacter {
  838. public boolean isValidCharacter(char aChar) {
  839. return (Character.isLetter(aChar) &&
  840. super.isValidCharacter(aChar));
  841. }
  842. public char getChar(char aChar) {
  843. return Character.toUpperCase(aChar);
  844. }
  845. }
  846. /**
  847. * Represents a character, upper case letters are mapped to lower case
  848. * using <code>Character.toLowerCase</code>.
  849. */
  850. private class LowerCaseCharacter extends MaskCharacter {
  851. public boolean isValidCharacter(char aChar) {
  852. return (Character.isLetter(aChar) &&
  853. super.isValidCharacter(aChar));
  854. }
  855. public char getChar(char aChar) {
  856. return Character.toLowerCase(aChar);
  857. }
  858. }
  859. /**
  860. * Represents either a character or digit, uses
  861. * <code>Character.isLetterOrDigit</code>.
  862. */
  863. private class AlphaNumericCharacter extends MaskCharacter {
  864. public boolean isValidCharacter(char aChar) {
  865. return (Character.isLetterOrDigit(aChar) &&
  866. super.isValidCharacter(aChar));
  867. }
  868. }
  869. /**
  870. * Represents a letter, uses <code>Character.isLetter</code>.
  871. */
  872. private class CharCharacter extends MaskCharacter {
  873. public boolean isValidCharacter(char aChar) {
  874. return (Character.isLetter(aChar) &&
  875. super.isValidCharacter(aChar));
  876. }
  877. }
  878. /**
  879. * Represents a hex character, 0-9a-fA-F. a-f is mapped to A-F
  880. */
  881. private class HexCharacter extends MaskCharacter {
  882. public boolean isValidCharacter(char aChar) {
  883. return ((aChar == '0' || aChar == '1' ||
  884. aChar == '2' || aChar == '3' ||
  885. aChar == '4' || aChar == '5' ||
  886. aChar == '6' || aChar == '7' ||
  887. aChar == '8' || aChar == '9' ||
  888. aChar == 'a' || aChar == 'A' ||
  889. aChar == 'b' || aChar == 'B' ||
  890. aChar == 'c' || aChar == 'C' ||
  891. aChar == 'd' || aChar == 'D' ||
  892. aChar == 'e' || aChar == 'E' ||
  893. aChar == 'f' || aChar == 'F') &&
  894. super.isValidCharacter(aChar));
  895. }
  896. public char getChar(char aChar) {
  897. if (Character.isDigit(aChar)) {
  898. return aChar;
  899. }
  900. return Character.toUpperCase(aChar);
  901. }
  902. }
  903. }