Search in sources :

Example 6 with Char

use of com.codename1.ui.TextSelection.Char in project CodenameOne by codenameone.

the class SimpleDateFormat method format.

@Override
String format(Date source, StringBuilder toAppendTo) {
    if (pattern == null) {
        return super.format(source, toAppendTo);
    }
    // format based on local timezone
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
    calendar.setTime(source);
    List<String> pattern = getPatternTokens();
    for (int i = 0; i < pattern.size(); i++) {
        String token = (String) pattern.get(i);
        char patternChar = token.charAt(0);
        token = token.substring(1);
        int len = token.length();
        int v = -1;
        switch(patternChar) {
            case LITERAL_LETTER:
                toAppendTo.append(token);
                break;
            case AMPM_LETTER:
                boolean am = calendar.get(Calendar.AM_PM) == Calendar.AM;
                String[] ampm = getDateFormatSymbols().getAmPmStrings();
                toAppendTo.append(am ? ampm[0] : ampm[1]);
                break;
            case ERA_LETTER:
                toAppendTo.append(getDateFormatSymbols().getEras()[calendar.get(ERA)]);
                break;
            case DAY_OF_WEEK_LETTER:
                v = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                if (len > 3) {
                    toAppendTo.append(getDateFormatSymbols().getWeekdays()[v]);
                } else {
                    toAppendTo.append(getDateFormatSymbols().getShortWeekdays()[v]);
                }
                break;
            case TIMEZONE_LETTER:
                String[] names = getTimeZoneDisplayNames(calendar.getTimeZone().getID());
                if (names == null) {
                    toAppendTo.append(calendar.getTimeZone().getID());
                } else {
                    DateUtil du = new DateUtil(TimeZone.getTimeZone(names[DateFormatSymbols.ZONE_ID]));
                    toAppendTo.append(names[du.inDaylightTime(source) ? DateFormatSymbols.ZONE_SHORTNAME_DST : DateFormatSymbols.ZONE_SHORTNAME]);
                }
                break;
            case TIMEZONE822_LETTER:
                v = getOffsetInMinutes(calendar, calendar.getTimeZone());
                if (v < 0) {
                    toAppendTo.append(SIGN_NEGATIVE);
                    v = -v;
                } else {
                    toAppendTo.append(SIGN_POSITIVE);
                }
                toAppendTo.append(leftPad(v / 60, 2));
                toAppendTo.append(leftPad(v % 60, 2));
                break;
            case YEAR_LETTER:
                v = calendar.get(Calendar.YEAR);
                if (len == 2) {
                    v %= 100;
                }
                toAppendTo.append(leftPad(v, len));
                break;
            case MONTH_LETTER:
                v = calendar.get(Calendar.MONTH) - Calendar.JANUARY;
                if (len > 3) {
                    toAppendTo.append(L10NManager.getInstance().getLongMonthName(source));
                } else if (len == 3) {
                    toAppendTo.append(L10NManager.getInstance().getShortMonthName(source));
                } else {
                    toAppendTo.append(leftPad(v + 1, len));
                }
                break;
            case DAY_LETTER:
                v = calendar.get(Calendar.DAY_OF_MONTH);
                toAppendTo.append(leftPad(v, len));
                break;
            case HOUR_LETTER:
            case HOUR_1_LETTER:
            case HOUR12_LETTER:
            case HOUR12_1_LETTER:
                v = calendar.get(Calendar.HOUR_OF_DAY);
                if (patternChar == HOUR_1_LETTER && v == 0) {
                    v = 24;
                }
                if (patternChar == HOUR12_1_LETTER) {
                    v %= 12;
                    if (v == 0) {
                        v = 12;
                    }
                } else {
                    if (patternChar == HOUR12_LETTER) {
                        v %= 12;
                    }
                }
                toAppendTo.append(leftPad(v, len));
                break;
            case MINUTE_LETTER:
                v = calendar.get(Calendar.MINUTE);
                toAppendTo.append(leftPad(v, len));
                break;
            case SECOND_LETTER:
                v = calendar.get(Calendar.SECOND);
                toAppendTo.append(leftPad(v, len));
                break;
            case MILLISECOND_LETTER:
                v = calendar.get(Calendar.MILLISECOND);
                toAppendTo.append(leftPad(v, len));
                break;
            case WEEK_IN_YEAR_LETTER:
                v = calendar.get(WEEK_OF_YEAR);
                toAppendTo.append(leftPad(v, len));
                break;
            case WEEK_IN_MONTH_LETTER:
                v = calendar.get(WEEK_OF_MONTH);
                toAppendTo.append(leftPad(v, len));
                break;
            case DAY_IN_YEAR_LETTER:
                v = calendar.get(DAY_OF_YEAR);
                toAppendTo.append(leftPad(v, len));
                break;
            case DOW_IN_MONTH_LETTER:
                v = calendar.get(DAY_OF_WEEK_IN_MONTH);
                toAppendTo.append(leftPad(v, len));
                break;
        }
    }
    return toAppendTo.toString();
}
Also used : DateUtil(com.codename1.util.DateUtil) Calendar(java.util.Calendar)

Example 7 with Char

use of com.codename1.ui.TextSelection.Char in project CodenameOne by codenameone.

the class CSSEngine method handleContentProperty.

/**
 * Handles a CSS content property
 *
 * @param element The element this content property
 * @param selector The CSS selector that includes the content property
 * @param htmlC The HTMLComponent
 */
private void handleContentProperty(HTMLElement element, CSSElement selector, HTMLComponent htmlC) {
    boolean after = ((selector.getSelectorPseudoClass() & CSSElement.PC_AFTER) != 0);
    String content = selector.getAttributeById(CSSElement.CSS_CONTENT);
    if (content != null) {
        // if there's no content, we don't add anything
        Component cmp = after ? (Component) element.getUi().lastElement() : (Component) element.getUi().firstElement();
        Component styleCmp = cmp;
        Container parent = null;
        int pos = 0;
        if (cmp instanceof Container) {
            parent = ((Container) cmp);
            while ((parent.getComponentCount() > 0) && (parent.getComponentAt(after ? parent.getComponentCount() - 1 : 0) instanceof Container)) {
                // find the actual content
                parent = (Container) parent.getComponentAt(after ? parent.getComponentCount() - 1 : 0);
            }
            if (parent.getComponentCount() > 0) {
                pos = after ? parent.getComponentCount() - 1 : 0;
                styleCmp = parent.getComponentAt(pos);
            }
        } else {
            parent = cmp.getParent();
            pos = cmp.getParent().getComponentIndex(cmp);
        }
        if (after) {
            pos++;
        }
        int initPos = pos;
        String str = "";
        // to make sure the last expression is evaluated, note that this will not print an extra space in any case, since it is out of the quotes if any
        content = content + " ";
        boolean segment = false;
        for (int i = 0; i < content.length(); i++) {
            char c = content.charAt(i);
            Label lbl = null;
            if (c == '"') {
                segment = !segment;
                if ((!segment) && (str.length() > 0)) {
                    lbl = new Label(str);
                    str = "";
                }
            } else if (CSSParser.isWhiteSpace(c)) {
                if (segment) {
                    str += c;
                    lbl = new Label(str);
                } else if (str.length() > 0) {
                    lbl = evalContentExpression(htmlC, str, element, selector);
                    if (lbl == null) {
                        // if we didn't find a match we search for the following expressions which are used to remove added content
                        int removeQuoteType = -1;
                        boolean removeAll = false;
                        if ((str.equals("none")) || (str.equals("normal"))) {
                            // normal/none means remove all content
                            removeAll = true;
                        } else if (str.equals("no-open-quote")) {
                            // 0 is the quote type for open quote, 1 for closed one
                            removeQuoteType = 0;
                        } else if (str.equals("no-close-quote")) {
                            removeQuoteType = 1;
                        }
                        if ((removeAll) || (removeQuoteType != -1)) {
                            Vector v = element.getUi();
                            if (v != null) {
                                Vector toRemove = new Vector();
                                for (Enumeration e = v.elements(); e.hasMoreElements(); ) {
                                    Component ui = (Component) e.nextElement();
                                    String conStr = (String) ui.getClientProperty(CLIENT_PROPERTY_CSS_CONTENT);
                                    if ((conStr != null) && (((after) && (conStr.equals("a"))) || ((!after) && (conStr.equals("b"))))) {
                                        boolean remove = true;
                                        if (removeQuoteType != -1) {
                                            Object obj = ui.getClientProperty(HTMLComponent.CLIENT_PROPERTY_QUOTE);
                                            if (obj != null) {
                                                int quoteType = ((Integer) obj).intValue();
                                                remove = (quoteType == removeQuoteType);
                                            } else {
                                                remove = false;
                                            }
                                        }
                                        if (remove) {
                                            parent.removeComponent(ui);
                                            toRemove.addElement(ui);
                                        }
                                    }
                                }
                                for (Enumeration e = toRemove.elements(); e.hasMoreElements(); ) {
                                    v.removeElement(e.nextElement());
                                }
                            }
                            // stop processing after removal clauses such as none/normal
                            return;
                        }
                    }
                }
                str = "";
            } else {
                str += c;
            }
            if (lbl != null) {
                if (after) {
                    element.addAssociatedComponent(lbl);
                } else {
                    element.addAssociatedComponentAt(pos - initPos, lbl);
                }
                lbl.setUnselectedStyle(new Style(styleCmp.getUnselectedStyle()));
                lbl.putClientProperty(CLIENT_PROPERTY_CSS_CONTENT, after ? "a" : "b");
                if (parent.getComponentCount() == 0) {
                    parent.addComponent(lbl);
                } else {
                    parent.addComponent(pos, lbl);
                }
                pos++;
                applyStyleToUIElement(lbl, selector, element, htmlC);
            }
        }
    }
}
Also used : Container(com.codename1.ui.Container) Enumeration(java.util.Enumeration) Label(com.codename1.ui.Label) Style(com.codename1.ui.plaf.Style) Component(com.codename1.ui.Component) Vector(java.util.Vector)

Example 8 with Char

use of com.codename1.ui.TextSelection.Char in project CodenameOne by codenameone.

the class FontImage method setFontIcon.

/**
 * <p>Applies an icon from the font to the given command using the
 * given UIID. Notice that the pressed/selected &amp; disabled states will be set appropriately.</p>
 *
 * @param c a command
 * @param font a font with icons
 * @param icon an icon in the font
 * @param uiid the UIID for the command (e.g. TitleCommand)
 * @param size the size of the icon in millimeters
 */
public static void setFontIcon(Command c, Font font, char icon, String uiid, float size) {
    UIManager uim = UIManager.getInstance();
    Style s = uim.getComponentStyle(uiid);
    s.setFont(font.derive(rightSize(s, size), Font.STYLE_PLAIN));
    c.setIcon(FontImage.create("" + icon, s));
    Style sel = uim.getComponentSelectedStyle(uiid);
    Style pre = uim.getComponentCustomStyle(uiid, "press");
    Style dis = uim.getComponentCustomStyle(uiid, "dis");
    ;
    if (sel.getFgColor() != s.getFgColor() || (sel.getBgColor() != s.getBgColor()) || (sel.getBgTransparency() != s.getBgTransparency()) || (sel.getFgAlpha() != s.getFgAlpha())) {
        sel = new Style(sel);
        sel.setFont(font.derive(rightSize(sel, size), Font.STYLE_PLAIN));
        c.setRolloverIcon(FontImage.create("" + icon, sel));
    }
    if (pre.getFgColor() != s.getFgColor() || (pre.getBgColor() != s.getBgColor()) || (pre.getBgTransparency() != s.getBgTransparency()) || (pre.getFgAlpha() != s.getFgAlpha())) {
        pre = new Style(pre);
        pre.setFont(font.derive(rightSize(pre, size), Font.STYLE_PLAIN));
        c.setPressedIcon(FontImage.create("" + icon, pre));
    }
    if (dis.getFgColor() != s.getFgColor() || (dis.getBgColor() != s.getBgColor()) || (dis.getBgTransparency() != s.getBgTransparency()) || (dis.getFgAlpha() != s.getFgAlpha())) {
        dis = new Style(dis);
        dis.setFont(font.derive(rightSize(dis, size), Font.STYLE_PLAIN));
        c.setDisabledIcon(FontImage.create("" + icon, dis));
    }
}
Also used : UIManager(com.codename1.ui.plaf.UIManager) Style(com.codename1.ui.plaf.Style)

Example 9 with Char

use of com.codename1.ui.TextSelection.Char in project CodenameOne by codenameone.

the class Paint method getTextWidths.

public void getTextWidths(String text, float[] widths) {
    Font f = getTypeface();
    if (f != null) {
        char[] chars = text.toCharArray();
        int clen = chars.length;
        int wlen = widths.length;
        for (int i = 0; i < clen && i < wlen; i++) {
            widths[i] = f.charWidth(chars[i]);
        }
    } else {
        throw new RuntimeException("Faild to get cn1 font");
    }
}
Also used : Font(com.codename1.ui.Font)

Example 10 with Char

use of com.codename1.ui.TextSelection.Char in project CodenameOne by codenameone.

the class JavaSEPort method editString.

/**
 * @inheritDoc
 */
public void editString(final Component cmp, final int maxSize, final int constraint, String text, final int keyCode) {
    if (scrollWheeling) {
        return;
    }
    if (System.getProperty("TextCompatMode") != null) {
        editStringLegacy(cmp, maxSize, constraint, text, keyCode);
        return;
    }
    if (editingInProgress != null) {
        final String fText = text;
        editingInProgress.invokeAfter(new Runnable() {

            public void run() {
                CN.callSerially(new Runnable() {

                    public void run() {
                        editString(cmp, maxSize, constraint, fText, keyCode);
                    }
                });
            }
        });
        editingInProgress.endEditing();
        return;
    }
    // a workaround to fix an issue where the previous Text Component wasn't removed properly.
    // java.awt.Component [] cmps = canvas.getComponents();
    // for (int i = 0; i < cmps.length; i++) {
    // java.awt.Component cmp1 = cmps[i];
    // if(cmp1 instanceof JScrollPane || cmp1 instanceof javax.swing.text.JTextComponent){
    // canvas.remove(cmp1);
    // }
    // }
    checkEDT();
    class Repainter {

        JComponent jcmp;

        javax.swing.border.Border origBorder;

        Repainter(JComponent jcmp) {
            this.jcmp = jcmp;
        }

        void repaint(long tm, int x, int y, int width, int height) {
            boolean oldShowEdtWarnings = showEDTWarnings;
            showEDTWarnings = false;
            // cmp.getSelectedStyle().getPadding(Component.TOP);
            int marginTop = 0;
            // cmp.getSelectedStyle().getPadding(Component.LEFT);
            int marginLeft = 0;
            // cmp.getSelectedStyle().getPadding(Component.RIGHT);
            int marginRight = 0;
            // cmp.getSelectedStyle().getPadding(Component.BOTTOM);
            int marginBottom = 0;
            int paddingTop = Math.round(cmp.getSelectedStyle().getPadding(Component.TOP) * zoomLevel);
            int paddingLeft = Math.round(cmp.getSelectedStyle().getPadding(Component.LEFT) * zoomLevel);
            int paddingRight = Math.round(cmp.getSelectedStyle().getPadding(Component.RIGHT) * zoomLevel);
            int paddingBottom = Math.round(cmp.getSelectedStyle().getPadding(Component.BOTTOM) * zoomLevel);
            Rectangle bounds;
            if (getSkin() != null) {
                bounds = new Rectangle((int) ((cmp.getAbsoluteX() + cmp.getScrollX() + getScreenCoordinates().x + canvas.x + marginLeft) * zoomLevel), (int) ((cmp.getAbsoluteY() + cmp.getScrollY() + getScreenCoordinates().y + canvas.y + marginTop) * zoomLevel), (int) ((cmp.getWidth() - marginLeft - marginRight) * zoomLevel), (int) ((cmp.getHeight() - marginTop - marginBottom) * zoomLevel));
            } else {
                bounds = new Rectangle(cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft, cmp.getAbsoluteY() + cmp.getScrollY() + marginTop, cmp.getWidth() - marginRight - marginLeft, cmp.getHeight() - marginTop - marginBottom);
            }
            if (!jcmp.getBounds().equals(bounds)) {
                jcmp.setBounds(bounds);
                if (origBorder == null) {
                    origBorder = jcmp.getBorder();
                }
                // jcmp.setBorder(BorderFactory.createCompoundBorder(
                // origBorder,
                // BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight))
                // );
                jcmp.setBorder(BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight));
            }
            showEDTWarnings = oldShowEdtWarnings;
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    cmp.repaint();
                }
            });
        }
    }
    javax.swing.text.JTextComponent swingT;
    if (((com.codename1.ui.TextArea) cmp).isSingleLineTextArea()) {
        JTextComponent t;
        if ((constraint & TextArea.PASSWORD) == TextArea.PASSWORD) {
            t = new JPasswordField() {

                Repainter repainter = new Repainter(this);

                @Override
                public void repaint(long tm, int x, int y, int width, int height) {
                    if (repainter != null) {
                        repainter.repaint(tm, x, y, width, height);
                    }
                }
            };
        } else {
            t = new JTextField() {

                Repainter repainter = new Repainter(this);

                @Override
                public void repaint(long tm, int x, int y, int width, int height) {
                    if (repainter != null) {
                        repainter.repaint(tm, x, y, width, height);
                    }
                }
            };
        /*
                ((JTextField)t).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (cmp instanceof com.codename1.ui.TextField) {
                            final com.codename1.ui.TextField tf = (com.codename1.ui.TextField)cmp;
                            if (tf.getDoneListener() != null) {
                                Display.getInstance().callSerially(new Runnable() {
                                    public void run() {
                                        if (tf.getDoneListener() != null) {
                                            tf.fireDoneEvent();
                                        }
                                    }
                                });
                            }
                        }
                    }
                    
                });
                */
        }
        swingT = t;
        textCmp = swingT;
    } else {
        // Forward references so that we can access the scroll pane and its
        // repainter from inside the JTextArea.
        final Repainter[] fRepainter = new Repainter[1];
        final JScrollPane[] fPane = new JScrollPane[1];
        final com.codename1.ui.TextArea ta = (com.codename1.ui.TextArea) cmp;
        JTextArea t = new JTextArea() {

            @Override
            public void repaint(long tm, int x, int y, int width, int height) {
                // enough.
                if (fRepainter[0] != null && fPane[0] != null) {
                    Point p = SwingUtilities.convertPoint(this, x, y, fPane[0]);
                    fRepainter[0].repaint(tm, p.x, p.y, width, height);
                }
            }
        };
        t.setWrapStyleWord(true);
        t.setLineWrap(true);
        swingT = t;
        JScrollPane pane = new JScrollPane(swingT) {

            Repainter repainter = new Repainter(this);

            {
                fRepainter[0] = repainter;
            }

            @Override
            public void repaint(long tm, int x, int y, int width, int height) {
                if (repainter != null) {
                    repainter.repaint(tm, x, y, width, height);
                }
            }
        };
        fPane[0] = pane;
        if (ta.isGrowByContent()) {
            pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        }
        pane.setBorder(null);
        pane.setOpaque(false);
        pane.getViewport().setOpaque(false);
        // Without these scrollbars, it seems terribly difficult
        // to work with TextAreas that contain more text than can fit.
        // Commenting these out for better usability - at least on OS X.
        // pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        // pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textCmp = pane;
    }
    if (cmp.isRTL()) {
        textCmp.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }
    DefaultCaret caret = (DefaultCaret) swingT.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    swingT.setFocusTraversalKeysEnabled(false);
    TextEditUtil.setCurrentEditComponent(cmp);
    final javax.swing.text.JTextComponent txt = swingT;
    txt.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_TAB) {
                if (e.isShiftDown()) {
                    TextEditUtil.editPrevTextArea();
                } else {
                    TextEditUtil.editNextTextArea();
                }
            }
        }
    });
    // swingT.setBorder(null);
    swingT.setOpaque(false);
    swingT.setForeground(new Color(cmp.getUnselectedStyle().getFgColor()));
    swingT.setCaretColor(new Color(cmp.getUnselectedStyle().getFgColor()));
    final javax.swing.text.JTextComponent tf = swingT;
    if (keyCode > 0) {
        text += ((char) keyCode);
        setText(tf, text);
        setCaretPosition(tf, text.length());
        if (cmp instanceof com.codename1.ui.TextField) {
            ((com.codename1.ui.TextField) cmp).setText(getText(tf));
        }
    } else {
        setText(tf, text);
    }
    textCmp.setBorder(null);
    textCmp.setOpaque(false);
    canvas.add(textCmp);
    int marginTop = cmp.getSelectedStyle().getPadding(Component.TOP);
    int marginLeft = cmp.getSelectedStyle().getPadding(Component.LEFT);
    int marginRight = cmp.getSelectedStyle().getPadding(Component.RIGHT);
    int marginBottom = cmp.getSelectedStyle().getPadding(Component.BOTTOM);
    if (getSkin() != null) {
        textCmp.setBounds((int) ((cmp.getAbsoluteX() + cmp.getScrollX() + getScreenCoordinates().x + canvas.x + marginLeft) * zoomLevel), (int) ((cmp.getAbsoluteY() + cmp.getScrollY() + getScreenCoordinates().y + canvas.y + marginTop) * zoomLevel), (int) ((cmp.getWidth() - marginLeft - marginRight) * zoomLevel), (int) ((cmp.getHeight() - marginTop - marginBottom) * zoomLevel));
        // System.out.println("Set bounds to "+textCmp.getBounds());
        java.awt.Font f = font(cmp.getStyle().getFont().getNativeFont());
        tf.setFont(f.deriveFont(f.getSize2D() * zoomLevel));
    } else {
        textCmp.setBounds(cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft, cmp.getAbsoluteY() + cmp.getScrollY() + marginTop, cmp.getWidth() - marginRight - marginLeft, cmp.getHeight() - marginTop - marginBottom);
        // System.out.println("Set bounds to "+textCmp.getBounds());
        tf.setFont(font(cmp.getStyle().getFont().getNativeFont()));
    }
    if (tf instanceof JPasswordField && tf.getFont() != null && tf.getFont().getFontName().contains("Roboto")) {
        java.awt.Font fallback = new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, tf.getFont().getSize());
        tf.setFont(fallback);
    }
    setCaretPosition(tf, getText(tf).length());
    // Windows Tablet Show Virtual Keyboard
    // REf https://stackoverflow.com/a/25783041/2935174
    final String sysroot = System.getenv("SystemRoot");
    String tabTipExe = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";
    if (exposeFilesystem) {
        final boolean useTabTip = "tabtip".equalsIgnoreCase(Display.getInstance().getProperty("javase.win.vkb", "tabtip"));
        if (new File(tabTipExe).exists()) {
            try {
                if (useTabTip) {
                    // System.out.println("Opening TabTip");
                    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", tabTipExe);
                    tabTipProcess = pb.start();
                } else {
                    // System.out.println("Opening OSK");
                    ProcessBuilder pb = new ProcessBuilder(sysroot + "/system32/osk.exe");
                    tabTipProcess = pb.start();
                }
            } catch (Exception e) {
                System.err.println("Failed to open VKB: " + e.getMessage());
            }
            tf.addFocusListener(new FocusListener() {

                @Override
                public void focusLost(FocusEvent arg0) {
                    // System.out.println("Lost focus...");
                    try {
                        if (tabTipProcess != null) {
                            tabTipProcess.destroy();
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (useTabTip) {
                            Runtime.getRuntime().exec("cmd /c taskkill /IM TabTip.exe");
                        } else {
                            Runtime.getRuntime().exec("cmd /c taskkill /IM osk.exe");
                        }
                    } catch (IOException e) {
                        System.err.println("Problem closing VKB: " + e.getMessage());
                    }
                }

                @Override
                public void focusGained(FocusEvent arg0) {
                }
            });
        }
    }
    tf.requestFocus();
    tf.setSelectionStart(0);
    tf.setSelectionEnd(0);
    class Listener implements ActionListener, FocusListener, KeyListener, TextListener, Runnable, DocumentListener, EditingInProgress {

        private final JTextComponent textCmp;

        private final JComponent swingComponentToRemove;

        private boolean performed;

        private boolean fireDone;

        Listener(JTextComponent textCmp, JComponent swingComponentToRemove) {
            this.textCmp = textCmp;
            this.swingComponentToRemove = swingComponentToRemove;
            if (textCmp instanceof JTextArea) {
                if (((com.codename1.ui.TextArea) cmp).getDoneListener() != null) {
                    InputMap input = textCmp.getInputMap();
                    KeyStroke enter = KeyStroke.getKeyStroke("ENTER");
                    KeyStroke shiftEnter = KeyStroke.getKeyStroke("shift ENTER");
                    // input.get(enter)) = "insert-break"
                    input.put(shiftEnter, "insert-break");
                    input.put(enter, "text-submit");
                    ActionMap actions = textCmp.getActionMap();
                    actions.put("text-submit", new AbstractAction() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            fireDone = true;
                            Listener.this.actionPerformed(null);
                        }
                    });
                }
            }
        }

        public void run() {
            while (swingComponentToRemove.getParent() != null) {
                synchronized (this) {
                    try {
                        wait(20);
                    } catch (InterruptedException ex) {
                    }
                }
            }
            EventQueue.invokeLater(new Runnable() {

                public void run() {
                    actionPerformed(null);
                }
            });
        }

        public void actionPerformed(ActionEvent e) {
            if (performed) {
                return;
            }
            performed = true;
            String txt = getText(tf);
            if (testRecorder != null) {
                testRecorder.editTextFieldCompleted(cmp, txt);
            }
            Display.getInstance().onEditingComplete(cmp, txt);
            if (e != null && cmp instanceof com.codename1.ui.TextField || fireDone) {
                final com.codename1.ui.TextArea cn1Tf = (com.codename1.ui.TextArea) cmp;
                if (cmp != null && cn1Tf.getDoneListener() != null) {
                    cn1Tf.fireDoneEvent();
                }
            }
            if (tf instanceof JTextField) {
                ((JTextField) tf).removeActionListener(this);
            }
            ((JTextComponent) tf).getDocument().removeDocumentListener(this);
            tf.removeFocusListener(this);
            canvas.remove(swingComponentToRemove);
            editingInProgress = null;
            currentlyEditingField = null;
            synchronized (this) {
                notify();
            }
            canvas.repaint();
            if (invokeAfter != null) {
                for (Runnable r : invokeAfter) {
                    r.run();
                }
                invokeAfter = null;
            }
        }

        public void focusGained(FocusEvent e) {
            setCaretPosition(tf, getText(tf).length());
        }

        public void focusLost(FocusEvent e) {
            actionPerformed(null);
        }

        public void keyTyped(KeyEvent e) {
            String t = getText(tf);
            if (t.length() >= ((TextArea) cmp).getMaxSize()) {
                e.consume();
            }
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                if (tf instanceof JTextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) >= getText(tf).length() - 1) {
                        actionPerformed(null);
                    }
                }
                return;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                if (tf instanceof JTextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) <= 2) {
                        actionPerformed(null);
                    }
                }
                return;
            }
        }

        public void textValueChanged(TextEvent e) {
            // if (cmp instanceof com.codename1.ui.TextField) {
            updateText();
        // }
        }

        private void updateText() {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    // if(cmp instanceof com.codename1.ui.TextField) {
                    ((com.codename1.ui.TextArea) cmp).setText(getText(tf));
                // }
                }
            });
        }

        public void insertUpdate(DocumentEvent e) {
            updateText();
        }

        public void removeUpdate(DocumentEvent e) {
            updateText();
        }

        public void changedUpdate(DocumentEvent e) {
            updateText();
        }

        private ArrayList<Runnable> invokeAfter;

        @Override
        public void invokeAfter(Runnable r) {
            if (invokeAfter == null) {
                invokeAfter = new ArrayList<Runnable>();
            }
            invokeAfter.add(r);
        }

        @Override
        public void endEditing() {
            if (!EventQueue.isDispatchThread()) {
                EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        endEditing();
                    }
                });
                return;
            }
            actionPerformed(null);
        }
    }
    ;
    final Listener l = new Listener(tf, textCmp);
    if (tf instanceof JTextField) {
        ((JTextField) tf).addActionListener(l);
    }
    ((JTextComponent) tf).getDocument().addDocumentListener(l);
    tf.addKeyListener(l);
    tf.addFocusListener(l);
    if (simulateAndroidKeyboard) {
        java.util.Timer t = new java.util.Timer();
        TimerTask tt = new TimerTask() {

            @Override
            public void run() {
                if (!Display.getInstance().isEdt()) {
                    Display.getInstance().callSerially(this);
                    return;
                }
                if (tf.getParent() != null) {
                    final int height = getScreenCoordinates().height;
                    JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height / 2);
                    new UITimer(new Runnable() {

                        public void run() {
                            if (tf.getParent() != null) {
                                new UITimer(this).schedule(100, false, Display.getInstance().getCurrent());
                            } else {
                                JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height);
                            }
                        }
                    }).schedule(100, false, Display.getInstance().getCurrent());
                }
            }
        };
        t.schedule(tt, 300);
    }
    editingInProgress = l;
    currentlyEditingField = cmp;
    new Thread(l).start();
}
Also used : TextArea(com.codename1.ui.TextArea) Rectangle(java.awt.Rectangle) JTextComponent(javax.swing.text.JTextComponent) Timer(java.util.Timer) AttributedString(java.text.AttributedString) DefaultCaret(javax.swing.text.DefaultCaret) FontRenderContext(java.awt.font.FontRenderContext) Color(java.awt.Color) java.util(java.util) EmptyBorder(javax.swing.border.EmptyBorder) TextArea(com.codename1.ui.TextArea) UITimer(com.codename1.ui.util.UITimer) Font(com.codename1.ui.Font) Point(java.awt.Point) JTextComponent(javax.swing.text.JTextComponent) Point(java.awt.Point) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) LineUnavailableException(javax.sound.sampled.LineUnavailableException) javax.swing(javax.swing) UITimer(com.codename1.ui.util.UITimer) Timer(java.util.Timer) java.awt(java.awt)

Aggregations

Style (com.codename1.ui.plaf.Style)15 Font (com.codename1.ui.Font)8 ArrayList (java.util.ArrayList)5 ComponentImage (ca.weblite.shared.components.ComponentImage)4 Image (com.codename1.ui.Image)4 Point (java.awt.Point)4 Hashtable (java.util.Hashtable)4 MultiButton (com.codename1.components.MultiButton)3 SpanButton (com.codename1.components.SpanButton)3 EventObject (java.util.EventObject)3 List (java.util.List)3 Vector (java.util.Vector)3 SpanLabel (com.codename1.components.SpanLabel)2 BadgeUIID (com.codename1.rad.attributes.BadgeUIID)2 IconUIID (com.codename1.rad.attributes.IconUIID)2 UIID (com.codename1.rad.attributes.UIID)2 Button (com.codename1.ui.Button)2 TextArea (com.codename1.ui.TextArea)2 BorderLayout (com.codename1.ui.layouts.BorderLayout)2 UIManager (com.codename1.ui.plaf.UIManager)2