mellotanica

SearchField.java

Nov 14th, 2016
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 54.33 KB | None | 0 0
  1. package com.mellotanica.game.ui;
  2.  
  3. import com.badlogic.gdx.Gdx;
  4. import com.badlogic.gdx.Input;
  5. import com.badlogic.gdx.graphics.Color;
  6. import com.badlogic.gdx.graphics.g2d.Batch;
  7. import com.badlogic.gdx.graphics.g2d.BitmapFont;
  8. import com.badlogic.gdx.graphics.g2d.GlyphLayout;
  9. import com.badlogic.gdx.math.Interpolation;
  10. import com.badlogic.gdx.math.MathUtils;
  11. import com.badlogic.gdx.math.Vector2;
  12. import com.badlogic.gdx.scenes.scene2d.Actor;
  13. import com.badlogic.gdx.scenes.scene2d.Event;
  14. import com.badlogic.gdx.scenes.scene2d.EventListener;
  15. import com.badlogic.gdx.scenes.scene2d.Group;
  16. import com.badlogic.gdx.scenes.scene2d.InputEvent;
  17. import com.badlogic.gdx.scenes.scene2d.InputListener;
  18. import com.badlogic.gdx.scenes.scene2d.Stage;
  19. import com.badlogic.gdx.scenes.scene2d.Touchable;
  20. import com.badlogic.gdx.scenes.scene2d.ui.List;
  21. import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
  22. import com.badlogic.gdx.scenes.scene2d.ui.Skin;
  23. import com.badlogic.gdx.scenes.scene2d.ui.Widget;
  24. import com.badlogic.gdx.scenes.scene2d.utils.ArraySelection;
  25. import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
  26. import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
  27. import com.badlogic.gdx.scenes.scene2d.utils.Disableable;
  28. import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
  29. import com.badlogic.gdx.scenes.scene2d.utils.UIUtils;
  30. import com.badlogic.gdx.utils.Align;
  31. import com.badlogic.gdx.utils.Array;
  32. import com.badlogic.gdx.utils.Clipboard;
  33. import com.badlogic.gdx.utils.FloatArray;
  34. import com.badlogic.gdx.utils.ObjectSet;
  35. import com.badlogic.gdx.utils.Pool;
  36. import com.badlogic.gdx.utils.Pools;
  37. import com.badlogic.gdx.utils.TimeUtils;
  38. import com.badlogic.gdx.utils.Timer;
  39. import com.mellotanica.game.utils.SelectListener;
  40.  
  41. import static com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeIn;
  42. import static com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeOut;
  43. import static com.badlogic.gdx.scenes.scene2d.actions.Actions.removeActor;
  44. import static com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence;
  45.  
  46. /** A single-line text input field with dropdown menu search engine style.
  47.  * <p>
  48.  * The preferred height of a text field is the height of the {@link SearchFieldStyle#font} and {@link SearchFieldStyle#background}.
  49.  * The preferred width of a text field is 150, a relatively arbitrary size.
  50.  * <p>
  51.  * The text field will copy the currently selected text when ctrl+c is pressed, and paste any text in the clipboard when ctrl+v is
  52.  * pressed. Clipboard functionality is provided via the {@link Clipboard} interface. Currently there are two standard
  53.  * implementations, one for the desktop and one for Android. The Android clipboard is a stub, as copy & pasting on Android is not
  54.  * supported yet.
  55.  * <p>
  56.  * The text field allows you to specify an {@link OnscreenKeyboard} for displaying a softkeyboard and piping all key events
  57.  * generated by the keyboard to the text field. There are two standard implementations, one for the desktop and one for Android.
  58.  * The desktop keyboard is a stub, as a softkeyboard is not needed on the desktop. The Android {@link OnscreenKeyboard}
  59.  * implementation will bring up the default IME.
  60.  * @author mzechner
  61.  * @author Nathan Sweet
  62.  * @author mellotanica */
  63.  
  64. public class SearchField<T> extends Widget implements Disableable {
  65.  
  66.     /* TextField fields */
  67.     static private final char BACKSPACE = 8;
  68.     static protected final char ENTER_DESKTOP = '\r';
  69.     static protected final char ENTER_ANDROID = '\n';
  70.     static private final char TAB = '\t';
  71.     static private final char DELETE = 127;
  72.     static private final char BULLET = 149;
  73.  
  74.     static private final Vector2 tmp1 = new Vector2();
  75.     static private final Vector2 tmp2 = new Vector2();
  76.     static private final Vector2 tmp3 = new Vector2();
  77.  
  78.     static public float keyRepeatInitialTime = 0.4f;
  79.     static public float keyRepeatTime = 0.1f;
  80.  
  81.     protected String text;
  82.     protected int cursor, selectionStart;
  83.     protected boolean hasSelection;
  84.     protected boolean writeEnters;
  85.     protected final GlyphLayout layout = new GlyphLayout();
  86.     protected final FloatArray glyphPositions = new FloatArray();
  87.  
  88.     SearchField.SearchFieldStyle style;
  89.     private String messageText;
  90.     protected CharSequence displayText;
  91.     Clipboard clipboard;
  92.     InputListener inputListener;
  93.     SearchField.SearchFieldListener listener;
  94.     SearchField.SearchFieldFilter filter;
  95.     SearchField.OnscreenKeyboard keyboard = new SearchField.DefaultOnscreenKeyboard();
  96.     boolean focusTraversal = true, onlyFontChars = true, disabled;
  97.     private int textHAlign = Align.left;
  98.     private float selectionX, selectionWidth;
  99.  
  100.     String undoText = "";
  101.     long lastChangeTime;
  102.  
  103.     boolean passwordMode;
  104.     private StringBuilder passwordBuffer;
  105.     private char passwordCharacter = BULLET;
  106.  
  107.     protected float fontOffset, textHeight, textOffset;
  108.     float renderOffset;
  109.     private int visibleTextStart, visibleTextEnd;
  110.     private int maxLength = 0;
  111.  
  112.     private float blinkTime = 0.32f;
  113.     boolean cursorOn = true;
  114.     long lastBlink;
  115.  
  116.     /* SelectBox fields */
  117.     static final Vector2 temp = new Vector2();
  118.  
  119.     final Array<T> items = new Array();
  120.     private float prefWidth, prefHeight;
  121.     final ArraySelection<T> selection = new ArraySelection(items);
  122.     SearchFieldList<T> searchFieldList;
  123.    
  124.     SearchField.KeyRepeatTask keyRepeatTask = new SearchField.KeyRepeatTask();
  125.     boolean programmaticChangeEvents;
  126.  
  127.     /* SearchField fields */
  128.     SearchFieldHelper updateHelper;
  129.  
  130.     public SearchField (String text, Skin skin) {
  131.         this(text, skin.get(SearchField.SearchFieldStyle.class), null);
  132.     }
  133.  
  134.     public SearchField (String text, Skin skin, SearchFieldHelper helper) {
  135.         this(text, skin.get(SearchField.SearchFieldStyle.class), helper);
  136.     }
  137.  
  138.     public SearchField (String text, Skin skin, String styleName) {
  139.         this(text, skin.get(styleName, SearchField.SearchFieldStyle.class), null);
  140.     }
  141.  
  142.     public SearchField (String text, Skin skin, String styleName, SearchFieldHelper helper) {
  143.         this(text, skin.get(styleName, SearchField.SearchFieldStyle.class), helper);
  144.     }
  145.  
  146.     public SearchField (String text, SearchField.SearchFieldStyle style, SearchFieldHelper helper) {
  147.         setStyle(style);
  148.         clipboard = Gdx.app.getClipboard();
  149.         initialize();
  150.         setText(text);
  151.         setSize(getPrefWidth(), getPrefHeight());
  152.         updateHelper = helper;
  153.         searchFieldList = new SearchFieldList<T>(this);
  154.     }
  155.  
  156.     protected void initialize () {
  157.         addListener(inputListener = createInputListener());
  158.     }
  159.  
  160.     protected InputListener createInputListener () {
  161.         return new SearchField.SearchFieldClickListener();
  162.     }
  163.  
  164.     protected int letterUnderCursor (float x) {
  165.         x -= textOffset + fontOffset - style.font.getData().cursorX - glyphPositions.get(visibleTextStart);
  166.         int n = this.glyphPositions.size;
  167.         float[] glyphPositions = this.glyphPositions.items;
  168.         for (int i = 1; i < n; i++) {
  169.             if (glyphPositions[i] > x) {
  170.                 if (glyphPositions[i] - x <= x - glyphPositions[i - 1]) return i;
  171.                 return i - 1;
  172.             }
  173.         }
  174.         return n - 1;
  175.     }
  176.  
  177.     protected boolean isWordCharacter (char c) {
  178.         return Character.isLetterOrDigit(c);
  179.     }
  180.  
  181.     protected int[] wordUnderCursor (int at) {
  182.         String text = this.text;
  183.         int start = at, right = text.length(), left = 0, index = start;
  184.         if(at>= text.length()){
  185.             left = text.length();
  186.             right = 0;
  187.         }
  188.         else {
  189.             for (; index < right; index++) {
  190.                 if (!isWordCharacter(text.charAt(index))) {
  191.                     right = index;
  192.                     break;
  193.                 }
  194.             }
  195.             for (index = start - 1; index > -1; index--) {
  196.                 if (!isWordCharacter(text.charAt(index))) {
  197.                     left = index + 1;
  198.                     break;
  199.                 }
  200.             }
  201.         }
  202.         return new int[] {left, right};
  203.     }
  204.  
  205.     int[] wordUnderCursor (float x) {
  206.         return wordUnderCursor(letterUnderCursor(x));
  207.     }
  208.  
  209.     boolean withinMaxLength (int size) {
  210.         return maxLength <= 0 || size < maxLength;
  211.     }
  212.  
  213.     public void setMaxLength (int maxLength) {
  214.         this.maxLength = maxLength;
  215.     }
  216.  
  217.     public int getMaxLength () {
  218.         return this.maxLength;
  219.     }
  220.  
  221.     /** When false, text set by {@link #setText(String)} may contain characters not in the font, a space will be displayed instead.
  222.      * When true (the default), characters not in the font are stripped by setText. Characters not in the font are always stripped
  223.      * when typed or pasted. */
  224.     public void setOnlyFontChars (boolean onlyFontChars) {
  225.         this.onlyFontChars = onlyFontChars;
  226.     }
  227.  
  228.     public void setStyle (SearchField.SearchFieldStyle style) {
  229.         if (style == null) throw new IllegalArgumentException("style cannot be null.");
  230.         this.style = style;
  231.         textHeight = style.font.getCapHeight() - style.font.getDescent() * 2;
  232.         invalidateHierarchy();
  233.     }
  234.  
  235.     /** Returns the text field's style. Modifying the returned style may not have an effect until {@link #setStyle(SearchField.SearchFieldStyle)}
  236.      * is called. */
  237.     public SearchField.SearchFieldStyle getStyle () {
  238.         return style;
  239.     }
  240.  
  241.     protected void calculateOffsets () {
  242.         float visibleWidth = getWidth();
  243.         if (style.background != null) visibleWidth -= style.background.getLeftWidth() + style.background.getRightWidth();
  244.  
  245.         int glyphCount = glyphPositions.size;
  246.         float[] glyphPositions = this.glyphPositions.items;
  247.  
  248.         // Check if the cursor has gone out the left or right side of the visible area and adjust renderOffset.
  249.         float distance = glyphPositions[Math.max(0, cursor - 1)] + renderOffset;
  250.         if (distance <= 0)
  251.             renderOffset -= distance;
  252.         else {
  253.             int index = Math.min(glyphCount - 1, cursor + 1);
  254.             float minX = glyphPositions[index] - visibleWidth;
  255.             if (-renderOffset < minX) renderOffset = -minX;
  256.         }
  257.  
  258.         // Prevent renderOffset from starting too close to the end, eg after text was deleted.
  259.         float maxOffset = 0;
  260.         float width = glyphPositions[glyphCount - 1];
  261.         for (int i = glyphCount - 2; i >= 0; i--) {
  262.             float x = glyphPositions[i];
  263.             if (width - x > visibleWidth) break;
  264.             maxOffset = x;
  265.         }
  266.         if (-renderOffset > maxOffset) renderOffset = -maxOffset;
  267.  
  268.         // calculate first visible char based on render offset
  269.         visibleTextStart = 0;
  270.         float startX = 0;
  271.         for (int i = 0; i < glyphCount; i++) {
  272.             if (glyphPositions[i] >= -renderOffset) {
  273.                 visibleTextStart = Math.max(0, i);
  274.                 startX = glyphPositions[i];
  275.                 break;
  276.             }
  277.         }
  278.  
  279.         // calculate last visible char based on visible width and render offset
  280.         int length = displayText.length();
  281.         visibleTextEnd = Math.min(length, cursor + 1);
  282.         for (; visibleTextEnd <= length; visibleTextEnd++)
  283.             if (glyphPositions[visibleTextEnd] > startX + visibleWidth) break;
  284.         visibleTextEnd = Math.max(0, visibleTextEnd - 1);
  285.  
  286.         if ((textHAlign & Align.left) == 0) {
  287.             textOffset = visibleWidth - (glyphPositions[visibleTextEnd] - startX);
  288.             if ((textHAlign & Align.center) != 0) textOffset = Math.round(textOffset * 0.5f);
  289.         } else
  290.             textOffset = startX + renderOffset;
  291.  
  292.         // calculate selection x position and width
  293.         if (hasSelection) {
  294.             int minIndex = Math.min(cursor, selectionStart);
  295.             int maxIndex = Math.max(cursor, selectionStart);
  296.             float minX = Math.max(glyphPositions[minIndex] - glyphPositions[visibleTextStart], -textOffset);
  297.             float maxX = Math.min(glyphPositions[maxIndex] - glyphPositions[visibleTextStart], visibleWidth - textOffset);
  298.             selectionX = minX;
  299.             selectionWidth = maxX - minX - style.font.getData().cursorX;
  300.         }
  301.     }
  302.  
  303.     @Override
  304.     public void draw (Batch batch, float parentAlpha) {
  305.         Stage stage = getStage();
  306.         boolean focused = stage != null && stage.getKeyboardFocus() == this;
  307.         if (!focused) keyRepeatTask.cancel();
  308.  
  309.         final BitmapFont font = style.font;
  310.         final Color fontColor = (disabled && style.disabledFontColor != null) ? style.disabledFontColor
  311.                 : ((focused && style.focusedFontColor != null) ? style.focusedFontColor : style.fontColor);
  312.         final Drawable selection = style.selection;
  313.         final Drawable cursorPatch = style.cursor;
  314.         final Drawable background = (disabled && style.disabledBackground != null) ? style.disabledBackground
  315.                 : ((focused && style.focusedBackground != null) ? style.focusedBackground : style.background);
  316.  
  317.         Color color = getColor();
  318.         float x = getX();
  319.         float y = getY();
  320.         float width = getWidth();
  321.         float height = getHeight();
  322.  
  323.         batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
  324.         float bgLeftWidth = 0, bgRightWidth = 0;
  325.         if (background != null) {
  326.             background.draw(batch, x, y, width, height);
  327.             bgLeftWidth = background.getLeftWidth();
  328.             bgRightWidth = background.getRightWidth();
  329.         }
  330.  
  331.         float textY = getTextY(font, background);
  332.         calculateOffsets();
  333.  
  334.         if (focused && hasSelection && selection != null) {
  335.             drawSelection(selection, batch, font, x + bgLeftWidth, y + textY);
  336.         }
  337.  
  338.         float yOffset = font.isFlipped() ? -textHeight : 0;
  339.         if (displayText.length() == 0) {
  340.             if (!focused && messageText != null) {
  341.                 if (style.messageFontColor != null) {
  342.                     font.setColor(style.messageFontColor.r, style.messageFontColor.g, style.messageFontColor.b,
  343.                             style.messageFontColor.a * color.a * parentAlpha);
  344.                 } else
  345.                     font.setColor(0.7f, 0.7f, 0.7f, color.a * parentAlpha);
  346.                 BitmapFont messageFont = style.messageFont != null ? style.messageFont : font;
  347.                 messageFont.draw(batch, messageText, x + bgLeftWidth, y + textY + yOffset, 0, messageText.length(),
  348.                         width - bgLeftWidth - bgRightWidth, textHAlign, false, "...");
  349.             }
  350.         } else {
  351.             font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * color.a * parentAlpha);
  352.             drawText(batch, font, x + bgLeftWidth, y + textY + yOffset);
  353.         }
  354.         if (focused && !disabled) {
  355.             blink();
  356.             if (cursorOn && cursorPatch != null) {
  357.                 drawCursor(cursorPatch, batch, font, x + bgLeftWidth, y + textY);
  358.             }
  359.         }
  360.     }
  361.  
  362.     protected float getTextY (BitmapFont font, Drawable background) {
  363.         float height = getHeight();
  364.         float textY = textHeight / 2 + font.getDescent();
  365.         if (background != null) {
  366.             float bottom = background.getBottomHeight();
  367.             textY = textY + (height - background.getTopHeight() - bottom) / 2 + bottom;
  368.         } else {
  369.             textY = textY + height / 2;
  370.         }
  371.         if (font.usesIntegerPositions()) textY = (int)textY;
  372.         return textY;
  373.     }
  374.  
  375.     /** Draws selection rectangle **/
  376.     protected void drawSelection (Drawable selection, Batch batch, BitmapFont font, float x, float y) {
  377.         selection.draw(batch, x + textOffset + selectionX + fontOffset, y - textHeight - font.getDescent(), selectionWidth,
  378.                 textHeight);
  379.     }
  380.  
  381.     protected void drawText (Batch batch, BitmapFont font, float x, float y) {
  382.         font.draw(batch, displayText, x + textOffset, y, visibleTextStart, visibleTextEnd, 0, Align.left, false);
  383.     }
  384.  
  385.     protected void drawCursor (Drawable cursorPatch, Batch batch, BitmapFont font, float x, float y) {
  386.         cursorPatch.draw(batch,
  387.                 x + textOffset + glyphPositions.get(cursor) - glyphPositions.get(visibleTextStart) + fontOffset + font.getData().cursorX,
  388.                 y - textHeight - font.getDescent(), cursorPatch.getMinWidth(), textHeight);
  389.     }
  390.  
  391.     void updateDisplayText () {
  392.         BitmapFont font = style.font;
  393.         BitmapFont.BitmapFontData data = font.getData();
  394.         String text = this.text;
  395.         int textLength = text.length();
  396.  
  397.         StringBuilder buffer = new StringBuilder();
  398.         for (int i = 0; i < textLength; i++) {
  399.             char c = text.charAt(i);
  400.             buffer.append(data.hasGlyph(c) ? c : ' ');
  401.         }
  402.         String newDisplayText = buffer.toString();
  403.  
  404.         if (passwordMode && data.hasGlyph(passwordCharacter)) {
  405.             if (passwordBuffer == null) passwordBuffer = new StringBuilder(newDisplayText.length());
  406.             if (passwordBuffer.length() > textLength)
  407.                 passwordBuffer.setLength(textLength);
  408.             else {
  409.                 for (int i = passwordBuffer.length(); i < textLength; i++)
  410.                     passwordBuffer.append(passwordCharacter);
  411.             }
  412.             displayText = passwordBuffer;
  413.         } else
  414.             displayText = newDisplayText;
  415.  
  416.         layout.setText(font, displayText);
  417.         glyphPositions.clear();
  418.         float x = 0;
  419.         if (layout.runs.size > 0) {
  420.             GlyphLayout.GlyphRun run = layout.runs.first();
  421.             FloatArray xAdvances = run.xAdvances;
  422.             fontOffset = xAdvances.first();
  423.             for (int i = 1, n = xAdvances.size; i < n; i++) {
  424.                 glyphPositions.add(x);
  425.                 x += xAdvances.get(i);
  426.             }
  427.         } else
  428.             fontOffset = 0;
  429.         glyphPositions.add(x);
  430.  
  431.         if (selectionStart > newDisplayText.length()) selectionStart = textLength;
  432.  
  433.         if(updateHelper != null){
  434.             setItems(updateHelper.search(text));
  435.             hideList();
  436.             showList();
  437.         }
  438.     }
  439.  
  440.     private void blink () {
  441.         if (!Gdx.graphics.isContinuousRendering()) {
  442.             cursorOn = true;
  443.             return;
  444.         }
  445.         long time = TimeUtils.nanoTime();
  446.         if ((time - lastBlink) / 1000000000.0f > blinkTime) {
  447.             cursorOn = !cursorOn;
  448.             lastBlink = time;
  449.         }
  450.     }
  451.  
  452.     /** Copies the contents of this SearchField to the {@link Clipboard} implementation set on this SearchField. */
  453.     public void copy () {
  454.         if (hasSelection && !passwordMode) {
  455.             clipboard.setContents(text.substring(Math.min(cursor, selectionStart), Math.max(cursor, selectionStart)));
  456.         }
  457.     }
  458.  
  459.     /** Copies the selected contents of this SearchField to the {@link Clipboard} implementation set on this SearchField, then removes
  460.      * it. */
  461.     public void cut () {
  462.         cut(programmaticChangeEvents);
  463.     }
  464.  
  465.     void cut (boolean fireChangeEvent) {
  466.         if (hasSelection && !passwordMode) {
  467.             copy();
  468.             cursor = delete(fireChangeEvent);
  469.             updateDisplayText();
  470.         }
  471.     }
  472.  
  473.     void paste (String content, boolean fireChangeEvent) {
  474.         if (content == null) return;
  475.         StringBuilder buffer = new StringBuilder();
  476.         int textLength = text.length();
  477.         if (hasSelection) textLength -= Math.abs(cursor - selectionStart);
  478.         BitmapFont.BitmapFontData data = style.font.getData();
  479.         for (int i = 0, n = content.length(); i < n; i++) {
  480.             if (!withinMaxLength(textLength + buffer.length())) break;
  481.             char c = content.charAt(i);
  482.             if (!(writeEnters && (c == ENTER_ANDROID || c == ENTER_DESKTOP))) {
  483.                 if (c == '\r' || c == '\n') continue;
  484.                 if (onlyFontChars && !data.hasGlyph(c)) continue;
  485.                 if (filter != null && !filter.acceptChar(this, c)) continue;
  486.             }
  487.             buffer.append(c);
  488.         }
  489.         content = buffer.toString();
  490.  
  491.         if (hasSelection) cursor = delete(fireChangeEvent);
  492.         if (fireChangeEvent)
  493.             changeText(text, insert(cursor, content, text));
  494.         else
  495.             text = insert(cursor, content, text);
  496.         updateDisplayText();
  497.         cursor += content.length();
  498.     }
  499.  
  500.     String insert (int position, CharSequence text, String to) {
  501.         if (to.length() == 0) return text.toString();
  502.         return to.substring(0, position) + text + to.substring(position, to.length());
  503.     }
  504.  
  505.     int delete (boolean fireChangeEvent) {
  506.         int from = selectionStart;
  507.         int to = cursor;
  508.         int minIndex = Math.min(from, to);
  509.         int maxIndex = Math.max(from, to);
  510.         String newText = (minIndex > 0 ? text.substring(0, minIndex) : "")
  511.                 + (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
  512.         if (fireChangeEvent)
  513.             changeText(text, newText);
  514.         else
  515.             text = newText;
  516.         clearSelection();
  517.         return minIndex;
  518.     }
  519.  
  520.     /** Focuses the next SearchField. If none is found, the keyboard is hidden. Does nothing if the text field is not in a stage.
  521.      * @param up If true, the SearchField with the same or next smallest y coordinate is found, else the next highest. */
  522.     public void next (boolean up) {
  523.         Stage stage = getStage();
  524.         if (stage == null) return;
  525.         SearchField current = this;
  526.         while (true) {
  527.             current.getParent().localToStageCoordinates(tmp1.set(getX(), getY()));
  528.             SearchField textField = current.findNextSearchField(stage.getActors(), null, tmp2, tmp1, up);
  529.             if (textField == null) { // Try to wrap around.
  530.                 if (up)
  531.                     tmp1.set(Float.MIN_VALUE, Float.MIN_VALUE);
  532.                 else
  533.                     tmp1.set(Float.MAX_VALUE, Float.MAX_VALUE);
  534.                 textField = current.findNextSearchField(getStage().getActors(), null, tmp2, tmp1, up);
  535.             }
  536.             if (textField == null) {
  537.                 Gdx.input.setOnscreenKeyboardVisible(false);
  538.                 break;
  539.             }
  540.             if (stage.setKeyboardFocus(textField)) break;
  541.             current = textField;
  542.         }
  543.     }
  544.  
  545.     private SearchField findNextSearchField (Array<Actor> actors, SearchField best, Vector2 bestCoords, Vector2 currentCoords,
  546.                                          boolean up) {
  547.         for (int i = 0, n = actors.size; i < n; i++) {
  548.             Actor actor = actors.get(i);
  549.             if (actor == this) continue;
  550.             if (actor instanceof SearchField) {
  551.                 SearchField textField = (SearchField)actor;
  552.                 if (textField.isDisabled() || !textField.focusTraversal) continue;
  553.                 Vector2 actorCoords = actor.getParent().localToStageCoordinates(tmp3.set(actor.getX(), actor.getY()));
  554.                 if ((actorCoords.y < currentCoords.y || (actorCoords.y == currentCoords.y && actorCoords.x > currentCoords.x)) ^ up) {
  555.                     if (best == null
  556.                             || (actorCoords.y > bestCoords.y || (actorCoords.y == bestCoords.y && actorCoords.x < bestCoords.x)) ^ up) {
  557.                         best = (SearchField)actor;
  558.                         bestCoords.set(actorCoords);
  559.                     }
  560.                 }
  561.             } else if (actor instanceof Group)
  562.                 best = findNextSearchField(((Group)actor).getChildren(), best, bestCoords, currentCoords, up);
  563.         }
  564.         return best;
  565.     }
  566.  
  567.     public InputListener getDefaultInputListener () {
  568.         return inputListener;
  569.     }
  570.  
  571.     /** @param listener May be null. */
  572.     public void setSearchFieldListener (SearchField.SearchFieldListener listener) {
  573.         this.listener = listener;
  574.     }
  575.  
  576.     /** @param filter May be null. */
  577.     public void setSearchFieldFilter (SearchField.SearchFieldFilter filter) {
  578.         this.filter = filter;
  579.     }
  580.  
  581.     public SearchField.SearchFieldFilter getSearchFieldFilter () {
  582.         return filter;
  583.     }
  584.  
  585.     /** If true (the default), tab/shift+tab will move to the next text field. */
  586.     public void setFocusTraversal (boolean focusTraversal) {
  587.         this.focusTraversal = focusTraversal;
  588.     }
  589.  
  590.     /** @return May be null. */
  591.     public String getMessageText () {
  592.         return messageText;
  593.     }
  594.  
  595.     /** Sets the text that will be drawn in the text field if no text has been entered.
  596.      * @param messageText may be null. */
  597.     public void setMessageText (String messageText) {
  598.         this.messageText = messageText;
  599.     }
  600.  
  601.     /** @param str If null, "" is used. */
  602.     public void appendText (String str) {
  603.         if (str == null) str = "";
  604.  
  605.         clearSelection();
  606.         cursor = text.length();
  607.         paste(str, programmaticChangeEvents);
  608.     }
  609.  
  610.     /** @param str If null, "" is used. */
  611.     public void setText (String str) {
  612.         if (str == null) str = "";
  613.         if (str.equals(text)) return;
  614.  
  615.         clearSelection();
  616.         String oldText = text;
  617.         text = "";
  618.         paste(str, false);
  619.         if (programmaticChangeEvents) changeText(oldText, text);
  620.         cursor = 0;
  621.     }
  622.  
  623.     /** @return Never null, might be an empty string. */
  624.     public String getText () {
  625.         return text;
  626.     }
  627.  
  628.     /** @param oldText May be null.
  629.      * @return True if the text was changed. */
  630.     boolean changeText (String oldText, String newText) {
  631.         if (newText.equals(oldText)) return false;
  632.         text = newText;
  633.         ChangeListener.ChangeEvent changeEvent = Pools.obtain(ChangeListener.ChangeEvent.class);
  634.         boolean cancelled = fire(changeEvent);
  635.         text = cancelled ? oldText : newText;
  636.         Pools.free(changeEvent);
  637.         return !cancelled;
  638.     }
  639.  
  640.     /** If false, methods that change the text will not fire {@link ChangeListener.ChangeEvent}, the event will be fired only when user changes
  641.      * the text. */
  642.     public void setProgrammaticChangeEvents (boolean programmaticChangeEvents) {
  643.         this.programmaticChangeEvents = programmaticChangeEvents;
  644.     }
  645.  
  646.     public boolean getProgrammaticChangeEvents () {
  647.         return programmaticChangeEvents;
  648.     }
  649.  
  650.     public int getSelectionStart () {
  651.         return selectionStart;
  652.     }
  653.  
  654.     public String getSelection () {
  655.         return hasSelection ? text.substring(Math.min(selectionStart, cursor), Math.max(selectionStart, cursor)) : "";
  656.     }
  657.  
  658.     /** Sets the selected text. */
  659.     public void setSelection (int selectionStart, int selectionEnd) {
  660.         if (selectionStart < 0) throw new IllegalArgumentException("selectionStart must be >= 0");
  661.         if (selectionEnd < 0) throw new IllegalArgumentException("selectionEnd must be >= 0");
  662.         selectionStart = Math.min(text.length(), selectionStart);
  663.         selectionEnd = Math.min(text.length(), selectionEnd);
  664.         if (selectionEnd == selectionStart) {
  665.             clearSelection();
  666.             return;
  667.         }
  668.         if (selectionEnd < selectionStart) {
  669.             int temp = selectionEnd;
  670.             selectionEnd = selectionStart;
  671.             selectionStart = temp;
  672.         }
  673.  
  674.         hasSelection = true;
  675.         this.selectionStart = selectionStart;
  676.         cursor = selectionEnd;
  677.     }
  678.  
  679.     public void selectAll () {
  680.         setSelection(0, text.length());
  681.     }
  682.  
  683.     public void clearSelection () {
  684.         hasSelection = false;
  685.     }
  686.  
  687.     /** Sets the cursor position and clears any selection. */
  688.     public void setCursorPosition (int cursorPosition) {
  689.         if (cursorPosition < 0) throw new IllegalArgumentException("cursorPosition must be >= 0");
  690.         clearSelection();
  691.         cursor = Math.min(cursorPosition, text.length());
  692.     }
  693.  
  694.     public int getCursorPosition () {
  695.         return cursor;
  696.     }
  697.  
  698.     /** Default is an instance of {@link SearchField.DefaultOnscreenKeyboard}. */
  699.     public SearchField.OnscreenKeyboard getOnscreenKeyboard () {
  700.         return keyboard;
  701.     }
  702.  
  703.     public void setOnscreenKeyboard (SearchField.OnscreenKeyboard keyboard) {
  704.         this.keyboard = keyboard;
  705.     }
  706.  
  707.     public void setClipboard (Clipboard clipboard) {
  708.         this.clipboard = clipboard;
  709.     }
  710.  
  711.  
  712.     /** Sets text horizontal alignment (left, center or right).
  713.      * @see Align */
  714.     public void setAlignment (int alignment) {
  715.         this.textHAlign = alignment;
  716.     }
  717.  
  718.     /** If true, the text in this text field will be shown as bullet characters.
  719.      * @see #setPasswordCharacter(char) */
  720.     public void setPasswordMode (boolean passwordMode) {
  721.         this.passwordMode = passwordMode;
  722.         updateDisplayText();
  723.     }
  724.  
  725.     public boolean isPasswordMode () {
  726.         return passwordMode;
  727.     }
  728.  
  729.     /** Sets the password character for the text field. The character must be present in the {@link BitmapFont}. Default is 149
  730.      * (bullet). */
  731.     public void setPasswordCharacter (char passwordCharacter) {
  732.         this.passwordCharacter = passwordCharacter;
  733.         if (passwordMode) updateDisplayText();
  734.     }
  735.  
  736.     public void setBlinkTime (float blinkTime) {
  737.         this.blinkTime = blinkTime;
  738.     }
  739.  
  740.     public void setDisabled (boolean disabled) {
  741.         if (disabled && !this.disabled) hideList();
  742.         this.disabled = disabled;
  743.     }
  744.  
  745.     public boolean isDisabled () {
  746.         return disabled;
  747.     }
  748.  
  749.     protected void moveCursor (boolean forward, boolean jump) {
  750.         int limit = forward ? text.length() : 0;
  751.         int charOffset = forward ? 0 : -1;
  752.         while ((forward ? ++cursor < limit : --cursor > limit) && jump) {
  753.             if (!continueCursor(cursor, charOffset)) break;
  754.         }
  755.     }
  756.  
  757.     protected boolean continueCursor (int index, int offset) {
  758.         char c = text.charAt(index + offset);
  759.         return isWordCharacter(c);
  760.     }
  761.  
  762.     class KeyRepeatTask extends Timer.Task {
  763.         int keycode;
  764.  
  765.         public void run () {
  766.             inputListener.keyDown(null, keycode);
  767.         }
  768.     }
  769.  
  770.     /** Interface for listening to typed characters.
  771.      * @author mzechner */
  772.     static public interface SearchFieldListener {
  773.         public void keyTyped (SearchField textField, char c);
  774.     }
  775.  
  776.     /** Interface for filtering characters entered into the text field.
  777.      * @author mzechner */
  778.     static public interface SearchFieldFilter {
  779.         public boolean acceptChar (SearchField textField, char c);
  780.  
  781.         static public class DigitsOnlyFilter implements SearchField.SearchFieldFilter {
  782.             @Override
  783.             public boolean acceptChar (SearchField textField, char c) {
  784.                 return Character.isDigit(c);
  785.             }
  786.  
  787.         }
  788.     }
  789.  
  790.     /** An interface for onscreen keyboards. Can invoke the default keyboard or render your own keyboard!
  791.      * @author mzechner */
  792.     static public interface OnscreenKeyboard {
  793.         public void show (boolean visible);
  794.     }
  795.  
  796.     /** The default {@link SearchField.OnscreenKeyboard} used by all {@link SearchField} instances. Just uses
  797.      * {@link Input#setOnscreenKeyboardVisible(boolean)} as appropriate. Might overlap your actual rendering, so use with care!
  798.      * @author mzechner */
  799.     static public class DefaultOnscreenKeyboard implements SearchField.OnscreenKeyboard {
  800.         @Override
  801.         public void show (boolean visible) {
  802.             Gdx.input.setOnscreenKeyboardVisible(visible);
  803.         }
  804.     }
  805.  
  806.     /** Basic input listener for the text field */
  807.     public class SearchFieldClickListener extends ClickListener {
  808.         public void clicked (InputEvent event, float x, float y) {
  809.             int count = getTapCount() % 4;
  810.             if (count == 0) clearSelection();
  811.             if (count == 2) {
  812.                 int[] array = wordUnderCursor(x);
  813.                 setSelection(array[0], array[1]);
  814.             }
  815.             if (count == 3) selectAll();
  816.         }
  817.  
  818.         public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
  819.             if (!super.touchDown(event, x, y, pointer, button)) return false;
  820.             if (pointer == 0 && button != 0) return false;
  821.             if (disabled) return true;
  822.             setCursorPosition(x, y);
  823.             selectionStart = cursor;
  824.             Stage stage = getStage();
  825.             if (stage != null) stage.setKeyboardFocus(SearchField.this);
  826.             keyboard.show(true);
  827.             hasSelection = true;
  828.             return true;
  829.         }
  830.  
  831.         public void touchDragged (InputEvent event, float x, float y, int pointer) {
  832.             super.touchDragged(event, x, y, pointer);
  833.             setCursorPosition(x, y);
  834.         }
  835.  
  836.         public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
  837.             if (selectionStart == cursor) hasSelection = false;
  838.             super.touchUp(event, x, y, pointer, button);
  839.         }
  840.  
  841.         protected void setCursorPosition (float x, float y) {
  842.             lastBlink = 0;
  843.             cursorOn = false;
  844.             cursor = letterUnderCursor(x);
  845.         }
  846.  
  847.         protected void goHome (boolean jump) {
  848.             cursor = 0;
  849.         }
  850.  
  851.         protected void goEnd (boolean jump) {
  852.             cursor = text.length();
  853.         }
  854.  
  855.         public boolean keyDown (InputEvent event, int keycode) {
  856.             if (disabled) return false;
  857.  
  858.             lastBlink = 0;
  859.             cursorOn = false;
  860.  
  861.             Stage stage = getStage();
  862.             if (stage == null || stage.getKeyboardFocus() != SearchField.this) return false;
  863.  
  864.             boolean repeat = false;
  865.             boolean ctrl = UIUtils.ctrl();
  866.             boolean jump = ctrl && !passwordMode;
  867.  
  868.             if (ctrl) {
  869.                 if (keycode == Input.Keys.V) {
  870.                     paste(clipboard.getContents(), true);
  871.                     repeat = true;
  872.                 }
  873.                 if (keycode == Input.Keys.C || keycode == Input.Keys.INSERT) {
  874.                     copy();
  875.                     return true;
  876.                 }
  877.                 if (keycode == Input.Keys.X) {
  878.                     cut(true);
  879.                     return true;
  880.                 }
  881.                 if (keycode == Input.Keys.A) {
  882.                     selectAll();
  883.                     return true;
  884.                 }
  885.                 if (keycode == Input.Keys.Z) {
  886.                     String oldText = text;
  887.                     setText(undoText);
  888.                     undoText = oldText;
  889.                     updateDisplayText();
  890.                     return true;
  891.                 }
  892.             }
  893.  
  894.             if (UIUtils.shift()) {
  895.                 if (keycode == Input.Keys.INSERT) paste(clipboard.getContents(), true);
  896.                 if (keycode == Input.Keys.FORWARD_DEL) cut(true);
  897.                 selection:
  898.                 {
  899.                     int temp = cursor;
  900.                     keys:
  901.                     {
  902.                         if (keycode == Input.Keys.LEFT) {
  903.                             moveCursor(false, jump);
  904.                             repeat = true;
  905.                             break keys;
  906.                         }
  907.                         if (keycode == Input.Keys.RIGHT) {
  908.                             moveCursor(true, jump);
  909.                             repeat = true;
  910.                             break keys;
  911.                         }
  912.                         if (keycode == Input.Keys.HOME) {
  913.                             goHome(jump);
  914.                             break keys;
  915.                         }
  916.                         if (keycode == Input.Keys.END) {
  917.                             goEnd(jump);
  918.                             break keys;
  919.                         }
  920.                         break selection;
  921.                     }
  922.                     if (!hasSelection) {
  923.                         selectionStart = temp;
  924.                         hasSelection = true;
  925.                     }
  926.                 }
  927.             } else {
  928.                 // Cursor movement or other keys (kills selection).
  929.                 if (keycode == Input.Keys.LEFT) {
  930.                     moveCursor(false, jump);
  931.                     clearSelection();
  932.                     repeat = true;
  933.                 }
  934.                 if (keycode == Input.Keys.RIGHT) {
  935.                     moveCursor(true, jump);
  936.                     clearSelection();
  937.                     repeat = true;
  938.                 }
  939.                 if (keycode == Input.Keys.HOME) {
  940.                     goHome(jump);
  941.                     clearSelection();
  942.                 }
  943.                 if (keycode == Input.Keys.END) {
  944.                     goEnd(jump);
  945.                     clearSelection();
  946.                 }
  947.             }
  948.             cursor = MathUtils.clamp(cursor, 0, text.length());
  949.  
  950.             if (repeat) {
  951.                 scheduleKeyRepeatTask(keycode);
  952.             }
  953.             return true;
  954.         }
  955.  
  956.         protected void scheduleKeyRepeatTask (int keycode) {
  957.             if (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode) {
  958.                 keyRepeatTask.keycode = keycode;
  959.                 keyRepeatTask.cancel();
  960.                 Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
  961.             }
  962.         }
  963.  
  964.         public boolean keyUp (InputEvent event, int keycode) {
  965.             if (disabled) return false;
  966.             keyRepeatTask.cancel();
  967.             return true;
  968.         }
  969.  
  970.         public boolean keyTyped (InputEvent event, char character) {
  971.             if (disabled) return false;
  972.  
  973.             // Disallow "typing" most ASCII control characters, which would show up as a space when onlyFontChars is true.
  974.             switch (character) {
  975.                 case BACKSPACE:
  976.                 case TAB:
  977.                 case ENTER_ANDROID:
  978.                 case ENTER_DESKTOP:
  979.                     break;
  980.                 default:
  981.                     if (character < 32) return false;
  982.             }
  983.  
  984.             Stage stage = getStage();
  985.             if (stage == null || stage.getKeyboardFocus() != SearchField.this) return false;
  986.  
  987.             if (UIUtils.isMac && Gdx.input.isKeyPressed(Input.Keys.SYM)) return true;
  988.  
  989.             if ((character == TAB || character == ENTER_ANDROID) && focusTraversal) {
  990.                 next(UIUtils.shift());
  991.             } else {
  992.                 boolean delete = character == DELETE;
  993.                 boolean backspace = character == BACKSPACE;
  994.                 boolean enter = character == ENTER_DESKTOP || character == ENTER_ANDROID;
  995.                 boolean add = enter ? writeEnters : (!onlyFontChars || style.font.getData().hasGlyph(character));
  996.                 boolean remove = backspace || delete;
  997.                 if (add || remove) {
  998.                     String oldText = text;
  999.                     int oldCursor = cursor;
  1000.                     if (hasSelection)
  1001.                         cursor = delete(false);
  1002.                     else {
  1003.                         if (backspace && cursor > 0) {
  1004.                             text = text.substring(0, cursor - 1) + text.substring(cursor--);
  1005.                             renderOffset = 0;
  1006.                         }
  1007.                         if (delete && cursor < text.length()) {
  1008.                             text = text.substring(0, cursor) + text.substring(cursor + 1);
  1009.                         }
  1010.                     }
  1011.                     if (add && !remove) {
  1012.                         // Character may be added to the text.
  1013.                         if (!enter && filter != null && !filter.acceptChar(SearchField.this, character)) return true;
  1014.                         if (!withinMaxLength(text.length())) return true;
  1015.                         String insertion = enter ? "\n" : String.valueOf(character);
  1016.                         text = insert(cursor++, insertion, text);
  1017.                     }
  1018.                     String tempUndoText = undoText;
  1019.                     if (changeText(oldText, text)) {
  1020.                         long time = System.currentTimeMillis();
  1021.                         if (time - 750 > lastChangeTime) undoText = oldText;
  1022.                         lastChangeTime = time;
  1023.                     } else
  1024.                         cursor = oldCursor;
  1025.                     updateDisplayText();
  1026.                 }
  1027.             }
  1028.             if (listener != null) listener.keyTyped(SearchField.this, character);
  1029.             return true;
  1030.         }
  1031.     }
  1032.    
  1033.     /* Methods from SearchField */
  1034.  
  1035.     /** Set the backing Array that makes up the choices available in the SearchField */
  1036.     public void setItems (T... newItems) {
  1037.         if (newItems == null) throw new IllegalArgumentException("newItems cannot be null.");
  1038.         float oldPrefWidth = getPrefWidth();
  1039.  
  1040.         items.clear();
  1041.         items.addAll(newItems);
  1042.         selection.validate();
  1043.         searchFieldList.list.setItems(items);
  1044.  
  1045.         invalidate();
  1046.         if (oldPrefWidth != getPrefWidth()) invalidateHierarchy();
  1047.     }
  1048.  
  1049.     /** Sets the items visible in the select box. */
  1050.     public void setItems (Array<T> newItems) {
  1051.         if (newItems == null) throw new IllegalArgumentException("newItems cannot be null.");
  1052.         float oldPrefWidth = getPrefWidth();
  1053.  
  1054.         items.clear();
  1055.         items.addAll(newItems);
  1056.         selection.validate();
  1057.         searchFieldList.list.setItems(items);
  1058.  
  1059.         invalidate();
  1060.         if (oldPrefWidth != getPrefWidth()) invalidateHierarchy();
  1061.     }
  1062.  
  1063.     public void clearItems () {
  1064.         if (items.size == 0) return;
  1065.         items.clear();
  1066.         selection.clear();
  1067.         invalidateHierarchy();
  1068.     }
  1069.  
  1070.     /** Returns the internal items array. If modified, {@link #setItems(Array)} must be called to reflect the changes. */
  1071.     public Array<T> getItems () {
  1072.         return items;
  1073.     }
  1074.  
  1075.     /** Get the set of selected items, useful when multiple items are selected
  1076.      * @return a Selection object containing the selected elements */
  1077.     public ArraySelection<T> getItemSelection () {
  1078.         return selection;
  1079.     }
  1080.  
  1081.     /** Returns the first selected item, or null. For multiple selections use {@link SearchField#getSelection()}. */
  1082.     public T getSelected () {
  1083.         return selection.first();
  1084.     }
  1085.  
  1086.     /** Sets the selection to only the passed item and fire a ChangedEvent. */
  1087.     public void setSelected (T item) {
  1088.         if (items.contains(item, false)) {
  1089.             selection.set(item);
  1090.             SelectListener.SelectEvent event = Pools.obtain(SelectListener.SelectEvent.class);
  1091.             boolean cancelled = fire(event);
  1092.             if(!cancelled){
  1093.                 setText(item.toString());
  1094.             }
  1095.             Pools.free(event);
  1096.         } else
  1097.             selection.clear();
  1098.     }
  1099.  
  1100.     /** @return The index of the first selected item. The top item has an index of 0. Nothing selected has an index of -1. */
  1101.     public int getSelectedIndex () {
  1102.         ObjectSet<T> selected = selection.items();
  1103.         return selected.size == 0 ? -1 : items.indexOf(selected.first(), false);
  1104.     }
  1105.  
  1106.     /** Sets the selection to only the selected index. */
  1107.     public void setSelectedIndex (int index) {
  1108.         selection.set(items.get(index));
  1109.     }
  1110.  
  1111.     public void showList () {
  1112.         if (items.size == 0) return;
  1113.         searchFieldList.show(getStage());
  1114.     }
  1115.  
  1116.     public void hideList () {
  1117.         searchFieldList.hide();
  1118.     }
  1119.  
  1120.     /** Returns the list shown when the select box is open. */
  1121.     public List<T> getList () {
  1122.         return searchFieldList.list;
  1123.     }
  1124.  
  1125.     /** Disables scrolling of the list shown when the select box is open. */
  1126.     public void setScrollingDisabled (boolean y) {
  1127.         searchFieldList.setScrollingDisabled(true, y);
  1128.         invalidateHierarchy();
  1129.     }
  1130.  
  1131.     /** Returns the scroll pane containing the list that is shown when the select box is open. */
  1132.     public ScrollPane getScrollPane () {
  1133.         return searchFieldList;
  1134.     }
  1135.  
  1136.     protected void onShow (Actor searchFieldList, boolean below) {
  1137.         searchFieldList.getColor().a = 0;
  1138.         searchFieldList.addAction(fadeIn(0.3f, Interpolation.fade));
  1139.     }
  1140.  
  1141.     protected void onHide (Actor searchFieldList) {
  1142.         searchFieldList.getColor().a = 1;
  1143.         searchFieldList.addAction(sequence(fadeOut(0.15f, Interpolation.fade), removeActor()));
  1144.     }
  1145.  
  1146.     protected String toString (T obj) {
  1147.         return obj.toString();
  1148.     }
  1149.  
  1150.     public float getPrefWidth () {
  1151.         validate();
  1152.         return prefWidth;
  1153.     }
  1154.  
  1155.     public float getPrefHeight () {
  1156.         validate();
  1157.         return prefHeight;
  1158.     }
  1159.  
  1160.     @Override
  1161.     public void layout () {
  1162.         Drawable bg = style.background;
  1163.         BitmapFont font = style.font;
  1164.  
  1165.         if (bg != null) {
  1166.             prefHeight = Math.max(bg.getTopHeight() + bg.getBottomHeight() + font.getCapHeight() - font.getDescent() * 2,
  1167.                     bg.getMinHeight());
  1168.         } else
  1169.             prefHeight = font.getCapHeight() - font.getDescent() * 2;
  1170.  
  1171.         float maxItemWidth = 0;
  1172.         Pool<GlyphLayout> layoutPool = Pools.get(GlyphLayout.class);
  1173.         GlyphLayout layout = layoutPool.obtain();
  1174.         for (int i = 0; i < items.size; i++) {
  1175.             layout.setText(font, toString(items.get(i)));
  1176.             maxItemWidth = Math.max(layout.width, maxItemWidth);
  1177.         }
  1178.         layoutPool.free(layout);
  1179.  
  1180.         prefWidth = maxItemWidth;
  1181.         if (bg != null) prefWidth += bg.getLeftWidth() + bg.getRightWidth();
  1182.  
  1183.         List.ListStyle listStyle = style.listStyle;
  1184.         ScrollPane.ScrollPaneStyle scrollStyle = style.scrollStyle;
  1185.         float listWidth = maxItemWidth + listStyle.selection.getLeftWidth() + listStyle.selection.getRightWidth();
  1186.         if (scrollStyle.background != null)
  1187.             listWidth += scrollStyle.background.getLeftWidth() + scrollStyle.background.getRightWidth();
  1188.         if (searchFieldList == null || !searchFieldList.isScrollingDisabledY())
  1189.             listWidth += Math.max(style.scrollStyle.vScroll != null ? style.scrollStyle.vScroll.getMinWidth() : 0,
  1190.                     style.scrollStyle.vScrollKnob != null ? style.scrollStyle.vScrollKnob.getMinWidth() : 0);
  1191.         prefWidth = Math.max(prefWidth, listWidth);
  1192.     }
  1193.  
  1194.     /** @author Nathan Sweet
  1195.      *  @author mellotanica */
  1196.     static class SearchFieldList<T> extends ScrollPane {
  1197.         private final SearchField<T> searchField;
  1198.         int maxListCount;
  1199.         private final Vector2 screenPosition = new Vector2();
  1200.         final List<T> list;
  1201.         private InputListener hideListener;
  1202.         private Actor previousScrollFocus;
  1203.         private boolean forceBelow;
  1204.  
  1205.         public SearchFieldList (final SearchField<T> searchField) {
  1206.             super(null, searchField.style.scrollStyle);
  1207.             this.searchField = searchField;
  1208.  
  1209.             setOverscroll(false, false);
  1210.             setFadeScrollBars(false);
  1211.             setScrollingDisabled(true, false);
  1212.  
  1213.             this.forceBelow = searchField.style.forceBelow;
  1214.  
  1215.             list = new List<T>(searchField.style.listStyle) {
  1216.                 @Override
  1217.                 protected String toString (T obj) {
  1218.                     return searchField.toString(obj);
  1219.                 }
  1220.             };
  1221.             list.setTouchable(Touchable.disabled);
  1222.             setWidget(list);
  1223.  
  1224.             list.addListener(new ClickListener() {
  1225.                 public void clicked (InputEvent event, float x, float y) {
  1226.                     searchField.setSelected(list.getSelected());
  1227.                     hide();
  1228.                 }
  1229.  
  1230.                 public boolean mouseMoved (InputEvent event, float x, float y) {
  1231.                     list.setSelectedIndex(Math.min(searchField.items.size - 1, (int)((list.getHeight() - y) / list.getItemHeight())));
  1232.                     return true;
  1233.                 }
  1234.             });
  1235.  
  1236.             addListener(new InputListener() {
  1237.                 public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) {
  1238.                     if (toActor == null || !isAscendantOf(toActor)) list.setSelected(searchField.getSelected());
  1239.                 }
  1240.             });
  1241.  
  1242.             hideListener = new InputListener() {
  1243.                 public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
  1244.                     Actor target = event.getTarget();
  1245.                     if (isAscendantOf(target)) return false;
  1246.                     list.setSelected(searchField.getSelected());
  1247.                     hide();
  1248.                     return false;
  1249.                 }
  1250.  
  1251.                 public boolean keyDown (InputEvent event, int keycode) {
  1252.                     if (keycode == Input.Keys.ESCAPE) hide();
  1253.                     return false;
  1254.                 }
  1255.             };
  1256.         }
  1257.  
  1258.         public void show (Stage stage) {
  1259.             if (list.isTouchable()) return;
  1260.  
  1261.             stage.removeCaptureListener(hideListener);
  1262.             stage.addCaptureListener(hideListener);
  1263.             stage.addActor(this);
  1264.  
  1265.             searchField.localToStageCoordinates(screenPosition.set(0, 0));
  1266.  
  1267.             // Show the list above or below the select box, limited to a number of items and the available height in the stage.
  1268.             float itemHeight = list.getItemHeight();
  1269.             float height = itemHeight * (maxListCount <= 0 ? searchField.items.size : Math.min(maxListCount, searchField.items.size));
  1270.             Drawable scrollPaneBackground = getStyle().background;
  1271.             if (scrollPaneBackground != null) height += scrollPaneBackground.getTopHeight() + scrollPaneBackground.getBottomHeight();
  1272.             Drawable listBackground = list.getStyle().background;
  1273.             if (listBackground != null) height += listBackground.getTopHeight() + listBackground.getBottomHeight();
  1274.  
  1275.             float heightBelow = screenPosition.y;
  1276.             float heightAbove = stage.getCamera().viewportHeight - screenPosition.y - searchField.getHeight();
  1277.             boolean below = true;
  1278.             if (height > heightBelow) {
  1279.                 if (heightAbove > heightBelow && !forceBelow) {
  1280.                     below = false;
  1281.                     height = Math.min(height, heightAbove);
  1282.                 } else
  1283.                     height = heightBelow;
  1284.             }
  1285.  
  1286.             if (below)
  1287.                 setY(screenPosition.y - height);
  1288.             else
  1289.                 setY(screenPosition.y + searchField.getHeight());
  1290.             setX(screenPosition.x);
  1291.             setHeight(height);
  1292.             validate();
  1293.  
  1294.             float innerWidth = getPrefWidth() + ((getPrefHeight() > height && !isScrollingDisabledY())? getScrollBarWidth() : 0);
  1295.             float width = Math.max(innerWidth, searchField.getWidth());
  1296.             setWidth(width);
  1297.  
  1298.             validate();
  1299.             scrollTo(0, list.getHeight() - searchField.getSelectedIndex() * itemHeight - itemHeight / 2, 0, 0, true, true);
  1300.             updateVisualScroll();
  1301.  
  1302.             previousScrollFocus = null;
  1303.             Actor actor = stage.getScrollFocus();
  1304.             if (actor != null && !actor.isDescendantOf(this)) previousScrollFocus = actor;
  1305.             stage.setScrollFocus(this);
  1306.  
  1307.             list.setSelected(searchField.getSelected());
  1308.             list.setTouchable(Touchable.enabled);
  1309.             clearActions();
  1310.             searchField.onShow(this, below);
  1311.         }
  1312.  
  1313.         public void hide () {
  1314.             if (!list.isTouchable() || !hasParent()) return;
  1315.             list.setTouchable(Touchable.disabled);
  1316.  
  1317.             Stage stage = getStage();
  1318.             if (stage != null) {
  1319.                 stage.removeCaptureListener(hideListener);
  1320.                 if (previousScrollFocus != null && previousScrollFocus.getStage() == null) previousScrollFocus = null;
  1321.                 Actor actor = stage.getScrollFocus();
  1322.                 if (actor == null || isAscendantOf(actor)) stage.setScrollFocus(previousScrollFocus);
  1323.             }
  1324.  
  1325.             clearActions();
  1326.             searchField.onHide(this);
  1327.         }
  1328.  
  1329.         public void draw (Batch batch, float parentAlpha) {
  1330.             searchField.localToStageCoordinates(temp.set(0, 0));
  1331.             if (!temp.equals(screenPosition)) hide();
  1332.             super.draw(batch, parentAlpha);
  1333.         }
  1334.  
  1335.         public void act (float delta) {
  1336.             super.act(delta);
  1337.             toFront();
  1338.         }
  1339.     }
  1340.  
  1341.     /** The style for a text field, see {@link SearchField}.
  1342.      * @author mzechner
  1343.      * @author Nathan Sweet
  1344.      * @author mellotanica */
  1345.     static public class SearchFieldStyle {
  1346.         public BitmapFont font;
  1347.         public ScrollPane.ScrollPaneStyle scrollStyle;
  1348.         public List.ListStyle listStyle;
  1349.         public Color fontColor;
  1350.         /** Optional. */
  1351.         public Color focusedFontColor, disabledFontColor;
  1352.         /** Optional. */
  1353.         public Drawable background, focusedBackground, disabledBackground, cursor, selection;
  1354.         /** Optional. */
  1355.         public BitmapFont messageFont;
  1356.         /** Optional. */
  1357.         public Color messageFontColor;
  1358.         /** Optional. */
  1359.         public boolean forceBelow;
  1360.  
  1361.         public SearchFieldStyle () {
  1362.         }
  1363.  
  1364.         public SearchFieldStyle (BitmapFont font, Color fontColor, Drawable cursor, Drawable selection, Drawable background,
  1365.                                  ScrollPane.ScrollPaneStyle scrollPaneStyle, List.ListStyle listStyle) {
  1366.             this.background = background;
  1367.             this.cursor = cursor;
  1368.             this.font = font;
  1369.             this.fontColor = fontColor;
  1370.             this.selection = selection;
  1371.             this.scrollStyle = scrollPaneStyle;
  1372.             this.listStyle = listStyle;
  1373.         }
  1374.  
  1375.         public SearchFieldStyle (SearchField.SearchFieldStyle style) {
  1376.             this.messageFont = style.messageFont;
  1377.             if (style.messageFontColor != null) this.messageFontColor = new Color(style.messageFontColor);
  1378.             this.background = style.background;
  1379.             this.focusedBackground = style.focusedBackground;
  1380.             this.disabledBackground = style.disabledBackground;
  1381.             this.cursor = style.cursor;
  1382.             this.font = style.font;
  1383.             if (style.fontColor != null) this.fontColor = new Color(style.fontColor);
  1384.             if (style.focusedFontColor != null) this.focusedFontColor = new Color(style.focusedFontColor);
  1385.             if (style.disabledFontColor != null) this.disabledFontColor = new Color(style.disabledFontColor);
  1386.             this.selection = style.selection;
  1387.             this.scrollStyle = new ScrollPane.ScrollPaneStyle(style.scrollStyle);
  1388.             this.listStyle = new List.ListStyle(style.listStyle);
  1389.             this.forceBelow = style.forceBelow;
  1390.         }
  1391.     }
  1392.  
  1393.     public interface SearchFieldHelper<T> {
  1394.         Array<T> search(CharSequence query);
  1395.     }
  1396. }
Advertisement
Add Comment
Please, Sign In to add comment