001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.dialogs;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.I18n.trc;
006
007import java.awt.Component;
008import java.awt.Dimension;
009import java.awt.event.KeyEvent;
010import java.awt.event.WindowEvent;
011import java.awt.event.WindowListener;
012import java.util.Arrays;
013import java.util.Collection;
014import java.util.Collections;
015import java.util.EnumSet;
016import java.util.List;
017import java.util.stream.Collectors;
018
019import javax.swing.BorderFactory;
020import javax.swing.GroupLayout;
021import javax.swing.JLabel;
022import javax.swing.JOptionPane;
023import javax.swing.JPanel;
024import javax.swing.KeyStroke;
025import javax.swing.border.EtchedBorder;
026import javax.swing.plaf.basic.BasicComboBoxEditor;
027
028import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
029import org.openstreetmap.josm.data.osm.PrimitiveId;
030import org.openstreetmap.josm.data.osm.SimplePrimitiveId;
031import org.openstreetmap.josm.gui.ExtendedDialog;
032import org.openstreetmap.josm.gui.Notification;
033import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils;
034import org.openstreetmap.josm.gui.widgets.HistoryComboBox;
035import org.openstreetmap.josm.gui.widgets.HtmlPanel;
036import org.openstreetmap.josm.gui.widgets.JosmTextField;
037import org.openstreetmap.josm.gui.widgets.OsmIdTextField;
038import org.openstreetmap.josm.gui.widgets.OsmPrimitiveTypesComboBox;
039import org.openstreetmap.josm.spi.preferences.Config;
040import org.openstreetmap.josm.tools.Logging;
041import org.openstreetmap.josm.tools.Utils;
042
043/**
044 * Dialog prompt to user to let him choose OSM primitives by specifying their type and IDs.
045 * @since 6448, split from DownloadObjectDialog
046 */
047public class OsmIdSelectionDialog extends ExtendedDialog implements WindowListener {
048
049    protected final JPanel panel = new JPanel();
050    protected final OsmPrimitiveTypesComboBox cbType = new OsmPrimitiveTypesComboBox();
051    protected final OsmIdTextField tfId = new OsmIdTextField();
052    protected final HistoryComboBox cbId = new HistoryComboBox();
053    protected final transient GroupLayout layout = new GroupLayout(panel);
054
055    /**
056     * Creates a new OsmIdSelectionDialog
057     * @param parent       The parent element that will be used for position and maximum size
058     * @param title        The text that will be shown in the window titlebar
059     * @param buttonTexts  String Array of the text that will appear on the buttons. The first button is the default one.
060     */
061    public OsmIdSelectionDialog(Component parent, String title, String... buttonTexts) {
062        super(parent, title, buttonTexts);
063    }
064
065    /**
066     * Creates a new OsmIdSelectionDialog
067     * @param parent The parent element that will be used for position and maximum size
068     * @param title The text that will be shown in the window titlebar
069     * @param buttonTexts String Array of the text that will appear on the buttons. The first button is the default one.
070     * @param modal Set it to {@code true} if you want the dialog to be modal
071     */
072    public OsmIdSelectionDialog(Component parent, String title, String[] buttonTexts, boolean modal) {
073        super(parent, title, buttonTexts, modal);
074    }
075
076    /**
077     * Creates a new OsmIdSelectionDialog
078     * @param parent The parent element that will be used for position and maximum size
079     * @param title The text that will be shown in the window titlebar
080     * @param buttonTexts String Array of the text that will appear on the buttons. The first button is the default one.
081     * @param modal Set it to {@code true} if you want the dialog to be modal
082     * @param disposeOnClose whether to call {@link #dispose} when closing the dialog
083     */
084    public OsmIdSelectionDialog(Component parent, String title, String[] buttonTexts, boolean modal, boolean disposeOnClose) {
085        super(parent, title, buttonTexts, modal, disposeOnClose);
086    }
087
088    protected void init() {
089        panel.setLayout(layout);
090        layout.setAutoCreateGaps(true);
091        layout.setAutoCreateContainerGaps(true);
092
093        JLabel lbl1 = new JLabel(tr("Object type:"));
094        lbl1.setLabelFor(cbType);
095
096        cbType.addItem(trc("osm object types", "mixed"));
097        cbType.setToolTipText(tr("Choose the OSM object type"));
098        JLabel lbl2 = new JLabel(tr("Object ID:"));
099        lbl2.setLabelFor(cbId);
100
101        cbId.setEditor(new BasicComboBoxEditor() {
102            @Override
103            protected JosmTextField createEditorComponent() {
104                return tfId;
105            }
106        });
107        cbId.setToolTipText(tr("Enter the ID of the object that should be downloaded"));
108        restorePrimitivesHistory(cbId);
109
110        // forward the enter key stroke to the download button
111        tfId.getKeymap().removeKeyStrokeBinding(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false));
112        tfId.setPreferredSize(new Dimension(400, tfId.getPreferredSize().height));
113
114        final String help1 = /* I18n: {0} and contains example strings not meant for translation. */
115                tr("Object IDs can be separated by comma or space, for instance: {0}",
116                        "<b>" + Utils.joinAsHtmlUnorderedList(Arrays.asList("1 2 5", "1,2,5")) + "</b>");
117        final String help2 = /* I18n: {0} and contains example strings not meant for translation. {1}=n, {2}=w, {3}=r. */
118                tr("In mixed mode, specify objects like this: {0}<br/>"
119                                + "({1} stands for <i>node</i>, {2} for <i>way</i>, and {3} for <i>relation</i>)",
120                        "<b>w123, n110, w12, r15</b>", "<b>n</b>", "<b>w</b>", "<b>r</b>");
121        final String help3 = /* I18n: {0} and contains example strings not meant for translation. */
122                tr("Ranges of object IDs are specified with a hyphen, for instance: {0}",
123                        "<b>" + Utils.joinAsHtmlUnorderedList(Arrays.asList("w1-5", "n30-37", "r501-5")) + "</b>");
124        HtmlPanel help = new HtmlPanel(help1 + "<br/>" + help2 + "<br/><br/>" + help3);
125        help.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
126
127        cbType.addItemListener(e -> {
128            tfId.setType(cbType.getType());
129            tfId.performValidation();
130        });
131
132        final GroupLayout.SequentialGroup sequentialGroup = layout.createSequentialGroup()
133                .addGroup(layout.createParallelGroup()
134                        .addComponent(lbl1)
135                        .addComponent(cbType, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
136                .addGroup(layout.createParallelGroup()
137                        .addComponent(lbl2)
138                        .addComponent(cbId, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE));
139
140        final GroupLayout.ParallelGroup parallelGroup = layout.createParallelGroup()
141                .addGroup(layout.createSequentialGroup()
142                        .addGroup(layout.createParallelGroup()
143                                .addComponent(lbl1)
144                                .addComponent(lbl2)
145                        )
146                        .addGroup(layout.createParallelGroup()
147                                .addComponent(cbType)
148                                .addComponent(cbId))
149                );
150
151        for (Component i : getComponentsBeforeHelp()) {
152            sequentialGroup.addComponent(i);
153            parallelGroup.addComponent(i);
154        }
155
156        layout.setVerticalGroup(sequentialGroup.addComponent(help));
157        layout.setHorizontalGroup(parallelGroup.addComponent(help));
158    }
159
160    /**
161     * Let subclasses add custom components between the id input field and the help text
162     * @return the collections to add
163     */
164    protected Collection<Component> getComponentsBeforeHelp() {
165        return Collections.emptySet();
166    }
167
168    /**
169     * Allows subclasses to specify a different continue button index. If this button is pressed, the history is updated.
170     * @return the button index
171     */
172    public int getContinueButtonIndex() {
173        return 1;
174    }
175
176    /**
177     * Restore the current history from the preferences
178     *
179     * @param cbHistory the {@link HistoryComboBox} to which the history is restored to
180     */
181    protected void restorePrimitivesHistory(HistoryComboBox cbHistory) {
182        cbHistory.getModel().prefs().load(getClass().getName() + ".primitivesHistory");
183    }
184
185    /**
186     * Remind the current history in the preferences
187     *
188     * @param cbHistory the {@link HistoryComboBox} of which to restore the history
189     */
190    protected void remindPrimitivesHistory(HistoryComboBox cbHistory) {
191        cbHistory.addCurrentItemToHistory();
192        cbHistory.getModel().prefs().save(getClass().getName() + ".primitivesHistory");
193    }
194
195    /**
196     * Gets the requested OSM object IDs.
197     *
198     * @return The list of requested OSM object IDs
199     */
200    public final List<PrimitiveId> getOsmIds() {
201        return tfId.getIds();
202    }
203
204    @Override
205    public void setupDialog() {
206        setContent(panel, false);
207        try {
208            cbType.setSelectedIndex(Config.getPref().getInt("downloadprimitive.lasttype", 0));
209        } catch (IllegalArgumentException e) {
210            cbType.setSelectedIndex(0);
211            Logging.warn(e);
212        }
213        tfId.setType(cbType.getType());
214        if (Config.getPref().getBoolean("downloadprimitive.autopaste", true)) {
215            tryToPasteFromClipboard(tfId, cbType);
216        }
217        setDefaultButton(getContinueButtonIndex());
218        addWindowListener(this);
219        super.setupDialog();
220    }
221
222    protected void tryToPasteFromClipboard(OsmIdTextField tfId, OsmPrimitiveTypesComboBox cbType) {
223        String buf = ClipboardUtils.getClipboardStringContent();
224        if (Utils.isEmpty(buf)) return;
225        final int maxPasteLength = Config.getPref().getInt("downloadprimitive.max-autopaste-length", 2000);
226        if (buf.length() > maxPasteLength) {
227            new Notification(tr("Clipboard has more than {0} characters. Not auto-pasting.\n" +
228                    "You may want to use Overpass instead.", maxPasteLength))
229                    .setIcon(JOptionPane.WARNING_MESSAGE)
230                    .show();
231            return;
232        }
233        final List<SimplePrimitiveId> ids = SimplePrimitiveId.fuzzyParse(buf);
234        if (!ids.isEmpty()) {
235            final String parsedText = ids.stream().map(x -> x.getType().getAPIName().charAt(0) + String.valueOf(x.getUniqueId()))
236                    .collect(Collectors.joining(", "));
237            tfId.tryToPasteFrom(parsedText);
238            final EnumSet<OsmPrimitiveType> types = ids.stream().map(SimplePrimitiveId::getType).collect(
239                    Collectors.toCollection(() -> EnumSet.noneOf(OsmPrimitiveType.class)));
240            if (types.size() == 1) {
241                // select corresponding type
242                cbType.setSelectedItem(types.iterator().next());
243            } else {
244                // select "mixed"
245                cbType.setSelectedIndex(3);
246            }
247        } else if (buf.matches("[\\d,v\\s]+")) {
248            //fallback solution for id1,id2,id3 format
249            tfId.tryToPasteFrom(buf);
250        }
251    }
252
253    @Override public void windowClosed(WindowEvent e) {
254        if (e != null && e.getComponent() == this && getValue() == getContinueButtonIndex()) {
255            Config.getPref().putInt("downloadprimitive.lasttype", cbType.getSelectedIndex());
256
257            if (!tfId.readIds()) {
258                JOptionPane.showMessageDialog(getParent(),
259                        tr("Invalid ID list specified\n"
260                                + "Cannot continue."),
261                        tr("Information"),
262                        JOptionPane.INFORMATION_MESSAGE
263                );
264                return;
265            }
266
267            remindPrimitivesHistory(cbId);
268        }
269    }
270
271    @Override public void windowOpened(WindowEvent e) {
272        // Do nothing
273    }
274
275    @Override public void windowClosing(WindowEvent e) {
276        // Do nothing
277    }
278
279    @Override public void windowIconified(WindowEvent e) {
280        // Do nothing
281    }
282
283    @Override public void windowDeiconified(WindowEvent e) {
284        // Do nothing
285    }
286
287    @Override public void windowActivated(WindowEvent e) {
288        // Do nothing
289    }
290
291    @Override public void windowDeactivated(WindowEvent e) {
292        // Do nothing
293    }
294}