001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004
005import java.awt.Component;
006import java.awt.ComponentOrientation;
007import java.awt.Dimension;
008import java.awt.Graphics;
009import java.awt.GraphicsConfiguration;
010import java.awt.Insets;
011import java.awt.Point;
012import java.awt.Rectangle;
013import java.awt.Toolkit;
014import java.beans.PropertyChangeEvent;
015import java.beans.PropertyChangeListener;
016
017import javax.swing.ComboBoxEditor;
018import javax.swing.JComboBox;
019import javax.swing.JList;
020import javax.swing.JScrollPane;
021import javax.swing.JTextField;
022import javax.swing.ListCellRenderer;
023import javax.swing.border.Border;
024import javax.swing.event.PopupMenuEvent;
025import javax.swing.event.PopupMenuListener;
026import javax.swing.text.JTextComponent;
027
028import org.openstreetmap.josm.spi.preferences.Config;
029
030/**
031 * Base class for all comboboxes in JOSM.
032 * <p>
033 * This combobox will show as many rows as possible without covering the combox itself. It makes
034 * sure the list will never go outside the screen (see #7917). You may limit the number of rows
035 * shown with the configuration: {@code gui.combobox.maximum-row-count}.
036 * <p>
037 * This combobox uses a {@link JosmTextField} for its editor component.
038 *
039 * @param <E> the type of the elements of this combo box
040 * @since 5429 (creation)
041 * @since 7015 (generics for Java 7)
042 */
043public class JosmComboBox<E> extends JComboBox<E> implements PopupMenuListener, PropertyChangeListener {
044    /**
045     * Limits the number of rows that this combobox will show.
046     */
047    public static final String PROP_MAXIMUM_ROW_COUNT = "gui.combobox.maximum-row-count";
048
049    /** the configured maximum row count or null */
050    private Integer configMaximumRowCount;
051
052    /**
053     * The preferred height of the combobox when closed.  Use if the items in the list dropdown are
054     * taller than the item in the editor, as in some comboboxes in the preset dialog.  -1 to use
055     * the height of the tallest item in the list.
056     */
057    private int preferredHeight = -1;
058
059    /** greyed text to display in the editor when the selected value is empty */
060    private String hint;
061
062    /**
063     * Creates a {@code JosmComboBox} with a {@link JosmComboBoxModel} data model.
064     * The default data model is an empty list of objects.
065     * Use <code>addItem</code> to add items. By default the first item
066     * in the data model becomes selected.
067     */
068    public JosmComboBox() {
069        super(new JosmComboBoxModel<>());
070        init();
071    }
072
073    /**
074     * Creates a {@code JosmComboBox} that takes it items from an existing {@link JosmComboBoxModel}
075     * data model.
076     *
077     * @param aModel the model that provides the displayed list of items
078     */
079    public JosmComboBox(JosmComboBoxModel<E> aModel) {
080        super(aModel);
081        init();
082    }
083
084    /**
085     * Creates a {@code JosmComboBox} that contains the elements
086     * in the specified array. By default the first item in the array
087     * (and therefore the data model) becomes selected.
088     *
089     * @param items  an array of objects to insert into the combo box
090     */
091    public JosmComboBox(E[] items) {
092        super(new JosmComboBoxModel<>());
093        init();
094        for (E elem : items) {
095            getModel().addElement(elem);
096        }
097    }
098
099    private void init() {
100        configMaximumRowCount = Config.getPref().getInt(PROP_MAXIMUM_ROW_COUNT, 9999);
101        setEditor(new JosmComboBoxEditor());
102        // listen when the popup shows up so we can maximize its height
103        addPopupMenuListener(this);
104    }
105
106    /**
107     * Returns the {@link JosmComboBoxModel} currently used.
108     *
109     * @return the model or null
110     */
111    @Override
112    public JosmComboBoxModel<E> getModel() {
113        return (JosmComboBoxModel<E>) dataModel;
114    }
115
116    @Override
117    public void setEditor(ComboBoxEditor newEditor) {
118        if (editor != null) {
119            editor.getEditorComponent().removePropertyChangeListener(this);
120        }
121        super.setEditor(newEditor);
122        if (editor != null) {
123            // listen to orientation changes in the editor
124            editor.getEditorComponent().addPropertyChangeListener(this);
125        }
126    }
127
128    /**
129     * Returns the editor component
130     * @return the editor component
131     * @see ComboBoxEditor#getEditorComponent()
132     * @since 9484
133     */
134    public JosmTextField getEditorComponent() {
135        return (JosmTextField) (editor == null ? null : editor.getEditorComponent());
136    }
137
138    /**
139     * Returns the string representation of current edited item, or null.
140     * @return the string representation of current edited item, or null
141     * @since 18313
142     */
143    public String getEditorItemAsString() {
144        return editor != null && editor.getItem() != null ? editor.getItem().toString() : null;
145    }
146
147    /**
148     * Returns the text in the combobox editor.
149     * @return the text
150     * @see JTextComponent#getText
151     * @since 18173
152     */
153    public String getText() {
154        JosmTextField tf = getEditorComponent();
155        return tf == null ? null : tf.getText();
156    }
157
158    /**
159     * Sets the text in the combobox editor.
160     * @param value the text to set
161     * @see JTextComponent#setText
162     * @since 18173
163     */
164    public void setText(String value) {
165        JosmTextField tf = getEditorComponent();
166        if (tf != null)
167            tf.setText(value);
168    }
169
170    /**
171     * Selects an item and/or sets text
172     * <p>
173     * Selects the item whose {@code toString()} equals {@code text}. If an item could not be found,
174     * selects nothing and sets the text anyway.
175     *
176     * @param text the text to select and set
177     * @return the item or null
178     */
179    public E setSelectedItemText(String text) {
180        E item = getModel().find(text);
181        setSelectedItem(item);
182        if (text == null || !text.equals(getText()))
183            setText(text);
184        return item;
185    }
186
187    /* Hint handling */
188
189    /**
190     * Returns the hint text
191     * @return the hint text
192     */
193    public String getHint() {
194        return hint;
195    }
196
197    /**
198     * Sets the hint to display when no text has been entered.
199     *
200     * @param newHint the hint to set
201     * @return the old hint
202     * @since 18221
203     */
204    public String setHint(String newHint) {
205        String old = this.hint;
206        this.hint = newHint;
207        JosmTextField tf = getEditorComponent();
208        if (tf != null)
209            tf.setHint(newHint);
210        return old;
211    }
212
213    @Override
214    public void setComponentOrientation(ComponentOrientation o) {
215        if (o.isLeftToRight() != getComponentOrientation().isLeftToRight()) {
216            super.setComponentOrientation(o);
217            getEditorComponent().setComponentOrientation(o);
218            // the button doesn't move over without this
219            revalidate();
220        }
221    }
222
223    /**
224     * Return true if the combobox should display the hint text.
225     *
226     * @return whether to display the hint text
227     * @since 18221
228     */
229    public boolean displayHint() {
230        return !isEditable() && hint != null && !hint.isEmpty() && getText().isEmpty(); // && !isFocusOwner();
231    }
232
233    /**
234     * Overrides the calculated height.  See: {@link #setPreferredHeight(int)}.
235     *
236     * @since 18221
237     */
238    @Override
239    public Dimension getPreferredSize() {
240        Dimension d = super.getPreferredSize();
241        if (preferredHeight != -1)
242            d.height = preferredHeight;
243        return d;
244    }
245
246    /**
247     * Sets the preferred height of the combobox editor.
248     * <p>
249     * A combobox editor is automatically sized to accomodate the widest and the tallest items in
250     * the list.  In the Preset dialogs we show more of an item in the list than in the editor, so
251     * the editor becomes too big.  With this method we can set the editor height to a fixed value.
252     * <p>
253     * Set this to -1 to get the default behaviour back.
254     * <p>
255     * See also: #6157
256     *
257     * @param height the preferred height or -1
258     * @return the old preferred height
259     * @see #setPreferredSize
260     * @since 18221
261     */
262    public int setPreferredHeight(int height) {
263        int old = preferredHeight;
264        preferredHeight = height;
265        return old;
266    }
267
268    /**
269     * Get the dropdown list component
270     *
271     * @return the list or null
272     */
273    @SuppressWarnings("rawtypes")
274    public JList getList() {
275        Object popup = getUI().getAccessibleChild(this, 0);
276        if (popup instanceof javax.swing.plaf.basic.ComboPopup) {
277            return ((javax.swing.plaf.basic.ComboPopup) popup).getList();
278        }
279        return null;
280    }
281
282    /**
283     * Draw the hint text for read-only comboboxes.
284     * <p>
285     * The obvious way -- to call {@code setText(hint)} and {@code setForeground(gray)} on the
286     * {@code JLabel} returned by the list cell renderer -- unfortunately does not work out well
287     * because many UIs change the foreground color or the enabled state of the {@code JLabel} after
288     * the list cell renderer has returned ({@code BasicComboBoxUI}).  Other UIs don't honor the
289     * label color at all ({@code SynthLabelUI}).
290     * <p>
291     * We use the same approach as in {@link JosmTextField}. The only problem we face is to get the
292     * coordinates of the text inside the combobox.  Fortunately even read-only comboboxes have a
293     * (partially configured) editor component, although they don't use it.  We configure that editor
294     * just enough to call {@link JTextField#modelToView modelToView} and
295     * {@link javax.swing.JComponent#getBaseline getBaseline} on it, thus obtaining the text
296     * coordinates.
297     *
298     * @see javax.swing.plaf.basic.BasicComboBoxUI#paintCurrentValue
299     * @see javax.swing.plaf.synth.SynthLabelUI#paint
300     */
301    @Override
302    protected void paintComponent(Graphics g) {
303        super.paintComponent(g);
304        JosmTextField editor = getEditorComponent();
305        if (displayHint() && editor != null) {
306            if (editor.getSize().width == 0) {
307                Dimension dimen = getSize();
308                Insets insets = getInsets();
309                // a fake configuration not too far from reality
310                editor.setSize(dimen.width - insets.left - insets.right,
311                               dimen.height - insets.top - insets.bottom);
312            }
313            editor.drawHint(g);
314        }
315    }
316
317    /**
318     * Empties the internal undo manager, if any.
319     * <p>
320     * Used in the {@link org.openstreetmap.josm.gui.io.UploadDialog UploadDialog}.
321     * @since 14977
322     */
323    public final void discardAllUndoableEdits() {
324        getEditorComponent().discardAllUndoableEdits();
325    }
326
327    /**
328     * Limits the popup height.
329     * <p>
330     * Limits the popup height to the available screen space either below or above the combobox,
331     * whichever is bigger. To find the maximum number of rows that fit the screen, it does the
332     * reverse of the calculation done in
333     * {@link javax.swing.plaf.basic.BasicComboPopup#getPopupLocation}.
334     *
335     * @see javax.swing.plaf.basic.BasicComboBoxUI#getAccessibleChild
336     */
337    @Override
338    public void popupMenuWillBecomeVisible(PopupMenuEvent ev) {
339        // Get the combobox bounds.
340        Rectangle bounds = new Rectangle(getLocationOnScreen(), getSize());
341
342        // Get the screen bounds of the screen (of a multi-screen setup) we are on.
343        Rectangle screenBounds;
344        GraphicsConfiguration gc = getGraphicsConfiguration();
345        Toolkit toolkit = Toolkit.getDefaultToolkit();
346        if (gc != null) {
347            Insets screenInsets = toolkit.getScreenInsets(gc);
348            screenBounds = gc.getBounds();
349            screenBounds.x += screenInsets.left;
350            screenBounds.y += screenInsets.top;
351            screenBounds.width -= (screenInsets.left + screenInsets.right);
352            screenBounds.height -= (screenInsets.top + screenInsets.bottom);
353        } else {
354            screenBounds = new Rectangle(new Point(), toolkit.getScreenSize());
355        }
356        int freeAbove = bounds.y - screenBounds.y;
357        int freeBelow = (screenBounds.y + screenBounds.height) - (bounds.y + bounds.height);
358
359        try {
360            // First try an implementation-dependent method to get the exact number.
361            @SuppressWarnings("unchecked")
362            JList<E> jList = getList();
363
364            // Calculate the free space available on screen
365            Insets insets = jList.getInsets();
366            // A small fudge factor that accounts for the displacement of the popup relative to the
367            // combobox and the popup shadow.
368            int fudge = 4;
369            int free = Math.max(freeAbove, freeBelow) - (insets.top + insets.bottom) - fudge;
370            if (jList.getParent() instanceof JScrollPane) {
371                JScrollPane scroller = (JScrollPane) jList.getParent();
372                Border border = scroller.getViewportBorder();
373                if (border != null) {
374                    insets = border.getBorderInsets(null);
375                    free -= insets.top + insets.bottom;
376                }
377                border = scroller.getBorder();
378                if (border != null) {
379                    insets = border.getBorderInsets(null);
380                    free -= insets.top + insets.bottom;
381                }
382            }
383
384            // Calculate how many rows fit into the free space.  Rows may have variable heights.
385            int rowCount = Math.min(configMaximumRowCount, getItemCount());
386            ListCellRenderer<? super E> r = jList.getCellRenderer();  // must take this from list, not combo: flatlaf bug
387            int i;
388            int h = 0;
389            for (i = 0; i < rowCount; ++i) {
390                Component c = r.getListCellRendererComponent(jList, getModel().getElementAt(i), i, false, false);
391                h += c.getPreferredSize().height;
392                if (h >= free)
393                    break;
394            }
395            setMaximumRowCount(i);
396            // Logging.debug("free = {0}, h = {1}, i = {2}, bounds = {3}, screenBounds = {4}", free, h, i, bounds, screenBounds);
397        } catch (Exception ex) {
398            setMaximumRowCount(8); // the default
399        }
400    }
401
402    @Override
403    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
404        // Who cares?
405    }
406
407    @Override
408    public void popupMenuCanceled(PopupMenuEvent e) {
409        // Who cares?
410    }
411
412    @Override
413    public void propertyChange(PropertyChangeEvent evt) {
414        // follow our editor's orientation
415        if ("componentOrientation".equals(evt.getPropertyName())) {
416            setComponentOrientation((ComponentOrientation) evt.getNewValue());
417        }
418    }
419}