001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import java.awt.Component;
005import java.awt.Dimension;
006import java.awt.Toolkit;
007import java.awt.event.MouseAdapter;
008import java.awt.event.MouseEvent;
009import java.beans.PropertyChangeEvent;
010import java.beans.PropertyChangeListener;
011import java.util.ArrayList;
012import java.util.Arrays;
013import java.util.Collection;
014import java.util.List;
015
016import javax.accessibility.Accessible;
017import javax.swing.ComboBoxModel;
018import javax.swing.DefaultComboBoxModel;
019import javax.swing.JComboBox;
020import javax.swing.JList;
021import javax.swing.plaf.basic.ComboPopup;
022import javax.swing.text.JTextComponent;
023
024/**
025 * Class overriding each {@link JComboBox} in JOSM to control consistently the number of displayed items at once.<br>
026 * This is needed because of the default Java behaviour that may display the top-down list off the screen (see #7917).
027 * @param <E> the type of the elements of this combo box
028 *
029 * @since 5429 (creation)
030 * @since 7015 (generics for Java 7)
031 */
032public class JosmComboBox<E> extends JComboBox<E> {
033
034    /**
035     * Creates a <code>JosmComboBox</code> with a default data model.
036     * The default data model is an empty list of objects.
037     * Use <code>addItem</code> to add items. By default the first item
038     * in the data model becomes selected.
039     *
040     * @see DefaultComboBoxModel
041     */
042    public JosmComboBox() {
043        init(null);
044    }
045
046    /**
047     * Creates a <code>JosmComboBox</code> with a default data model and
048     * the specified prototype display value.
049     * The default data model is an empty list of objects.
050     * Use <code>addItem</code> to add items. By default the first item
051     * in the data model becomes selected.
052     *
053     * @param prototypeDisplayValue the <code>Object</code> used to compute
054     *      the maximum number of elements to be displayed at once before
055     *      displaying a scroll bar
056     *
057     * @see DefaultComboBoxModel
058     * @since 5450
059     */
060    public JosmComboBox(E prototypeDisplayValue) {
061        init(prototypeDisplayValue);
062    }
063
064    /**
065     * Creates a <code>JosmComboBox</code> that takes its items from an
066     * existing <code>ComboBoxModel</code>. Since the
067     * <code>ComboBoxModel</code> is provided, a combo box created using
068     * this constructor does not create a default combo box model and
069     * may impact how the insert, remove and add methods behave.
070     *
071     * @param aModel the <code>ComboBoxModel</code> that provides the
072     *      displayed list of items
073     * @see DefaultComboBoxModel
074     */
075    public JosmComboBox(ComboBoxModel<E> aModel) {
076        super(aModel);
077        List<E> list = new ArrayList<>(aModel.getSize());
078        for (int i = 0; i<aModel.getSize(); i++) {
079            list.add(aModel.getElementAt(i));
080        }
081        init(findPrototypeDisplayValue(list));
082    }
083
084    /**
085     * Creates a <code>JosmComboBox</code> 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     * @see DefaultComboBoxModel
091     */
092    public JosmComboBox(E[] items) {
093        super(items);
094        init(findPrototypeDisplayValue(Arrays.asList(items)));
095    }
096
097    /**
098     * Finds the prototype display value to use among the given possible candidates.
099     * @param possibleValues The possible candidates that will be iterated.
100     * @return The value that needs the largest display height on screen.
101     * @since 5558
102     */
103    protected final E findPrototypeDisplayValue(Collection<E> possibleValues) {
104        E result = null;
105        int maxHeight = -1;
106        if (possibleValues != null) {
107            // Remind old prototype to restore it later
108            E oldPrototype = getPrototypeDisplayValue();
109            // Get internal JList to directly call the renderer
110            JList<E> list = getList();
111            try {
112                // Index to give to renderer
113                int i = 0;
114                for (E value : possibleValues) {
115                    if (value != null) {
116                        // With a "classic" renderer, we could call setPrototypeDisplayValue(value) + getPreferredSize()
117                        // but not with TaggingPreset custom renderer that return a dummy height if index is equal to -1
118                        // So we explicitely call the renderer by simulating a correct index for the current value
119                        Component c = getRenderer().getListCellRendererComponent(list, value, i, true, true);
120                        if (c != null) {
121                            // Get the real preferred size for the current value
122                            Dimension dim = c.getPreferredSize();
123                            if (dim.height > maxHeight) {
124                                // Larger ? This is our new prototype
125                                maxHeight = dim.height;
126                                result = value;
127                            }
128                        }
129                    }
130                    i++;
131                }
132            } finally {
133                // Restore original prototype
134                setPrototypeDisplayValue(oldPrototype);
135            }
136        }
137        return result;
138    }
139
140    @SuppressWarnings("unchecked")
141    protected final JList<E> getList() {
142        for (int i = 0; i < getUI().getAccessibleChildrenCount(this); i++) {
143            Accessible child = getUI().getAccessibleChild(this, i);
144            if (child instanceof ComboPopup) {
145                return ((ComboPopup)child).getList();
146            }
147        }
148        return null;
149    }
150
151    protected final void init(E prototype) {
152        if (prototype != null) {
153            setPrototypeDisplayValue(prototype);
154            int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
155            // Compute maximum number of visible items based on the preferred size of the combo box.
156            // This assumes that items have the same height as the combo box, which is not granted by the look and feel
157            int maxsize = (screenHeight/getPreferredSize().height) / 2;
158            // If possible, adjust the maximum number of items with the real height of items
159            // It is not granted this works on every platform (tested OK on Windows)
160            JList<E> list = getList();
161            if (list != null) {
162                if (!prototype.equals(list.getPrototypeCellValue())) {
163                    list.setPrototypeCellValue(prototype);
164                }
165                int height = list.getFixedCellHeight();
166                if (height > 0) {
167                    maxsize = (screenHeight/height) / 2;
168                }
169            }
170            setMaximumRowCount(Math.max(getMaximumRowCount(), maxsize));
171        }
172        // Handle text contextual menus for editable comboboxes
173        ContextMenuHandler handler = new ContextMenuHandler();
174        addPropertyChangeListener("editable", handler);
175        addPropertyChangeListener("editor", handler);
176    }
177
178    protected class ContextMenuHandler extends MouseAdapter implements PropertyChangeListener {
179
180        private JTextComponent component;
181        private PopupMenuLauncher launcher;
182
183        @Override public void propertyChange(PropertyChangeEvent evt) {
184            if ("editable".equals(evt.getPropertyName())) {
185                if (evt.getNewValue().equals(true)) {
186                    enableMenu();
187                } else {
188                    disableMenu();
189                }
190            } else if ("editor".equals(evt.getPropertyName())) {
191                disableMenu();
192                if (isEditable()) {
193                    enableMenu();
194                }
195            }
196        }
197
198        private void enableMenu() {
199            if (launcher == null && editor != null) {
200                Component editorComponent = editor.getEditorComponent();
201                if (editorComponent instanceof JTextComponent) {
202                    component = (JTextComponent) editorComponent;
203                    component.addMouseListener(this);
204                    launcher = TextContextualPopupMenu.enableMenuFor(component);
205                }
206            }
207        }
208
209        private void disableMenu() {
210            if (launcher != null) {
211                TextContextualPopupMenu.disableMenuFor(component, launcher);
212                launcher = null;
213                component.removeMouseListener(this);
214                component = null;
215            }
216        }
217
218        @Override
219        public void mousePressed(MouseEvent e) {
220            processEvent(e);
221        }
222
223        @Override
224        public void mouseReleased(MouseEvent e) {
225            processEvent(e);
226        }
227
228        private void processEvent(MouseEvent e) {
229            if (launcher != null && !e.isPopupTrigger() && launcher.getMenu().isShowing()) {
230                launcher.getMenu().setVisible(false);
231            }
232        }
233    }
234
235    /**
236     * Reinitializes this {@link JosmComboBox} to the specified values. This may needed if a custom renderer is used.
237     * @param values The values displayed in the combo box.
238     * @since 5558
239     */
240    public final void reinitialize(Collection<E> values) {
241        init(findPrototypeDisplayValue(values));
242    }
243}