001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import java.awt.Color;
005import java.awt.ComponentOrientation;
006import java.awt.Font;
007import java.awt.FontMetrics;
008import java.awt.Graphics;
009import java.awt.Graphics2D;
010import java.awt.Insets;
011import java.awt.Point;
012import java.awt.RenderingHints;
013import java.awt.event.ComponentEvent;
014import java.awt.event.ComponentListener;
015import java.awt.event.FocusEvent;
016import java.awt.event.FocusListener;
017import java.beans.PropertyChangeEvent;
018import java.beans.PropertyChangeListener;
019
020import javax.swing.Icon;
021import javax.swing.JTextField;
022import javax.swing.RepaintManager;
023import javax.swing.JMenuItem;
024import javax.swing.JPopupMenu;
025import javax.swing.UIManager;
026import javax.swing.text.BadLocationException;
027import javax.swing.text.Document;
028
029import org.openstreetmap.josm.gui.MainApplication;
030import org.openstreetmap.josm.gui.MapFrame;
031import org.openstreetmap.josm.tools.Destroyable;
032import org.openstreetmap.josm.tools.Logging;
033import org.openstreetmap.josm.tools.Utils;
034
035/**
036 * Subclass of {@link JTextField} that:<ul>
037 * <li>adds a "native" context menu (undo/redo/cut/copy/paste/select all)</li>
038 * <li>adds an optional "hint" displayed when no text has been entered</li>
039 * <li>disables the global advanced key press detector when focused</li>
040 * <li>implements a workaround to <a href="https://bugs.openjdk.java.net/browse/JDK-6322854">JDK bug 6322854</a></li>
041 * </ul><br>This class must be used everywhere in core and plugins instead of {@code JTextField}.
042 * @since 5886
043 */
044public class JosmTextField extends JTextField implements Destroyable, ComponentListener, FocusListener, PropertyChangeListener {
045
046    private final PopupMenuLauncher launcher;
047    private String hint;
048    private Icon icon;
049    private Point iconPos;
050    private Insets originalMargin;
051    private OrientationAction orientationAction;
052
053    /**
054     * Constructs a new <code>JosmTextField</code> that uses the given text
055     * storage model and the given number of columns.
056     * This is the constructor through which the other constructors feed.
057     * If the document is <code>null</code>, a default model is created.
058     *
059     * @param doc  the text storage to use; if this is <code>null</code>,
060     *      a default will be provided by calling the
061     *      <code>createDefaultModel</code> method
062     * @param text  the initial string to display, or <code>null</code>
063     * @param columns  the number of columns to use to calculate
064     *   the preferred width &gt;= 0; if <code>columns</code>
065     *   is set to zero, the preferred width will be whatever
066     *   naturally results from the component implementation
067     * @throws IllegalArgumentException if <code>columns</code> &lt; 0
068     */
069    public JosmTextField(Document doc, String text, int columns) {
070        this(doc, text, columns, true);
071    }
072
073    /**
074     * Constructs a new <code>JosmTextField</code> that uses the given text
075     * storage model and the given number of columns.
076     * This is the constructor through which the other constructors feed.
077     * If the document is <code>null</code>, a default model is created.
078     *
079     * @param doc  the text storage to use; if this is <code>null</code>,
080     *      a default will be provided by calling the
081     *      <code>createDefaultModel</code> method
082     * @param text  the initial string to display, or <code>null</code>
083     * @param columns  the number of columns to use to calculate
084     *   the preferred width &gt;= 0; if <code>columns</code>
085     *   is set to zero, the preferred width will be whatever
086     *   naturally results from the component implementation
087     * @param undoRedo Enables or not Undo/Redo feature. Not recommended for table cell editors, unless each cell provides its own editor
088     * @throws IllegalArgumentException if <code>columns</code> &lt; 0
089     */
090    public JosmTextField(Document doc, String text, int columns, boolean undoRedo) {
091        super(doc, text, columns);
092        launcher = TextContextualPopupMenu.enableMenuFor(this, undoRedo);
093
094        // There seems to be a bug in Swing 8 that components with Bidi enabled are smaller than
095        // without. (eg. 23px vs 21px in height, maybe a font thing).  Usually Bidi starts disabled
096        // but gets enabled whenever RTL text is loaded.  To avoid trashing the layout we enable
097        // Bidi by default.  See also {@link #drawHint()}.
098        getDocument().putProperty("i18n", Boolean.TRUE);
099
100        // the menu and hotkey to change text orientation
101        orientationAction = new OrientationAction(this);
102        orientationAction.addPropertyChangeListener(this);
103        JPopupMenu menu = launcher.getMenu();
104        menu.addSeparator();
105        menu.add(new JMenuItem(orientationAction));
106        getInputMap().put(OrientationAction.getShortcutKey(), orientationAction);
107
108        // Fix minimum size when columns are specified
109        if (columns > 0) {
110            setMinimumSize(getPreferredSize());
111        }
112        addFocusListener(this);
113        addComponentListener(this);
114        // Workaround for Java bug 6322854
115        JosmPasswordField.workaroundJdkBug6322854(this);
116        originalMargin = getMargin();
117    }
118
119    /**
120     * Constructs a new <code>JosmTextField</code> initialized with the
121     * specified text and columns.  A default model is created.
122     *
123     * @param text the text to be displayed, or <code>null</code>
124     * @param columns  the number of columns to use to calculate
125     *   the preferred width; if columns is set to zero, the
126     *   preferred width will be whatever naturally results from
127     *   the component implementation
128     */
129    public JosmTextField(String text, int columns) {
130        this(null, text, columns);
131    }
132
133    /**
134     * Constructs a new <code>JosmTextField</code> initialized with the
135     * specified text. A default model is created and the number of
136     * columns is 0.
137     *
138     * @param text the text to be displayed, or <code>null</code>
139     */
140    public JosmTextField(String text) {
141        this(null, text, 0);
142    }
143
144    /**
145     * Constructs a new empty <code>JosmTextField</code> with the specified
146     * number of columns.
147     * A default model is created and the initial string is set to
148     * <code>null</code>.
149     *
150     * @param columns  the number of columns to use to calculate
151     *   the preferred width; if columns is set to zero, the
152     *   preferred width will be whatever naturally results from
153     *   the component implementation
154     */
155    public JosmTextField(int columns) {
156        this(null, null, columns);
157    }
158
159    /**
160     * Constructs a new <code>JosmTextField</code>.  A default model is created,
161     * the initial string is <code>null</code>,
162     * and the number of columns is set to 0.
163     */
164    public JosmTextField() {
165        this(null, null, 0);
166    }
167
168    /**
169     * Replies the hint displayed when no text has been entered.
170     * @return the hint
171     * @since 7505
172     */
173    public final String getHint() {
174        return hint;
175    }
176
177    /**
178     * Sets the hint to display when no text has been entered.
179     * @param hint the hint to set
180     * @return the old hint
181     * @since 18221 (signature)
182     */
183    public String setHint(String hint) {
184        String old = this.hint;
185        this.hint = hint;
186        return old;
187    }
188
189    /**
190     * Return true if the textfield should display the hint text.
191     *
192     * @return whether to display the hint text
193     * @since 18221
194     */
195    public boolean displayHint() {
196        return !Utils.isEmpty(hint) && getText().isEmpty() && !isFocusOwner();
197    }
198
199    /**
200     * Returns the icon to display
201     * @return the icon to display
202     * @since 17768
203     */
204    public Icon getIcon() {
205        return icon;
206    }
207
208    /**
209     * Sets the icon to display
210     * @param icon the icon to set
211     * @since 17768
212     */
213    public void setIcon(Icon icon) {
214        this.icon = icon;
215        if (icon == null) {
216            setMargin(originalMargin);
217        }
218        positionIcon();
219    }
220
221    private void positionIcon() {
222        if (icon != null) {
223            Insets margin = (Insets) originalMargin.clone();
224            int hGap = (getHeight() - icon.getIconHeight()) / 2;
225            if (getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT) {
226                margin.right += icon.getIconWidth() + 2 * hGap;
227                iconPos = new Point(getWidth() - icon.getIconWidth() - hGap, hGap);
228            } else {
229                margin.left += icon.getIconWidth() + 2 * hGap;
230                iconPos = new Point(hGap, hGap);
231            }
232            setMargin(margin);
233        }
234    }
235
236    @Override
237    public void setComponentOrientation(ComponentOrientation o) {
238        if (o.isLeftToRight() != getComponentOrientation().isLeftToRight()) {
239            super.setComponentOrientation(o);
240            positionIcon();
241        }
242    }
243
244    /**
245     * Empties the internal undo manager.
246     * @since 14977
247     */
248    public final void discardAllUndoableEdits() {
249        launcher.discardAllUndoableEdits();
250    }
251
252    /**
253     * Returns the color for hint texts.
254     * @return the Color for hint texts
255     */
256    public static Color getHintTextColor() {
257        Color color = UIManager.getColor("TextField[Disabled].textForeground"); // Nimbus?
258        if (color == null)
259            color = UIManager.getColor("TextField.inactiveForeground");
260        if (color == null)
261            color = Color.GRAY;
262        return color;
263    }
264
265    /**
266     * Returns the font for hint texts.
267     * @return the font for hint texts
268     */
269    public static Font getHintFont() {
270        return UIManager.getFont("TextField.font");
271    }
272
273    @Override
274    public void paintComponent(Graphics g) {
275        super.paintComponent(g);
276        if (icon != null) {
277            icon.paintIcon(this, g, iconPos.x, iconPos.y);
278        }
279        if (displayHint()) {
280            // Logging.debug("drawing textfield hint: {0}", getHint());
281            drawHint(g);
282        }
283    }
284
285    /**
286     * Draws the hint text over the editor component.
287     *
288     * @param g the graphics context
289     */
290    public void drawHint(Graphics g) {
291        int x;
292        try {
293            x = (int) Math.round(modelToView2D(0).getX());
294        } catch (BadLocationException exc) {
295            Logging.trace(exc);
296            return; // can't happen
297        }
298        // Taken from http://stackoverflow.com/a/24571681/2257172
299        if (g instanceof Graphics2D) {
300            ((Graphics2D) g).setRenderingHint(
301                    RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
302        }
303        g.setColor(getHintTextColor());
304        g.setFont(getHintFont());
305        if (getComponentOrientation().isLeftToRight()) {
306            g.drawString(getHint(), x, getBaseline(getWidth(), getHeight()));
307        } else {
308            FontMetrics metrics = g.getFontMetrics(g.getFont());
309            int dx = metrics.stringWidth(getHint());
310            g.drawString(getHint(), x - dx, getBaseline(getWidth(), getHeight()));
311        }
312        // Needed to avoid endless repaint loop if we accidentally draw over the insets.  This may
313        // easily happen because a change in text orientation invalidates the textfield and
314        // following that the preferred size gets smaller. (Bug in Swing?)
315        RepaintManager.currentManager(this).markCompletelyClean(this);
316    }
317
318    @Override
319    public void focusGained(FocusEvent e) {
320        MapFrame map = MainApplication.getMap();
321        if (map != null) {
322            map.keyDetector.setEnabled(false);
323        }
324        if (e != null && e.getOppositeComponent() != null) {
325            // Select all characters when the change of focus occurs inside JOSM only.
326            // When switching from another application, it is annoying, see #13747
327            selectAll();
328        }
329        positionIcon();
330        repaint(); // get rid of hint
331    }
332
333    @Override
334    public void focusLost(FocusEvent e) {
335        MapFrame map = MainApplication.getMap();
336        if (map != null) {
337            map.keyDetector.setEnabled(true);
338        }
339        repaint(); // paint hint
340    }
341
342    @Override
343    public void destroy() {
344        removeFocusListener(this);
345        TextContextualPopupMenu.disableMenuFor(this, launcher);
346    }
347
348    @Override
349    public void componentResized(ComponentEvent e) {
350        positionIcon();
351    }
352
353    @Override
354    public void componentMoved(ComponentEvent e) {
355    }
356
357    @Override
358    public void componentShown(ComponentEvent e) {
359    }
360
361    @Override
362    public void componentHidden(ComponentEvent e) {
363    }
364
365    @Override
366    public void propertyChange(PropertyChangeEvent evt) {
367        // command from the menu / shortcut key
368        if ("orientationAction".equals(evt.getPropertyName())) {
369            setComponentOrientation((ComponentOrientation) evt.getNewValue());
370        }
371    }
372}