1 /*
   2  * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javafx.scene.control;
  27 
  28 import com.sun.javafx.scene.control.FormatterAccessor;
  29 import javafx.beans.DefaultProperty;
  30 import javafx.beans.InvalidationListener;
  31 import javafx.beans.Observable;
  32 import javafx.beans.binding.IntegerBinding;
  33 import javafx.beans.binding.StringBinding;
  34 import javafx.beans.property.BooleanProperty;
  35 import javafx.beans.property.ObjectProperty;
  36 import javafx.beans.property.ObjectPropertyBase;
  37 import javafx.beans.property.ReadOnlyBooleanProperty;
  38 import javafx.beans.property.ReadOnlyBooleanWrapper;
  39 import javafx.beans.property.ReadOnlyIntegerProperty;
  40 import javafx.beans.property.ReadOnlyIntegerWrapper;
  41 import javafx.beans.property.ReadOnlyObjectProperty;
  42 import javafx.beans.property.ReadOnlyObjectWrapper;
  43 import javafx.beans.property.ReadOnlyStringProperty;
  44 import javafx.beans.property.ReadOnlyStringWrapper;
  45 import javafx.beans.property.SimpleBooleanProperty;
  46 import javafx.beans.property.SimpleStringProperty;
  47 import javafx.beans.property.StringProperty;
  48 import javafx.beans.value.ChangeListener;
  49 import javafx.beans.value.ObservableStringValue;
  50 import javafx.beans.value.ObservableValue;
  51 import javafx.beans.value.WritableValue;
  52 import javafx.css.CssMetaData;
  53 import javafx.css.FontCssMetaData;
  54 import javafx.css.PseudoClass;
  55 import javafx.css.StyleOrigin;
  56 import javafx.css.Styleable;
  57 import javafx.css.StyleableObjectProperty;
  58 import javafx.css.StyleableProperty;
  59 import javafx.scene.AccessibleAction;
  60 import javafx.scene.AccessibleAttribute;
  61 import javafx.scene.input.Clipboard;
  62 import javafx.scene.input.ClipboardContent;
  63 import javafx.scene.text.Font;
  64 
  65 import java.text.BreakIterator;
  66 import java.util.ArrayList;
  67 import java.util.Collections;
  68 import java.util.List;
  69 
  70 import com.sun.javafx.util.Utils;
  71 import com.sun.javafx.binding.ExpressionHelper;
  72 import javafx.util.StringConverter;
  73 
  74 /**
  75  * Abstract base class for text input controls.
  76  * @since JavaFX 2.0
  77  */
  78 @DefaultProperty("text")
  79 public abstract class TextInputControl extends Control {
  80     /**
  81      * Interface representing a text input's content. Since it is an ObservableStringValue,
  82      * you can also bind to, or observe the content.
  83      * @since JavaFX 2.0
  84      */
  85     protected interface Content extends ObservableStringValue {
  86         /**
  87          * Retrieves a subset of the content.
  88          *
  89          * @param start
  90          * @param end
  91          */
  92         public String get(int start, int end);
  93 
  94         /**
  95          * Inserts a sequence of characters into the content.
  96          *
  97          * @param index
  98          * @param text
  99          * @since JavaFX 2.1
 100          */
 101         public void insert(int index, String text, boolean notifyListeners);
 102 
 103         /**
 104          * Removes a sequence of characters from the content.
 105          *
 106          * @param start
 107          * @param end
 108          * @since JavaFX 2.1
 109          */
 110         public void delete(int start, int end, boolean notifyListeners);
 111 
 112         /**
 113          * Returns the number of characters represented by the content.
 114          */
 115         public int length();
 116     }
 117 
 118     /***************************************************************************
 119      *                                                                         *
 120      * Constructors                                                            *
 121      *                                                                         *
 122      **************************************************************************/
 123 
 124     /**
 125      * Creates a new TextInputControl. The content is an immutable property and
 126      * must be specified (as non-null) at the time of construction.
 127      *
 128      * @param content a non-null implementation of Content.
 129      */
 130     protected TextInputControl(final Content content) {
 131         this.content = content;
 132 
 133         // Add a listener so that whenever the Content is changed, we notify
 134         // listeners of the text property that it is invalid.
 135         content.addListener(observable -> {
 136             if (content.length() > 0) {
 137                 text.textIsNull = false;
 138             }
 139             text.controlContentHasChanged();
 140         });
 141 
 142         // Bind the length to be based on the length of the text property
 143         length.bind(new IntegerBinding() {
 144             { bind(text); }
 145             @Override protected int computeValue() {
 146                 String txt = text.get();
 147                 return txt == null ? 0 : txt.length();
 148             }
 149         });
 150 
 151         // Bind the selected text to be based on the selection and text properties
 152         selectedText.bind(new StringBinding() {
 153             { bind(selection, text); }
 154             @Override protected String computeValue() {
 155                 String txt = text.get();
 156                 IndexRange sel = selection.get();
 157                 if (txt == null || sel == null) return "";
 158 
 159                 int start = sel.getStart();
 160                 int end = sel.getEnd();
 161                 int length = txt.length();
 162                 if (end > start + length) end = length;
 163                 if (start > length-1) start = end = 0;
 164                 return txt.substring(start, end);
 165             }
 166         });
 167 
 168         focusedProperty().addListener((ob, o, n) -> {
 169             if (n) {
 170                 if (getTextFormatter() != null) {
 171                     updateText(getTextFormatter());
 172                 }
 173             } else {
 174                 commitValue();
 175             }
 176         });
 177 
 178         // Specify the default style class
 179         getStyleClass().add("text-input");
 180     }
 181 
 182     /***************************************************************************
 183      *                                                                         *
 184      * Properties                                                              *
 185      *                                                                         *
 186      **************************************************************************/
 187 
 188     /**
 189      * The default font to use for text in the TextInputControl. If the TextInputControl's text is
 190      * rich text then this font may or may not be used depending on the font
 191      * information embedded in the rich text, but in any case where a default
 192      * font is required, this font will be used.
 193      * @since JavaFX 8.0
 194      */
 195     public final ObjectProperty<Font> fontProperty() {
 196         if (font == null) {
 197             font = new StyleableObjectProperty<Font>(Font.getDefault()) {
 198 
 199 
 200                 private boolean fontSetByCss = false;
 201 
 202                 @Override
 203                 public void applyStyle(StyleOrigin newOrigin, Font value) {
 204 
 205                     //
 206                     // RT-20727 - if CSS is setting the font, then make sure invalidate doesn't call impl_reapplyCSS
 207                     //
 208                     try {
 209                         // super.applyStyle calls set which might throw if value is bound.
 210                         // Have to make sure fontSetByCss is reset.
 211                         fontSetByCss = true;
 212                         super.applyStyle(newOrigin, value);
 213                     } catch(Exception e) {
 214                         throw e;
 215                     } finally {
 216                         fontSetByCss = false;
 217                     }
 218 
 219                 }
 220 
 221 
 222                 @Override
 223                 public void set(Font value) {
 224                     final Font oldValue = get();
 225                     if (value == null ? oldValue == null : value.equals(oldValue)) {
 226                         return;
 227                     }
 228                     super.set(value);
 229                 }
 230 
 231                 @Override
 232                 protected void invalidated() {
 233                     // RT-20727 - if font is changed by calling setFont, then
 234                     // css might need to be reapplied since font size affects
 235                     // calculated values for styles with relative values
 236                     if(fontSetByCss == false) {
 237                         TextInputControl.this.impl_reapplyCSS();
 238                     }
 239                 }
 240 
 241                 @Override
 242                 public CssMetaData<TextInputControl,Font> getCssMetaData() {
 243                     return StyleableProperties.FONT;
 244                 }
 245 
 246                 @Override
 247                 public Object getBean() {
 248                     return TextInputControl.this;
 249                 }
 250 
 251                 @Override
 252                 public String getName() {
 253                     return "font";
 254                 }
 255             };
 256         }
 257         return font;
 258     }
 259 
 260     private ObjectProperty<Font> font;
 261     public final void setFont(Font value) { fontProperty().setValue(value); }
 262     public final Font getFont() { return font == null ? Font.getDefault() : font.getValue(); }
 263 
 264     /**
 265      * The prompt text to display in the {@code TextInputControl}, or
 266      * <tt>null</tt> if no prompt text is displayed.
 267      * @since JavaFX 2.2
 268      */
 269     private StringProperty promptText = new SimpleStringProperty(this, "promptText", "") {
 270         @Override protected void invalidated() {
 271             // Strip out newlines
 272             String txt = get();
 273             if (txt != null && txt.contains("\n")) {
 274                 txt = txt.replace("\n", "");
 275                 set(txt);
 276             }
 277         }
 278     };
 279     public final StringProperty promptTextProperty() { return promptText; }
 280     public final String getPromptText() { return promptText.get(); }
 281     public final void setPromptText(String value) { promptText.set(value); }
 282 
 283 
 284     /**
 285      * The property contains currently attached {@link TextFormatter}.
 286      * Since the value is part of the {@code Formatter}, changing the TextFormatter will update the text based on the new textFormatter.
 287      *
 288      * @defaultValue null
 289      * @since JavaFX 8u40
 290      */
 291     private final ObjectProperty<TextFormatter<?>> textFormatter = new ObjectPropertyBase<TextFormatter<?>>() {
 292 
 293         private TextFormatter<?> oldFormatter = null;
 294 
 295         @Override
 296         public Object getBean() {
 297             return TextInputControl.this;
 298         }
 299 
 300         @Override
 301         public String getName() {
 302             return "textFormatter";
 303         }
 304 
 305         @Override
 306         protected void invalidated() {
 307             final TextFormatter<?> formatter = get();
 308             try {
 309                 if (formatter != null) {
 310                     try {
 311                         formatter.bindToControl(f -> updateText(f));
 312                     } catch (IllegalStateException e) {
 313                         if (isBound()) {
 314                             unbind();
 315                         }
 316                         set(null);
 317                         throw e;
 318                     }
 319                     if (!isFocused()) {
 320                         updateText(get());
 321                     }
 322                 }
 323 
 324                 if (oldFormatter != null) {
 325                     oldFormatter.unbindFromControl();
 326                 }
 327             } finally {
 328                 oldFormatter = formatter;
 329             }
 330         }
 331     };
 332     public final ObjectProperty<TextFormatter<?>> textFormatterProperty() { return textFormatter; }
 333     public final TextFormatter<?> getTextFormatter() { return textFormatter.get(); }
 334     public final void setTextFormatter(TextFormatter<?> value) { textFormatter.set(value); }
 335 
 336     private final Content content;
 337     /**
 338      * Returns the text input's content model.
 339      */
 340     protected final Content getContent() {
 341         return content;
 342     }
 343 
 344     /**
 345      * The textual content of this TextInputControl.
 346      */
 347     private TextProperty text = new TextProperty();
 348     public final String getText() { return text.get(); }
 349     public final void setText(String value) { text.set(value); }
 350     public final StringProperty textProperty() { return text; }
 351 
 352     /**
 353      * The number of characters in the text input.
 354      */
 355     private ReadOnlyIntegerWrapper length = new ReadOnlyIntegerWrapper(this, "length");
 356     public final int getLength() { return length.get(); }
 357     public final ReadOnlyIntegerProperty lengthProperty() { return length.getReadOnlyProperty(); }
 358 
 359     /**
 360      * Indicates whether this TextInputControl can be edited by the user.
 361      */
 362     private BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) {
 363         @Override protected void invalidated() {
 364             pseudoClassStateChanged(PSEUDO_CLASS_READONLY, ! get());
 365         }
 366     };
 367     public final boolean isEditable() { return editable.getValue(); }
 368     public final void setEditable(boolean value) { editable.setValue(value); }
 369     public final BooleanProperty editableProperty() { return editable; }
 370 
 371     /**
 372      * The current selection.
 373      */
 374     private ReadOnlyObjectWrapper<IndexRange> selection = new ReadOnlyObjectWrapper<IndexRange>(this, "selection", new IndexRange(0, 0));
 375     public final IndexRange getSelection() { return selection.getValue(); }
 376     public final ReadOnlyObjectProperty<IndexRange> selectionProperty() { return selection.getReadOnlyProperty(); }
 377 
 378     /**
 379      * Defines the characters in the TextInputControl which are selected
 380      */
 381     private ReadOnlyStringWrapper selectedText = new ReadOnlyStringWrapper(this, "selectedText");
 382     public final String getSelectedText() { return selectedText.get(); }
 383     public final ReadOnlyStringProperty selectedTextProperty() { return selectedText.getReadOnlyProperty(); }
 384 
 385     /**
 386      * The <code>anchor</code> of the text selection.
 387      * The <code>anchor</code> and <code>caretPosition</code> make up the selection
 388      * range. Selection must always be specified in terms of begin &lt;= end, but
 389      * <code>anchor</code> may be less than, equal to, or greater than the
 390      * <code>caretPosition</code>. Depending on how the user selects text,
 391      * the anchor might represent the lower or upper bound of the selection.
 392      */
 393     private ReadOnlyIntegerWrapper anchor = new ReadOnlyIntegerWrapper(this, "anchor", 0);
 394     public final int getAnchor() { return anchor.get(); }
 395     public final ReadOnlyIntegerProperty anchorProperty() { return anchor.getReadOnlyProperty(); }
 396 
 397     /**
 398      * The current position of the caret within the text.
 399      * The <code>anchor</code> and <code>caretPosition</code> make up the selection
 400      * range. Selection must always be specified in terms of begin &lt;= end, but
 401      * <code>anchor</code> may be less than, equal to, or greater than the
 402      * <code>caretPosition</code>. Depending on how the user selects text,
 403      * the caretPosition might represent the lower or upper bound of the selection.
 404      */
 405     private ReadOnlyIntegerWrapper caretPosition = new ReadOnlyIntegerWrapper(this, "caretPosition", 0);
 406     public final int getCaretPosition() { return caretPosition.get(); }
 407     public final ReadOnlyIntegerProperty caretPositionProperty() { return caretPosition.getReadOnlyProperty(); }
 408 
 409     private UndoRedoChange undoChangeHead = new UndoRedoChange();
 410     private UndoRedoChange undoChange = undoChangeHead;
 411     private boolean createNewUndoRecord = false;
 412 
 413     /**
 414      * The property describes if it's currently possible to undo the latest change of the content that was done.
 415      * @defaultValue false
 416      * @since JavaFX 8u40
 417      */
 418     private final ReadOnlyBooleanWrapper undoable = new ReadOnlyBooleanWrapper(this, "undoable", false);
 419     public final boolean isUndoable() { return undoable.get(); }
 420     public final ReadOnlyBooleanProperty undoableProperty() { return undoable.getReadOnlyProperty(); }
 421 
 422 
 423     /**
 424      * The property describes if it's currently possible to redo the latest change of the content that was undone.
 425      * @defaultValue false
 426      * @since JavaFX 8u40
 427      */
 428     private final ReadOnlyBooleanWrapper redoable = new ReadOnlyBooleanWrapper(this, "redoable", false);
 429     public final boolean isRedoable() { return redoable.get(); }
 430     public final ReadOnlyBooleanProperty redoableProperty() { return redoable.getReadOnlyProperty(); }
 431 
 432     /***************************************************************************
 433      *                                                                         *
 434      * Methods                                                                 *
 435      *                                                                         *
 436      **************************************************************************/
 437 
 438     /**
 439      * Returns a subset of the text input's content.
 440      *
 441      * @param start must be a value between 0 and end - 1.
 442      * @param end must be less than or equal to the length
 443      */
 444     public String getText(int start, int end) {
 445         if (start > end) {
 446             throw new IllegalArgumentException("The start must be <= the end");
 447         }
 448 
 449         if (start < 0
 450             || end > getLength()) {
 451             throw new IndexOutOfBoundsException();
 452         }
 453 
 454         return getContent().get(start, end);
 455     }
 456 
 457     /**
 458      * Appends a sequence of characters to the content.
 459      *
 460      * @param text a non null String
 461      */
 462     public void appendText(String text) {
 463         insertText(getLength(), text);
 464     }
 465 
 466     /**
 467      * Inserts a sequence of characters into the content.
 468      *
 469      * @param index The location to insert the text.
 470      * @param text The text to insert.
 471      */
 472     public void insertText(int index, String text) {
 473         replaceText(index, index, text);
 474     }
 475 
 476     /**
 477      * Removes a range of characters from the content.
 478      *
 479      * @param range The range of text to delete. The range object must not be null.
 480      *
 481      * @see #deleteText(int, int)
 482      */
 483     public void deleteText(IndexRange range) {
 484         replaceText(range, "");
 485     }
 486 
 487     /**
 488      * Removes a range of characters from the content.
 489      *
 490      * @param start The starting index in the range, inclusive. This must be &gt;= 0 and &lt; the end.
 491      * @param end The ending index in the range, exclusive. This is one-past the last character to
 492      *            delete (consistent with the String manipulation methods). This must be &gt; the start,
 493      *            and &lt;= the length of the text.
 494      */
 495     public void deleteText(int start, int end) {
 496         replaceText(start, end, "");
 497     }
 498 
 499     /**
 500      * Replaces a range of characters with the given text.
 501      *
 502      * @param range The range of text to replace. The range object must not be null.
 503      * @param text The text that is to replace the range. This must not be null.
 504      *
 505      * @see #replaceText(int, int, String)
 506      */
 507     public void replaceText(IndexRange range, String text) {
 508         final int start = range.getStart();
 509         final int end = start + range.getLength();
 510         replaceText(start, end, text);
 511     }
 512 
 513     /**
 514      * Replaces a range of characters with the given text.
 515      *
 516      * @param start The starting index in the range, inclusive. This must be &gt;= 0 and &lt; the end.
 517      * @param end The ending index in the range, exclusive. This is one-past the last character to
 518      *            delete (consistent with the String manipulation methods). This must be &gt; the start,
 519      *            and &lt;= the length of the text.
 520      * @param text The text that is to replace the range. This must not be null.
 521      */
 522     public void replaceText(final int start, final int end, final String text) {
 523         if (start > end) {
 524             throw new IllegalArgumentException();
 525         }
 526 
 527         if (text == null) {
 528             throw new NullPointerException();
 529         }
 530 
 531         if (start < 0
 532             || end > getLength()) {
 533             throw new IndexOutOfBoundsException();
 534         }
 535 
 536         if (!this.text.isBound()) {
 537             final int oldLength = getLength();
 538             TextFormatter<?> formatter = getTextFormatter();
 539             TextFormatter.Change change = new TextFormatter.Change(this, getFormatterAccessor(), start, end, text);
 540             if (formatter != null && formatter.getFilter() != null) {
 541                 change = formatter.getFilter().apply(change);
 542                 if (change == null) {
 543                     return;
 544                 }
 545             }
 546 
 547             // Update the content
 548             updateContent(change, oldLength == 0);
 549 
 550         }
 551     }
 552 
 553     private void updateContent(TextFormatter.Change change, boolean forceNewUndoRecord) {
 554         final boolean nonEmptySelection = getSelection().getLength() > 0;
 555         String oldText = getText(change.start, change.end);
 556         int adjustmentAmount = replaceText(change.start, change.end, change.text, change.getAnchor(), change.getCaretPosition());
 557 
 558         // If you select some stuff and type anything, then we need to
 559         // create an undo record. If the range is a single character and
 560         // is right next to the index of the last undo record end index, then
 561         // we don't need to create a new undo record. In all other cases
 562         // we do.
 563         int endOfUndoChange = undoChange == undoChangeHead ? -1 : undoChange.start + undoChange.newText.length();
 564         String newText = getText(change.start, change.start + change.text.length() - adjustmentAmount);
 565         if (createNewUndoRecord || nonEmptySelection || endOfUndoChange == -1 || forceNewUndoRecord ||
 566                 (endOfUndoChange != change.start && endOfUndoChange != change.end) || change.start - change.end > 1) {
 567             undoChange = undoChange.add(change.start, oldText, newText);
 568         } else if (change.start != change.end && change.text.isEmpty()) {
 569             // I know I am deleting, and am located at the end of the range of the current undo record
 570             if (undoChange.newText.length() > 0) {
 571                 undoChange.newText = undoChange.newText.substring(0, change.start - undoChange.start);
 572                 if (undoChange.newText.isEmpty()) {
 573                     // throw away this undo change record
 574                     undoChange = undoChange.discard();
 575                 }
 576             } else {
 577                 if (change.start == endOfUndoChange) {
 578                     undoChange.oldText += oldText;
 579                 } else { // end == endOfUndoChange
 580                     undoChange.oldText = oldText + undoChange.oldText;
 581                     undoChange.start--;
 582                 }
 583             }
 584         } else {
 585             // I know I am adding, and am located at the end of the range of the current undo record
 586             undoChange.newText += newText;
 587         }
 588         updateUndoRedoState();
 589     }
 590 
 591     /**
 592      * Transfers the currently selected range in the text to the clipboard,
 593      * removing the current selection.
 594      */
 595     public void cut() {
 596         copy();
 597         IndexRange selection = getSelection();
 598         deleteText(selection.getStart(), selection.getEnd());
 599     }
 600 
 601     /**
 602      * Transfers the currently selected range in the text to the clipboard,
 603      * leaving the current selection.
 604      */
 605      public void copy() {
 606         final String selectedText = getSelectedText();
 607         if (selectedText.length() > 0) {
 608             final ClipboardContent content = new ClipboardContent();
 609             content.putString(selectedText);
 610             Clipboard.getSystemClipboard().setContent(content);
 611         }
 612     }
 613 
 614     /**
 615      * Transfers the contents in the clipboard into this text,
 616      * replacing the current selection.  If there is no selection, the contents
 617      * in the clipboard is inserted at the current caret position.
 618      */
 619     public void paste() {
 620         final Clipboard clipboard = Clipboard.getSystemClipboard();
 621         if (clipboard.hasString()) {
 622             final String text = clipboard.getString();
 623             if (text != null) {
 624                 createNewUndoRecord = true;
 625                 try {
 626                     replaceSelection(text);
 627                 } finally {
 628                     createNewUndoRecord = false;
 629                 }
 630             }
 631         }
 632     }
 633 
 634     /**
 635      * Moves the selection backward one char in the text. This may have the
 636      * effect of deselecting, depending on the location of the anchor relative
 637      * to the caretPosition. This function effectively just moves the caretPosition.
 638      */
 639     public void selectBackward() {
 640         if (getCaretPosition() > 0 && getLength() > 0) {
 641             // because the anchor stays put, by moving the caret to the left
 642             // we ensure that a selection is registered and that it is correct
 643             if (charIterator == null) {
 644                 charIterator = BreakIterator.getCharacterInstance();
 645             }
 646             charIterator.setText(getText());
 647             selectRange(getAnchor(), charIterator.preceding(getCaretPosition()));
 648         }
 649     }
 650 
 651     /**
 652      * Moves the selection forward one char in the text. This may have the
 653      * effect of deselecting, depending on the location of the anchor relative
 654      * to the caretPosition. This function effectively just moves the caret forward.
 655      */
 656     public void selectForward() {
 657         final int textLength = getLength();
 658         if (textLength > 0 && getCaretPosition() < textLength) {
 659             if (charIterator == null) {
 660                 charIterator = BreakIterator.getCharacterInstance();
 661             }
 662             charIterator.setText(getText());
 663             selectRange(getAnchor(), charIterator.following(getCaretPosition()));
 664         }
 665     }
 666 
 667     /**
 668      * The break iterator instances for navigation over words and complex characters.
 669      */
 670     private BreakIterator charIterator;
 671     private BreakIterator wordIterator;
 672 
 673     /**
 674      * Moves the caret to the beginning of previous word. This function
 675      * also has the effect of clearing the selection.
 676      */
 677     public void previousWord() {
 678         previousWord(false);
 679     }
 680 
 681     /**
 682      * Moves the caret to the beginning of next word. This function
 683      * also has the effect of clearing the selection.
 684      */
 685     public void nextWord() {
 686         nextWord(false);
 687     }
 688 
 689     /**
 690      * Moves the caret to the end of the next word. This function
 691      * also has the effect of clearing the selection.
 692      */
 693     public void endOfNextWord() {
 694         endOfNextWord(false);
 695     }
 696 
 697     /**
 698      * Moves the caret to the beginning of previous word. This does not cause
 699      * the selection to be cleared. Rather, the anchor stays put and the caretPosition is
 700      * moved to the beginning of previous word.
 701      */
 702     public void selectPreviousWord() {
 703         previousWord(true);
 704     }
 705 
 706     /**
 707      * Moves the caret to the beginning of next word. This does not cause
 708      * the selection to be cleared. Rather, the anchor stays put and the caretPosition is
 709      * moved to the beginning of next word.
 710      */
 711     public void selectNextWord() {
 712         nextWord(true);
 713     }
 714 
 715     /**
 716      * Moves the caret to the end of the next word. This does not cause
 717      * the selection to be cleared.
 718      */
 719     public void selectEndOfNextWord() {
 720         endOfNextWord(true);
 721     }
 722 
 723     private void previousWord(boolean select) {
 724         final int textLength = getLength();
 725         final String text = getText();
 726         if (textLength <= 0) {
 727             return;
 728         }
 729 
 730         if (wordIterator == null) {
 731             wordIterator = BreakIterator.getWordInstance();
 732         }
 733         wordIterator.setText(text);
 734 
 735         int pos = wordIterator.preceding(Utils.clamp(0, getCaretPosition(), textLength));
 736 
 737         // Skip the non-word region, then move/select to the beginning of the word.
 738         while (pos != BreakIterator.DONE &&
 739                !Character.isLetterOrDigit(text.charAt(Utils.clamp(0, pos, textLength-1)))) {
 740             pos = wordIterator.preceding(Utils.clamp(0, pos, textLength));
 741         }
 742 
 743         // move/select
 744         selectRange(select ? getAnchor() : pos, pos);
 745     }
 746 
 747     private void nextWord(boolean select) {
 748         final int textLength = getLength();
 749         final String text = getText();
 750         if (textLength <= 0) {
 751             return;
 752         }
 753 
 754         if (wordIterator == null) {
 755             wordIterator = BreakIterator.getWordInstance();
 756         }
 757         wordIterator.setText(text);
 758 
 759         int last = wordIterator.following(Utils.clamp(0, getCaretPosition(), textLength-1));
 760         int current = wordIterator.next();
 761 
 762         // Skip non-word characters to the beginning of next word, but
 763         // stop at newline. Then move the caret or select a range.
 764         while (current != BreakIterator.DONE) {
 765             for (int p=last; p<=current; p++) {
 766                 char ch = text.charAt(Utils.clamp(0, p, textLength-1));
 767                 if (Character.isLetterOrDigit(ch) || ch == '\n') {
 768                     if (select) {
 769                         selectRange(getAnchor(), p);
 770                     } else {
 771                         selectRange(p, p);
 772                     }
 773                     return;
 774                 }
 775             }
 776             last = current;
 777             current = wordIterator.next();
 778         }
 779 
 780         // move/select to the end
 781         if (select) {
 782             selectRange(getAnchor(), textLength);
 783         } else {
 784             end();
 785         }
 786     }
 787 
 788     private void endOfNextWord(boolean select) {
 789         final int textLength = getLength();
 790         final String text = getText();
 791         if (textLength <= 0) {
 792             return;
 793         }
 794 
 795         if (wordIterator == null) {
 796             wordIterator = BreakIterator.getWordInstance();
 797         }
 798         wordIterator.setText(text);
 799 
 800         int last = wordIterator.following(Utils.clamp(0, getCaretPosition(), textLength));
 801         int current = wordIterator.next();
 802 
 803         // skip the non-word region, then move/select to the end of the word.
 804         while (current != BreakIterator.DONE) {
 805             for (int p=last; p<=current; p++) {
 806                 if (!Character.isLetterOrDigit(text.charAt(Utils.clamp(0, p, textLength-1)))) {
 807                     if (select) {
 808                         selectRange(getAnchor(), p);
 809                     } else {
 810                         selectRange(p, p);
 811                     }
 812                     return;
 813                 }
 814             }
 815             last = current;
 816             current = wordIterator.next();
 817         }
 818 
 819         // move/select to the end
 820         if (select) {
 821             selectRange(getAnchor(), textLength);
 822         } else {
 823             end();
 824         }
 825     }
 826 
 827     /**
 828      * Selects all text in the text input.
 829      */
 830     public void selectAll() {
 831         selectRange(0, getLength());
 832     }
 833 
 834     /**
 835      * Moves the caret to before the first char of the text. This function
 836      * also has the effect of clearing the selection.
 837      */
 838     public void home() {
 839         // user wants to go to start
 840         selectRange(0, 0);
 841     }
 842 
 843     /**
 844      * Moves the caret to after the last char of the text. This function
 845      * also has the effect of clearing the selection.
 846      */
 847     public void end() {
 848         // user wants to go to end
 849         final int textLength = getLength();
 850         if (textLength > 0) {
 851             selectRange(textLength, textLength);
 852         }
 853     }
 854 
 855     /**
 856      * Moves the caret to before the first char of text. This does not cause
 857      * the selection to be cleared. Rather, the anchor stays put and the
 858      * caretPosition is moved to before the first char.
 859      */
 860     public void selectHome() {
 861         selectRange(getAnchor(), 0);
 862     }
 863 
 864     /**
 865      * Moves the caret to after the last char of text. This does not cause
 866      * the selection to be cleared. Rather, the anchor stays put and the
 867      * caretPosition is moved to after the last char.
 868      */
 869     public void selectEnd() {
 870         final int textLength = getLength();
 871         if (textLength > 0) selectRange(getAnchor(), textLength);
 872     }
 873 
 874     /**
 875      * Deletes the character that precedes the current caret position from the
 876      * text if there is no selection, or deletes the selection if there is one.
 877      * This function returns true if the deletion succeeded, false otherwise.
 878      */
 879     public boolean deletePreviousChar() {
 880         boolean failed = true;
 881         if (isEditable() && !isDisabled()) {
 882             final String text = getText();
 883             final int dot = getCaretPosition();
 884             final int mark = getAnchor();
 885             if (dot != mark) {
 886                 // there is a selection of text to remove
 887                 replaceSelection("");
 888                 failed = false;
 889             } else if (dot > 0) {
 890                 // The caret is not at the beginning, so remove some characters.
 891                 // Typically you'd only be removing a single character, but
 892                 // in some cases you must remove two depending on the unicode
 893                 // characters
 894                 // Note: Do not use charIterator here, because we do want to
 895                 // break up clusters when deleting backwards.
 896                 int p = Character.offsetByCodePoints(text, dot, -1);
 897                 deleteText(p, dot);
 898                 failed = false;
 899             }
 900         }
 901         return !failed;
 902     }
 903 
 904     /**
 905      * Deletes the character that follows the current caret position from the
 906      * text if there is no selection, or deletes the selection if there is one.
 907      * This function returns true if the deletion succeeded, false otherwise.
 908      */
 909     public boolean deleteNextChar() {
 910         boolean failed = true;
 911         if (isEditable() && !isDisabled()) {
 912             final String text = getText();
 913             final int dot = getCaretPosition();
 914             final int mark = getAnchor();
 915             if (dot != mark) {
 916                 // there is a selection of text to remove
 917                 replaceSelection("");
 918                 failed = false;
 919             } else if (text.length() > 0 && dot < text.length()) {
 920                 // The caret is not at the end, so remove some characters.
 921                 // Typically you'd only be removing a single character, but
 922                 // in some cases you must remove two depending on the unicode
 923                 // characters
 924                 if (charIterator == null) {
 925                     charIterator = BreakIterator.getCharacterInstance();
 926                 }
 927                 charIterator.setText(text);
 928                 int p = charIterator.following(dot);
 929                 deleteText(dot, p);
 930                 failed = false;
 931             }
 932         }
 933         return !failed;
 934     }
 935 
 936     /**
 937      * Moves the caret position forward. If there is no selection, then the
 938      * caret position is moved one character forward. If there is a selection,
 939      * then the caret position is moved to the end of the selection and
 940      * the selection cleared.
 941      */
 942     public void forward() {
 943         // user has moved caret to the right
 944         final int textLength = getLength();
 945         final int dot = getCaretPosition();
 946         final int mark = getAnchor();
 947         if (dot != mark) {
 948             int pos = Math.max(dot, mark);
 949             selectRange(pos, pos);
 950         } else if (dot < textLength && textLength > 0) {
 951             if (charIterator == null) {
 952                 charIterator = BreakIterator.getCharacterInstance();
 953             }
 954             charIterator.setText(getText());
 955             int pos = charIterator.following(dot);
 956             selectRange(pos, pos);
 957         }
 958         deselect();
 959     }
 960 
 961     /**
 962      * Moves the caret position backward. If there is no selection, then the
 963      * caret position is moved one character backward. If there is a selection,
 964      * then the caret position is moved to the beginning of the selection and
 965      * the selection cleared.
 966      *
 967      * @expert This function is intended to be used by experts, primarily
 968      *         by those implementing new Skins or Behaviors. It is not common
 969      *         for developers or designers to access this function directly.
 970      */
 971     public void backward() {
 972         // user has moved caret to the left
 973         final int textLength = getLength();
 974         final int dot = getCaretPosition();
 975         final int mark = getAnchor();
 976         if (dot != mark) {
 977             int pos = Math.min(dot, mark);
 978             selectRange(pos, pos);
 979         } else if (dot > 0 && textLength > 0) {
 980             if (charIterator == null) {
 981                 charIterator = BreakIterator.getCharacterInstance();
 982             }
 983             charIterator.setText(getText());
 984             int pos = charIterator.preceding(dot);
 985             selectRange(pos, pos);
 986         }
 987         deselect();
 988     }
 989 
 990     /**
 991      * Positions the caret to the position indicated by {@code pos}. This
 992      * function will also clear the selection.
 993      */
 994     public void positionCaret(int pos) {
 995         final int p = Utils.clamp(0, pos, getLength());
 996         selectRange(p, p);
 997     }
 998 
 999     /**
1000      * Positions the caret to the position indicated by {@code pos} and extends
1001      * the selection, if there is one. If there is no selection, then a
1002      * selection is formed where the anchor is at the current caret position
1003      * and the caretPosition is moved to pos.
1004      */
1005     public void selectPositionCaret(int pos) {
1006         selectRange(getAnchor(), Utils.clamp(0, pos, getLength()));
1007     }
1008 
1009     /**
1010      * Positions the anchor and caretPosition explicitly.
1011      */
1012     public void selectRange(int anchor, int caretPosition) {
1013         caretPosition = Utils.clamp(0, caretPosition, getLength());
1014         anchor = Utils.clamp(0, anchor, getLength());
1015 
1016         TextFormatter.Change change = new TextFormatter.Change(this, getFormatterAccessor(), anchor, caretPosition);
1017         TextFormatter<?> formatter = getTextFormatter();
1018         if (formatter != null && formatter.getFilter() != null) {
1019             change = formatter.getFilter().apply(change);
1020             if (change == null) {
1021                 return;
1022             }
1023         }
1024 
1025         updateContent(change, false);
1026     }
1027 
1028     private void doSelectRange(int anchor, int caretPosition) {
1029         this.caretPosition.set(Utils.clamp(0, caretPosition, getLength()));
1030         this.anchor.set(Utils.clamp(0, anchor, getLength()));
1031         this.selection.set(IndexRange.normalize(getAnchor(), getCaretPosition()));
1032         notifyAccessibleAttributeChanged(AccessibleAttribute.SELECTION_START);
1033     }
1034 
1035     /**
1036      * This function will extend the selection to include the specified pos.
1037      * This is different from selectPositionCaret in that it does not simply
1038      * move the caret. Rather, it will reposition the caret and anchor as necessary
1039      * to ensure that pos becomes the new caret and the far other end of the
1040      * selection becomes the anchor.
1041      */
1042     public void extendSelection(int pos) {
1043         final int p = Utils.clamp(0, pos, getLength());
1044         final int dot = getCaretPosition();
1045         final int mark = getAnchor();
1046         int start = Math.min(dot, mark);
1047         int end = Math.max(dot, mark);
1048         if (p < start) {
1049             selectRange(end, p);
1050         } else {
1051             selectRange(start, p);
1052         }
1053     }
1054 
1055     /**
1056      * Clears the text.
1057      */
1058     public void clear() {
1059         deselect();
1060         if (!text.isBound()) {
1061             setText("");
1062         }
1063     }
1064 
1065     /**
1066      * Clears the selection.
1067      */
1068     public void deselect() {
1069         // set the anchor equal to the caret position, which clears the selection
1070         // while also preserving the caret position
1071         selectRange(getCaretPosition(), getCaretPosition());
1072     }
1073 
1074     /**
1075      * Replaces the selection with the given replacement String. If there is
1076      * no selection, then the replacement text is simply inserted at the current
1077      * caret position. If there was a selection, then the selection is cleared
1078      * and the given replacement text inserted.
1079      */
1080     public void replaceSelection(String replacement) {
1081         replaceText(getSelection(), replacement);
1082     }
1083 
1084     /**
1085      * If possible, undoes the last modification. If {@link #isUndoable()} returns
1086      * false, then calling this method has no effect.
1087      * @since JavaFX 8u40
1088      */
1089     public final void undo() {
1090         if (isUndoable()) {
1091             // Apply reverse change here
1092             final int start = undoChange.start;
1093             final String newText = undoChange.newText;
1094             final String oldText = undoChange.oldText;
1095 
1096             if (newText != null) {
1097                 getContent().delete(start, start + newText.length(), oldText.isEmpty());
1098             }
1099 
1100             if (oldText != null) {
1101                 getContent().insert(start, oldText, true);
1102                 doSelectRange(start, start + oldText.length());
1103             } else {
1104                 doSelectRange(start, start + newText.length());
1105             }
1106 
1107             undoChange = undoChange.prev;
1108         }
1109         updateUndoRedoState();
1110     }
1111 
1112     /**
1113      * If possible, redoes the last undone modification. If {@link #isRedoable()} returns
1114      * false, then calling this method has no effect.
1115      * @since JavaFX 8u40
1116      */
1117     public final void redo() {
1118         if (isRedoable()) {
1119             // Apply change here
1120             undoChange = undoChange.next;
1121             final int start = undoChange.start;
1122             final String newText = undoChange.newText;
1123             final String oldText = undoChange.oldText;
1124 
1125             if (oldText != null) {
1126                 getContent().delete(start, start + oldText.length(), newText.isEmpty());
1127             }
1128 
1129             if (newText != null) {
1130                 getContent().insert(start, newText, true);
1131                 doSelectRange(start + newText.length(), start + newText.length());
1132             } else {
1133                 doSelectRange(start, start);
1134             }
1135         }
1136         updateUndoRedoState();
1137         // else beep ?
1138     }
1139 
1140     // Used by TextArea, although there are probably other better ways of
1141     // doing this.
1142     void textUpdated() { }
1143 
1144     private void resetUndoRedoState() {
1145         undoChange = undoChangeHead;
1146         undoChange.next = null;
1147         updateUndoRedoState();
1148     }
1149 
1150     private void updateUndoRedoState() {
1151         undoable.set(undoChange != undoChangeHead);
1152         redoable.set(undoChange.next != null);
1153     }
1154 
1155     private boolean filterAndSet(String value) {
1156         // Send the new value through the textFormatter, if one exists.
1157         TextFormatter<?> formatter = getTextFormatter();
1158         int length = content.length();
1159         if (formatter != null && formatter.getFilter() != null && !text.isBound()) {
1160             TextFormatter.Change change = new TextFormatter.Change(
1161                     TextInputControl.this, getFormatterAccessor(), 0, length, value, 0, 0);
1162             change = formatter.getFilter().apply(change);
1163             if (change == null) {
1164                 return false;
1165             }
1166             replaceText(change.start, change.end, change.text, change.getAnchor(), change.getCaretPosition());
1167         } else {
1168             replaceText(0, length, value, 0, 0);
1169         }
1170         return true;
1171     }
1172 
1173     /**
1174      * This is what is ultimately called by every code path that will update
1175      * the content (except for undo / redo). The input into this method has
1176      * already run through the textFormatter where appropriate.
1177      *
1178      * @param start            The start index into the existing text which
1179      *                         will be replaced by the new value
1180      * @param end              The end index into the existing text which will
1181      *                         be replaced by the new value. As with
1182      *                         String.replace this is a lastIndex+1 value
1183      * @param value            The new text value
1184      * @param anchor           The new selection anchor after the change is made
1185      * @param caretPosition    The new selection caretPosition after the change
1186      *                         is made.
1187      * @return The amount of adjustment made to the end / anchor / caretPosition to
1188      *         accommodate for subsequent filtering (such as the filtering of
1189      *         new lines by the TextField)
1190      */
1191     private int replaceText(int start, int end, String value, int anchor, int caretPosition) {
1192         // RT-16566: Need to take into account stripping of chars into the
1193         // final anchor & caret position
1194         int length = getLength();
1195         int adjustmentAmount = 0;
1196         if (end != start) {
1197             getContent().delete(start, end, value.isEmpty());
1198             length -= (end - start);
1199         }
1200         if (value != null) {
1201             getContent().insert(start, value, true);
1202             adjustmentAmount = value.length() - (getLength() - length);
1203             anchor -= adjustmentAmount;
1204             caretPosition -= adjustmentAmount;
1205         }
1206         doSelectRange(anchor, caretPosition);
1207         return adjustmentAmount;
1208     }
1209 
1210     private <T> void updateText(TextFormatter<T> formatter) {
1211         T value = formatter.getValue();
1212         StringConverter<T> converter = formatter.getValueConverter();
1213         if (converter != null) {
1214             String text = converter.toString(value);
1215             replaceText(0, getLength(), text, text.length(), text.length());
1216         }
1217     }
1218 
1219     /**
1220      * Commit the current text and convert it to a value.
1221      * @since JavaFX 8u40
1222      */
1223     public final void commitValue() {
1224         if (getTextFormatter() != null) {
1225             getTextFormatter().updateValue(getText());
1226         }
1227     }
1228 
1229     /**
1230      * If the field is currently being edited, this call will set text to the last commited value.
1231      * @since JavaFX 8u40
1232      */
1233     public final void cancelEdit() {
1234         if (getTextFormatter() != null) {
1235             updateText(getTextFormatter());
1236         }
1237     }
1238 
1239     private FormatterAccessor accessor;
1240 
1241     private FormatterAccessor getFormatterAccessor() {
1242         if (accessor == null) {
1243             accessor = new TextInputControlFromatterAccessor();
1244         }
1245         return accessor;
1246     }
1247 
1248 
1249     /**
1250      * A little utility method for stripping out unwanted characters.
1251      * 
1252      * @param txt
1253      * @param stripNewlines
1254      * @param stripTabs
1255      * @return The string after having the unwanted characters stripped out.
1256      */
1257     static String filterInput(String txt, boolean stripNewlines, boolean stripTabs) {
1258         // Most of the time, when text is inserted, there are no illegal
1259         // characters. So we'll do a "cheap" check for illegal characters.
1260         // If we find one, we'll do a longer replace algorithm. In the
1261         // case of illegal characters, this may at worst be an O(2n) solution.
1262         // Strip out any characters that are outside the printed range
1263         if (containsInvalidCharacters(txt, stripNewlines, stripTabs)) {
1264             StringBuilder s = new StringBuilder(txt.length());
1265             for (int i=0; i<txt.length(); i++) {
1266                 final char c = txt.charAt(i);
1267                 if (!isInvalidCharacter(c, stripNewlines, stripTabs)) {
1268                     s.append(c);
1269                 }
1270             }
1271             txt = s.toString();
1272         }
1273         return txt;
1274     }
1275 
1276     static boolean containsInvalidCharacters(String txt, boolean newlineIllegal, boolean tabIllegal) {
1277         for (int i=0; i<txt.length(); i++) {
1278             final char c = txt.charAt(i);
1279             if (isInvalidCharacter(c, newlineIllegal, tabIllegal)) return true;
1280         }
1281         return false;
1282     }
1283 
1284     private static boolean isInvalidCharacter(char c, boolean newlineIllegal, boolean tabIllegal) {
1285         if (c == 0x7F) return true;
1286         if (c == 0xA) return newlineIllegal;
1287         if (c == 0x9) return tabIllegal;
1288         if (c < 0x20) return true;
1289         return false;
1290     }
1291 
1292     // It can be bound, in which case we will force it to be an eager
1293     // binding so that we update the content eagerly
1294     // It can be bidirectionally bound, which basically will just work
1295     // If somebody changes the content directly, it will be notified and
1296     // send an invalidation event.
1297     private class TextProperty extends StringProperty {
1298         // This is used only when the property is bound
1299         private ObservableValue<? extends String> observable = null;
1300         // Added to the observable when bound
1301         private InvalidationListener listener = null;
1302         // Used for event handling
1303         private ExpressionHelper<String> helper = null;
1304         // The developer my set the Text property to null. Although
1305         // the Content must be given an empty String, we must still
1306         // treat the value as though it were null, so that a subsequent
1307         // getText() will return null.
1308         private boolean textIsNull = false;
1309 
1310         @Override public String get() {
1311             // Since we force eager binding and content is always up to date,
1312             // we just need to get it from content and not through the binding
1313             return textIsNull ? null : content.get();
1314         }
1315 
1316         @Override public void set(String value) {
1317             if (isBound()) {
1318                 throw new java.lang.RuntimeException("A bound value cannot be set.");
1319             }
1320             doSet(value);
1321             markInvalid();
1322         }
1323 
1324         /**
1325          * Called whenever the content on the control has changed (as determined
1326          * by a listener on the content).
1327          */
1328         private void controlContentHasChanged() {
1329             markInvalid();
1330             notifyAccessibleAttributeChanged(AccessibleAttribute.TEXT);
1331         }
1332 
1333         @Override public void bind(ObservableValue<? extends String> observable) {
1334             if (observable == null) {
1335                 throw new NullPointerException("Cannot bind to null");
1336             }
1337             if (!observable.equals(this.observable)) {
1338                 unbind();
1339                 this.observable = observable;
1340                 if (listener == null) {
1341                     listener = new Listener();
1342                 }
1343                 this.observable.addListener(listener);
1344                 markInvalid();
1345                 doSet(observable.getValue());
1346             }
1347         }
1348 
1349         @Override public void unbind() {
1350             if (observable != null) {
1351                 doSet(observable.getValue());
1352                 observable.removeListener(listener);
1353                 observable = null;
1354             }
1355         }
1356 
1357         @Override public boolean isBound() {
1358             return observable != null;
1359         }
1360 
1361         @Override public void addListener(InvalidationListener listener) {
1362             helper = ExpressionHelper.addListener(helper, this, listener);
1363         }
1364 
1365         @Override public void removeListener(InvalidationListener listener) {
1366             helper = ExpressionHelper.removeListener(helper, listener);
1367         }
1368 
1369         @Override public void addListener(ChangeListener<? super String> listener) {
1370             helper = ExpressionHelper.addListener(helper, this, listener);
1371         }
1372 
1373         @Override public void removeListener(ChangeListener<? super String> listener) {
1374             helper = ExpressionHelper.removeListener(helper, listener);
1375         }
1376 
1377         @Override public Object getBean() {
1378             return TextInputControl.this;
1379         }
1380 
1381         @Override public String getName() {
1382             return "text";
1383         }
1384 
1385         private void fireValueChangedEvent() {
1386             ExpressionHelper.fireValueChangedEvent(helper);
1387         }
1388 
1389         private void markInvalid() {
1390             fireValueChangedEvent();
1391         }
1392 
1393         /**
1394          * doSet is called whenever the setText() method was called directly
1395          * on the TextInputControl, or when the text property was bound,
1396          * unbound, or reacted to a binding invalidation. It is *not* called
1397          * when modifications to the content happened indirectly, such as
1398          * through the replaceText / replaceSelection methods.
1399          *
1400          * @param value The new value
1401          */
1402         private void doSet(String value) {
1403             // Guard against the null value.
1404             textIsNull = value == null;
1405             if (value == null) value = "";
1406 
1407             if (!filterAndSet(value)) return;
1408 
1409             if (getTextFormatter() != null) {
1410                 getTextFormatter().updateValue(getText());
1411             }
1412 
1413             textUpdated();
1414 
1415             // If the programmer has directly manipulated the text property
1416             // or has it bound up, then we will clear out any modifications
1417             // from the undo manager as we must suppose that the control is
1418             // being reused, for example, between forms.
1419             resetUndoRedoState();
1420         }
1421 
1422         private class Listener implements InvalidationListener {
1423             @Override
1424             public void invalidated(Observable valueModel) {
1425                 // We now need to force it to be eagerly recomputed
1426                 // because we need to push these changes to the
1427                 // content model. Because changing the model ends
1428                 // up calling invalidate and markInvalid, the
1429                 // listeners will all be notified.
1430                 doSet(observable.getValue());
1431             }
1432         }
1433     }
1434 
1435     /**
1436      * Used to form a linked-list of Undo / Redo changes. Each UndoRedoChange
1437      * records the old and new text, and the start index. It also has
1438      * the links to the previous and next Changes in the chain. There
1439      * are two special UndoRedoChange objects in this chain representing the
1440      * head and the tail so we can have beforeFirst and afterLast
1441      * behavior as necessary.
1442      */
1443     static class UndoRedoChange {
1444         int start;
1445         String oldText;
1446         String newText;
1447         UndoRedoChange prev;
1448         UndoRedoChange next;
1449 
1450         UndoRedoChange() { }
1451 
1452         public UndoRedoChange add(int start, String oldText, String newText) {
1453             UndoRedoChange c = new UndoRedoChange();
1454             c.start = start;
1455             c.oldText = oldText;
1456             c.newText = newText;
1457             c.prev = this;
1458             next = c;
1459             return c;
1460         }
1461 
1462         public UndoRedoChange discard() {
1463             prev.next = next;
1464             return prev;
1465         }
1466 
1467         // Handy to use when debugging, just put it in undo or redo
1468         // method or replaceText to see what is happening to the undo
1469         // history as it occurs.
1470         void debugPrint() {
1471             UndoRedoChange c = this;
1472             System.out.print("[");
1473             while (c != null) {
1474                 System.out.print(c.toString());
1475                 if (c.next != null) System.out.print(", ");
1476                 c = c.next;
1477             }
1478             System.out.println("]");
1479         }
1480 
1481         @Override public String toString() {
1482             if (oldText == null && newText == null) {
1483                 return "head";
1484             }
1485             if (oldText.isEmpty() && !newText.isEmpty()) {
1486                 return "added '" + newText + "' at index " + start;
1487             } else if (!oldText.isEmpty() && !newText.isEmpty()) {
1488                 return "replaced '" + oldText + "' with '" + newText + "' at index " + start;
1489             } else {
1490                 return "deleted '" + oldText + "' at index " + start;
1491             }
1492         }
1493     }
1494 
1495     /***************************************************************************
1496      *                                                                         *
1497      * Stylesheet Handling                                                     *
1498      *                                                                         *
1499      **************************************************************************/
1500 
1501 
1502     private static final PseudoClass PSEUDO_CLASS_READONLY
1503             = PseudoClass.getPseudoClass("readonly");
1504 
1505     /**
1506      * @treatAsPrivate implementation detail
1507      */
1508     private static class StyleableProperties {
1509         private static final FontCssMetaData<TextInputControl> FONT =
1510             new FontCssMetaData<TextInputControl>("-fx-font", Font.getDefault()) {
1511 
1512             @Override
1513             public boolean isSettable(TextInputControl n) {
1514                 return n.font == null || !n.font.isBound();
1515             }
1516 
1517             @Override
1518             public StyleableProperty<Font> getStyleableProperty(TextInputControl n) {
1519                 return (StyleableProperty<Font>)(WritableValue<Font>)n.fontProperty();
1520             }
1521         };
1522 
1523         private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES;
1524         static {
1525             final List<CssMetaData<? extends Styleable, ?>> styleables =
1526                 new ArrayList<CssMetaData<? extends Styleable, ?>>(Control.getClassCssMetaData());
1527             styleables.add(FONT);
1528             STYLEABLES = Collections.unmodifiableList(styleables);
1529         }
1530     }
1531 
1532     /**
1533      * @return The CssMetaData associated with this class, which may include the
1534      * CssMetaData of its super classes.
1535      * @since JavaFX 8.0
1536      */
1537     public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
1538         return StyleableProperties.STYLEABLES;
1539     }
1540 
1541     /**
1542      * {@inheritDoc}
1543      * @since JavaFX 8.0
1544      */
1545     @Override
1546     public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() {
1547         return getClassCssMetaData();
1548     }
1549 
1550 
1551     /***************************************************************************
1552      *                                                                         *
1553      * Accessibility handling                                                  *
1554      *                                                                         *
1555      **************************************************************************/
1556 
1557     @Override
1558     public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) {
1559         switch (attribute) {
1560             case TEXT: {
1561                 String accText = getAccessibleText();
1562                 if (accText != null && !accText.isEmpty()) return accText;
1563 
1564                 String text = getText();
1565                 if (text == null || text.isEmpty()) {
1566                     text = getPromptText();
1567                 }
1568                 return text;
1569             }
1570             case EDITABLE: return isEditable();
1571             case SELECTION_START: return getSelection().getStart();
1572             case SELECTION_END: return getSelection().getEnd();
1573             case CARET_OFFSET: return getCaretPosition();
1574             case FONT: return getFont();
1575             default: return super.queryAccessibleAttribute(attribute, parameters);
1576         }
1577     }
1578 
1579     @Override
1580     public void executeAccessibleAction(AccessibleAction action, Object... parameters) {
1581         switch (action) {
1582             case SET_TEXT: {
1583                 String value = (String) parameters[0];
1584                 if (value != null) setText(value);
1585             }
1586             case SET_TEXT_SELECTION: {
1587                 Integer start = (Integer) parameters[0];
1588                 Integer end = (Integer) parameters[1];
1589                 if (start != null && end != null) {
1590                     selectRange(start,  end);
1591                 }
1592                 break;
1593             }
1594             default: super.executeAccessibleAction(action, parameters);
1595         }
1596     }
1597 
1598     private class TextInputControlFromatterAccessor implements FormatterAccessor {
1599         @Override
1600         public int getTextLength() {
1601             return TextInputControl.this.getLength();
1602         }
1603 
1604         @Override
1605         public String getText(int begin, int end) {
1606             return TextInputControl.this.getText(begin, end);
1607         }
1608 
1609         @Override
1610         public int getCaret() {
1611             return TextInputControl.this.getCaretPosition();
1612         }
1613 
1614         @Override
1615         public int getAnchor() {
1616             return TextInputControl.this.getAnchor();
1617         }
1618     }
1619 
1620 }