001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.download;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.BorderLayout;
007import java.awt.Component;
008import java.awt.Dimension;
009import java.awt.GridBagLayout;
010import java.awt.GridLayout;
011import java.awt.event.ActionEvent;
012import java.awt.event.MouseAdapter;
013import java.awt.event.MouseEvent;
014import java.io.IOException;
015import java.io.Reader;
016import java.net.URL;
017import java.text.DecimalFormat;
018import java.util.ArrayList;
019import java.util.Collections;
020import java.util.LinkedList;
021import java.util.List;
022import java.util.StringTokenizer;
023
024import javax.swing.AbstractAction;
025import javax.swing.BorderFactory;
026import javax.swing.DefaultListSelectionModel;
027import javax.swing.JButton;
028import javax.swing.JLabel;
029import javax.swing.JOptionPane;
030import javax.swing.JPanel;
031import javax.swing.JScrollPane;
032import javax.swing.JTable;
033import javax.swing.ListSelectionModel;
034import javax.swing.UIManager;
035import javax.swing.event.DocumentEvent;
036import javax.swing.event.DocumentListener;
037import javax.swing.event.ListSelectionEvent;
038import javax.swing.event.ListSelectionListener;
039import javax.swing.table.DefaultTableColumnModel;
040import javax.swing.table.DefaultTableModel;
041import javax.swing.table.TableCellRenderer;
042import javax.swing.table.TableColumn;
043
044import org.openstreetmap.josm.Main;
045import org.openstreetmap.josm.data.Bounds;
046import org.openstreetmap.josm.gui.ExceptionDialogUtil;
047import org.openstreetmap.josm.gui.HelpAwareOptionPane;
048import org.openstreetmap.josm.gui.PleaseWaitRunnable;
049import org.openstreetmap.josm.gui.util.GuiHelper;
050import org.openstreetmap.josm.gui.widgets.HistoryComboBox;
051import org.openstreetmap.josm.gui.widgets.JosmComboBox;
052import org.openstreetmap.josm.io.OsmTransferException;
053import org.openstreetmap.josm.tools.GBC;
054import org.openstreetmap.josm.tools.HttpClient;
055import org.openstreetmap.josm.tools.ImageProvider;
056import org.openstreetmap.josm.tools.OsmUrlToBounds;
057import org.openstreetmap.josm.tools.Utils;
058import org.xml.sax.Attributes;
059import org.xml.sax.InputSource;
060import org.xml.sax.SAXException;
061import org.xml.sax.SAXParseException;
062import org.xml.sax.helpers.DefaultHandler;
063
064/**
065 * Place selector.
066 * @since 1329
067 */
068public class PlaceSelection implements DownloadSelection {
069    private static final String HISTORY_KEY = "download.places.history";
070
071    private HistoryComboBox cbSearchExpression;
072    private NamedResultTableModel model;
073    private NamedResultTableColumnModel columnmodel;
074    private JTable tblSearchResults;
075    private DownloadDialog parent;
076    private static final Server[] SERVERS = new Server[] {
077        new Server("Nominatim", "https://nominatim.openstreetmap.org/search?format=xml&q=", tr("Class Type"), tr("Bounds"))
078    };
079    private final JosmComboBox<Server> server = new JosmComboBox<>(SERVERS);
080
081    private static class Server {
082        public final String name;
083        public final String url;
084        public final String thirdcol;
085        public final String fourthcol;
086
087        Server(String n, String u, String t, String f) {
088            name = n;
089            url = u;
090            thirdcol = t;
091            fourthcol = f;
092        }
093
094        @Override
095        public String toString() {
096            return name;
097        }
098    }
099
100    protected JPanel buildSearchPanel() {
101        JPanel lpanel = new JPanel(new GridLayout(2, 2));
102        JPanel panel = new JPanel(new GridBagLayout());
103
104        lpanel.add(new JLabel(tr("Choose the server for searching:")));
105        lpanel.add(server);
106        String s = Main.pref.get("namefinder.server", SERVERS[0].name);
107        for (int i = 0; i < SERVERS.length; ++i) {
108            if (SERVERS[i].name.equals(s)) {
109                server.setSelectedIndex(i);
110            }
111        }
112        lpanel.add(new JLabel(tr("Enter a place name to search for:")));
113
114        cbSearchExpression = new HistoryComboBox();
115        cbSearchExpression.setToolTipText(tr("Enter a place name to search for"));
116        List<String> cmtHistory = new LinkedList<>(Main.pref.getCollection(HISTORY_KEY, new LinkedList<String>()));
117        Collections.reverse(cmtHistory);
118        cbSearchExpression.setPossibleItems(cmtHistory);
119        lpanel.add(cbSearchExpression);
120
121        panel.add(lpanel, GBC.std().fill(GBC.HORIZONTAL).insets(5, 5, 0, 5));
122        SearchAction searchAction = new SearchAction();
123        JButton btnSearch = new JButton(searchAction);
124        cbSearchExpression.getEditorComponent().getDocument().addDocumentListener(searchAction);
125        cbSearchExpression.getEditorComponent().addActionListener(searchAction);
126
127        panel.add(btnSearch, GBC.eol().insets(5, 5, 0, 5));
128
129        return panel;
130    }
131
132    /**
133     * Adds a new tab to the download dialog in JOSM.
134     *
135     * This method is, for all intents and purposes, the constructor for this class.
136     */
137    @Override
138    public void addGui(final DownloadDialog gui) {
139        JPanel panel = new JPanel(new BorderLayout());
140        panel.add(buildSearchPanel(), BorderLayout.NORTH);
141
142        DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
143        model = new NamedResultTableModel(selectionModel);
144        columnmodel = new NamedResultTableColumnModel();
145        tblSearchResults = new JTable(model, columnmodel);
146        tblSearchResults.setSelectionModel(selectionModel);
147        JScrollPane scrollPane = new JScrollPane(tblSearchResults);
148        scrollPane.setPreferredSize(new Dimension(200, 200));
149        panel.add(scrollPane, BorderLayout.CENTER);
150
151        if (gui != null)
152            gui.addDownloadAreaSelector(panel, tr("Areas around places"));
153
154        scrollPane.setPreferredSize(scrollPane.getPreferredSize());
155        tblSearchResults.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
156        tblSearchResults.getSelectionModel().addListSelectionListener(new ListSelectionHandler());
157        tblSearchResults.addMouseListener(new MouseAdapter() {
158            @Override
159            public void mouseClicked(MouseEvent e) {
160                if (e.getClickCount() > 1) {
161                    SearchResult sr = model.getSelectedSearchResult();
162                    if (sr != null) {
163                        parent.startDownload(sr.getDownloadArea());
164                    }
165                }
166            }
167        });
168        parent = gui;
169    }
170
171    @Override
172    public void setDownloadArea(Bounds area) {
173        tblSearchResults.clearSelection();
174    }
175
176    /**
177     * Data storage for search results.
178     */
179    private static class SearchResult {
180        public String name;
181        public String info;
182        public String nearestPlace;
183        public String description;
184        public double lat;
185        public double lon;
186        public int zoom;
187        public Bounds bounds;
188
189        public Bounds getDownloadArea() {
190            return bounds != null ? bounds : OsmUrlToBounds.positionToBounds(lat, lon, zoom);
191        }
192    }
193
194    /**
195     * A very primitive parser for the name finder's output.
196     * Structure of xml described here:  http://wiki.openstreetmap.org/index.php/Name_finder
197     *
198     */
199    private static class NameFinderResultParser extends DefaultHandler {
200        private SearchResult currentResult;
201        private StringBuilder description;
202        private int depth;
203        private final List<SearchResult> data = new LinkedList<>();
204
205        /**
206         * Detect starting elements.
207         *
208         */
209        @Override
210        public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
211        throws SAXException {
212            depth++;
213            try {
214                if ("searchresults".equals(qName)) {
215                    // do nothing
216                } else if ("named".equals(qName) && (depth == 2)) {
217                    currentResult = new PlaceSelection.SearchResult();
218                    currentResult.name = atts.getValue("name");
219                    currentResult.info = atts.getValue("info");
220                    if (currentResult.info != null) {
221                        currentResult.info = tr(currentResult.info);
222                    }
223                    currentResult.lat = Double.parseDouble(atts.getValue("lat"));
224                    currentResult.lon = Double.parseDouble(atts.getValue("lon"));
225                    currentResult.zoom = Integer.parseInt(atts.getValue("zoom"));
226                    data.add(currentResult);
227                } else if ("description".equals(qName) && (depth == 3)) {
228                    description = new StringBuilder();
229                } else if ("named".equals(qName) && (depth == 4)) {
230                    // this is a "named" place in the nearest places list.
231                    String info = atts.getValue("info");
232                    if ("city".equals(info) || "town".equals(info) || "village".equals(info)) {
233                        currentResult.nearestPlace = atts.getValue("name");
234                    }
235                } else if ("place".equals(qName) && atts.getValue("lat") != null) {
236                    currentResult = new PlaceSelection.SearchResult();
237                    currentResult.name = atts.getValue("display_name");
238                    currentResult.description = currentResult.name;
239                    currentResult.info = atts.getValue("class");
240                    if (currentResult.info != null) {
241                        currentResult.info = tr(currentResult.info);
242                    }
243                    currentResult.nearestPlace = tr(atts.getValue("type"));
244                    currentResult.lat = Double.parseDouble(atts.getValue("lat"));
245                    currentResult.lon = Double.parseDouble(atts.getValue("lon"));
246                    String[] bbox = atts.getValue("boundingbox").split(",");
247                    currentResult.bounds = new Bounds(
248                            Double.parseDouble(bbox[0]), Double.parseDouble(bbox[2]),
249                            Double.parseDouble(bbox[1]), Double.parseDouble(bbox[3]));
250                    data.add(currentResult);
251                }
252            } catch (NumberFormatException x) {
253                Main.error(x); // SAXException does not chain correctly
254                throw new SAXException(x.getMessage(), x);
255            } catch (NullPointerException x) {
256                Main.error(x); // SAXException does not chain correctly
257                throw new SAXException(tr("Null pointer exception, possibly some missing tags."), x);
258            }
259        }
260
261        /**
262         * Detect ending elements.
263         */
264        @Override
265        public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
266            if ("description".equals(qName) && description != null) {
267                currentResult.description = description.toString();
268                description = null;
269            }
270            depth--;
271        }
272
273        /**
274         * Read characters for description.
275         */
276        @Override
277        public void characters(char[] data, int start, int length) throws SAXException {
278            if (description != null) {
279                description.append(data, start, length);
280            }
281        }
282
283        public List<SearchResult> getResult() {
284            return data;
285        }
286    }
287
288    class SearchAction extends AbstractAction implements DocumentListener {
289
290        SearchAction() {
291            putValue(NAME, tr("Search ..."));
292            putValue(SMALL_ICON, ImageProvider.get("dialogs", "search"));
293            putValue(SHORT_DESCRIPTION, tr("Click to start searching for places"));
294            updateEnabledState();
295        }
296
297        @Override
298        public void actionPerformed(ActionEvent e) {
299            if (!isEnabled() || cbSearchExpression.getText().trim().isEmpty())
300                return;
301            cbSearchExpression.addCurrentItemToHistory();
302            Main.pref.putCollection(HISTORY_KEY, cbSearchExpression.getHistory());
303            NameQueryTask task = new NameQueryTask(cbSearchExpression.getText());
304            Main.worker.submit(task);
305        }
306
307        protected final void updateEnabledState() {
308            setEnabled(!cbSearchExpression.getText().trim().isEmpty());
309        }
310
311        @Override
312        public void changedUpdate(DocumentEvent e) {
313            updateEnabledState();
314        }
315
316        @Override
317        public void insertUpdate(DocumentEvent e) {
318            updateEnabledState();
319        }
320
321        @Override
322        public void removeUpdate(DocumentEvent e) {
323            updateEnabledState();
324        }
325    }
326
327    class NameQueryTask extends PleaseWaitRunnable {
328
329        private final String searchExpression;
330        private HttpClient connection;
331        private List<SearchResult> data;
332        private boolean canceled;
333        private final Server useserver;
334        private Exception lastException;
335
336        NameQueryTask(String searchExpression) {
337            super(tr("Querying name server"), false /* don't ignore exceptions */);
338            this.searchExpression = searchExpression;
339            useserver = (Server) server.getSelectedItem();
340            Main.pref.put("namefinder.server", useserver.name);
341        }
342
343        @Override
344        protected void cancel() {
345            this.canceled = true;
346            synchronized (this) {
347                if (connection != null) {
348                    connection.disconnect();
349                }
350            }
351        }
352
353        @Override
354        protected void finish() {
355            if (canceled)
356                return;
357            if (lastException != null) {
358                ExceptionDialogUtil.explainException(lastException);
359                return;
360            }
361            columnmodel.setHeadlines(useserver.thirdcol, useserver.fourthcol);
362            model.setData(this.data);
363        }
364
365        @Override
366        protected void realRun() throws SAXException, IOException, OsmTransferException {
367            String urlString = useserver.url+Utils.encodeUrl(searchExpression);
368
369            try {
370                getProgressMonitor().indeterminateSubTask(tr("Querying name server ..."));
371                URL url = new URL(urlString);
372                synchronized (this) {
373                    connection = HttpClient.create(url);
374                    connection.connect();
375                }
376                try (Reader reader = connection.getResponse().getContentReader()) {
377                    InputSource inputSource = new InputSource(reader);
378                    NameFinderResultParser parser = new NameFinderResultParser();
379                    Utils.parseSafeSAX(inputSource, parser);
380                    this.data = parser.getResult();
381                }
382            } catch (SAXParseException e) {
383                if (!canceled) {
384                    // Nominatim sometimes returns garbage, see #5934, #10643
385                    Main.warn(tr("Error occured with query ''{0}'': ''{1}''", urlString, e.getMessage()));
386                    GuiHelper.runInEDTAndWait(new Runnable() {
387                        @Override
388                        public void run() {
389                            HelpAwareOptionPane.showOptionDialog(
390                                    Main.parent,
391                                    tr("Name server returned invalid data. Please try again."),
392                                    tr("Bad response"),
393                                    JOptionPane.WARNING_MESSAGE, null
394                            );
395                        }
396                    });
397                }
398            } catch (Exception e) {
399                if (!canceled) {
400                    OsmTransferException ex = new OsmTransferException(e);
401                    ex.setUrl(urlString);
402                    lastException = ex;
403                }
404            }
405        }
406    }
407
408    static class NamedResultTableModel extends DefaultTableModel {
409        private transient List<SearchResult> data;
410        private final transient ListSelectionModel selectionModel;
411
412        NamedResultTableModel(ListSelectionModel selectionModel) {
413            data = new ArrayList<>();
414            this.selectionModel = selectionModel;
415        }
416
417        @Override
418        public int getRowCount() {
419            return data != null ? data.size() : 0;
420        }
421
422        @Override
423        public Object getValueAt(int row, int column) {
424            return data != null ? data.get(row) : null;
425        }
426
427        public void setData(List<SearchResult> data) {
428            if (data == null) {
429                this.data.clear();
430            } else {
431                this.data = new ArrayList<>(data);
432            }
433            fireTableDataChanged();
434        }
435
436        @Override
437        public boolean isCellEditable(int row, int column) {
438            return false;
439        }
440
441        public SearchResult getSelectedSearchResult() {
442            if (selectionModel.getMinSelectionIndex() < 0)
443                return null;
444            return data.get(selectionModel.getMinSelectionIndex());
445        }
446    }
447
448    static class NamedResultTableColumnModel extends DefaultTableColumnModel {
449        private TableColumn col3;
450        private TableColumn col4;
451
452        NamedResultTableColumnModel() {
453            createColumns();
454        }
455
456        protected final void createColumns() {
457            TableColumn col;
458            NamedResultCellRenderer renderer = new NamedResultCellRenderer();
459
460            // column 0 - Name
461            col = new TableColumn(0);
462            col.setHeaderValue(tr("Name"));
463            col.setResizable(true);
464            col.setPreferredWidth(200);
465            col.setCellRenderer(renderer);
466            addColumn(col);
467
468            // column 1 - Version
469            col = new TableColumn(1);
470            col.setHeaderValue(tr("Type"));
471            col.setResizable(true);
472            col.setPreferredWidth(100);
473            col.setCellRenderer(renderer);
474            addColumn(col);
475
476            // column 2 - Near
477            col3 = new TableColumn(2);
478            col3.setHeaderValue(SERVERS[0].thirdcol);
479            col3.setResizable(true);
480            col3.setPreferredWidth(100);
481            col3.setCellRenderer(renderer);
482            addColumn(col3);
483
484            // column 3 - Zoom
485            col4 = new TableColumn(3);
486            col4.setHeaderValue(SERVERS[0].fourthcol);
487            col4.setResizable(true);
488            col4.setPreferredWidth(50);
489            col4.setCellRenderer(renderer);
490            addColumn(col4);
491        }
492
493        public void setHeadlines(String third, String fourth) {
494            col3.setHeaderValue(third);
495            col4.setHeaderValue(fourth);
496            fireColumnMarginChanged();
497        }
498    }
499
500    class ListSelectionHandler implements ListSelectionListener {
501        @Override
502        public void valueChanged(ListSelectionEvent lse) {
503            SearchResult r = model.getSelectedSearchResult();
504            if (r != null) {
505                parent.boundingBoxChanged(r.getDownloadArea(), PlaceSelection.this);
506            }
507        }
508    }
509
510    static class NamedResultCellRenderer extends JLabel implements TableCellRenderer {
511
512        /**
513         * Constructs a new {@code NamedResultCellRenderer}.
514         */
515        NamedResultCellRenderer() {
516            setOpaque(true);
517            setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
518        }
519
520        protected void reset() {
521            setText("");
522            setIcon(null);
523        }
524
525        protected void renderColor(boolean selected) {
526            if (selected) {
527                setForeground(UIManager.getColor("Table.selectionForeground"));
528                setBackground(UIManager.getColor("Table.selectionBackground"));
529            } else {
530                setForeground(UIManager.getColor("Table.foreground"));
531                setBackground(UIManager.getColor("Table.background"));
532            }
533        }
534
535        protected String lineWrapDescription(String description) {
536            StringBuilder ret = new StringBuilder();
537            StringBuilder line = new StringBuilder();
538            StringTokenizer tok = new StringTokenizer(description, " ");
539            while (tok.hasMoreElements()) {
540                String t = tok.nextToken();
541                if (line.length() == 0) {
542                    line.append(t);
543                } else if (line.length() < 80) {
544                    line.append(' ').append(t);
545                } else {
546                    line.append(' ').append(t).append("<br>");
547                    ret.append(line);
548                    line = new StringBuilder();
549                }
550            }
551            ret.insert(0, "<html>");
552            ret.append("</html>");
553            return ret.toString();
554        }
555
556        @Override
557        public Component getTableCellRendererComponent(JTable table, Object value,
558                boolean isSelected, boolean hasFocus, int row, int column) {
559
560            reset();
561            renderColor(isSelected);
562
563            if (value == null)
564                return this;
565            SearchResult sr = (SearchResult) value;
566            switch(column) {
567            case 0:
568                setText(sr.name);
569                break;
570            case 1:
571                setText(sr.info);
572                break;
573            case 2:
574                setText(sr.nearestPlace);
575                break;
576            case 3:
577                if (sr.bounds != null) {
578                    setText(sr.bounds.toShortString(new DecimalFormat("0.000")));
579                } else {
580                    setText(sr.zoom != 0 ? Integer.toString(sr.zoom) : tr("unknown"));
581                }
582                break;
583            }
584            setToolTipText(lineWrapDescription(sr.description));
585            return this;
586        }
587    }
588}