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.Cursor;
009import java.awt.Dimension;
010import java.awt.FlowLayout;
011import java.awt.GridBagLayout;
012import java.awt.event.ActionEvent;
013import java.awt.event.ItemEvent;
014import java.awt.event.ItemListener;
015import java.awt.event.MouseAdapter;
016import java.awt.event.MouseEvent;
017import java.util.Arrays;
018
019import javax.swing.BorderFactory;
020import javax.swing.ButtonGroup;
021import javax.swing.JCheckBox;
022import javax.swing.JLabel;
023import javax.swing.JOptionPane;
024import javax.swing.JPanel;
025import javax.swing.JRadioButton;
026import javax.swing.SwingUtilities;
027import javax.swing.text.BadLocationException;
028import javax.swing.text.Document;
029import javax.swing.text.JTextComponent;
030
031import org.openstreetmap.josm.data.osm.DataSet;
032import org.openstreetmap.josm.data.osm.Filter;
033import org.openstreetmap.josm.data.osm.search.SearchCompiler;
034import org.openstreetmap.josm.data.osm.search.SearchMode;
035import org.openstreetmap.josm.data.osm.search.SearchParseError;
036import org.openstreetmap.josm.data.osm.search.SearchSetting;
037import org.openstreetmap.josm.gui.ExtendedDialog;
038import org.openstreetmap.josm.gui.MainApplication;
039import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSException;
040import org.openstreetmap.josm.gui.tagging.ac.AutoCompComboBox;
041import org.openstreetmap.josm.gui.tagging.ac.AutoCompComboBoxModel;
042import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
043import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetSelector;
044import org.openstreetmap.josm.gui.widgets.AbstractTextComponentValidator;
045import org.openstreetmap.josm.tools.GBC;
046import org.openstreetmap.josm.tools.JosmRuntimeException;
047import org.openstreetmap.josm.tools.Logging;
048import org.openstreetmap.josm.tools.Utils;
049
050/**
051 * Search dialog to find primitives by a wide range of search criteria.
052 * @since 14927 (extracted from {@code SearchAction})
053 */
054public class SearchDialog extends ExtendedDialog {
055
056    private final SearchSetting searchSettings;
057
058    protected final AutoCompComboBox<SearchSetting> hcbSearchString;
059
060    private JCheckBox addOnToolbar;
061    private JCheckBox caseSensitive;
062    private JCheckBox allElements;
063
064    private JRadioButton standardSearch;
065    private JRadioButton regexSearch;
066    private JRadioButton mapCSSSearch;
067
068    private JRadioButton replace;
069    private JRadioButton add;
070    private JRadioButton remove;
071    private JRadioButton inSelection;
072    private TaggingPresetSelector selector;
073    /**
074     * Constructs a new {@code SearchDialog}.
075     * @param initialValues initial search settings, eg. when opened for editing from the filter panel
076     * @param model The combobox model.
077     * @param expertMode expert mode. Shows more options and the "search syntax" panel.
078     * @since 18173 (signature)
079     */
080    public SearchDialog(SearchSetting initialValues, AutoCompComboBoxModel<SearchSetting> model, boolean expertMode) {
081        this(initialValues, model, new PanelOptions(expertMode, false), MainApplication.getMainFrame(),
082                initialValues instanceof Filter ? tr("Filter") : tr("Search"),
083                initialValues instanceof Filter ? tr("Submit filter") : tr("Search"),
084                tr("Cancel"));
085        setButtonIcons("dialogs/search", "cancel");
086        configureContextsensitiveHelp("/Action/Search", true /* show help button */);
087    }
088
089    protected SearchDialog(SearchSetting initialValues, AutoCompComboBoxModel<SearchSetting> model, PanelOptions options,
090                           Component mainFrame, String title, String... buttonTexts) {
091        super(mainFrame, title, buttonTexts);
092        hcbSearchString = new AutoCompComboBox<>(model);
093        this.searchSettings = new SearchSetting(initialValues);
094        setContent(buildPanel(options));
095
096        // See #24333
097        if (!(initialValues instanceof Filter)) {
098            DataSet data = MainApplication.getLayerManager().getActiveDataSet();
099            if (data != null && data.getSelected().isEmpty()) {
100                remove.setEnabled(false);
101                inSelection.setEnabled(false);
102                if (this.searchSettings.mode == SearchMode.in_selection
103                        || this.searchSettings.mode == SearchMode.remove) {
104                    this.searchSettings.mode = SearchMode.replace;
105                    replace.setSelected(true);
106                }
107            }
108        }
109    }
110
111    /**
112     * Determines which parts of the search dialog will be shown
113     */
114    protected static class PanelOptions {
115        private final boolean expertMode;
116        private final boolean overpassQuery;
117
118        /**
119         * Constructs new options which determine which parts of the search dialog will be shown
120         * @param expertMode Shows more options and the "search syntax" panel.
121         * @param overpassQuery Don't show left panels and right "preset" panel. Show different "hints".
122         */
123        public PanelOptions(boolean expertMode, boolean overpassQuery) {
124            this.expertMode = expertMode;
125            this.overpassQuery = overpassQuery;
126        }
127    }
128
129    private JPanel buildPanel(PanelOptions options) {
130
131        // prepare the combo box with the search expressions
132        JLabel label = new JLabel(searchSettings instanceof Filter ? tr("Filter string:") : tr("Search string:"));
133
134        String tooltip = tr("Enter the search expression");
135        hcbSearchString.setText(searchSettings.toString());
136        hcbSearchString.setToolTipText(tooltip);
137        hcbSearchString.setPreferredSize(new Dimension(40, hcbSearchString.getPreferredSize().height));
138        label.setLabelFor(hcbSearchString);
139
140        replace = new JRadioButton(tr("select"), searchSettings.mode == SearchMode.replace);
141        add = new JRadioButton(tr("add to selection"), searchSettings.mode == SearchMode.add);
142        remove = new JRadioButton(tr("remove from selection"), searchSettings.mode == SearchMode.remove);
143        inSelection = new JRadioButton(tr("find in selection"), searchSettings.mode == SearchMode.in_selection);
144        ButtonGroup bg = new ButtonGroup();
145        bg.add(replace);
146        bg.add(add);
147        bg.add(remove);
148        bg.add(inSelection);
149
150        caseSensitive = new JCheckBox(tr("case sensitive"), searchSettings.caseSensitive);
151        allElements = new JCheckBox(tr("all objects"), searchSettings.allElements);
152        allElements.setToolTipText(tr("Also include incomplete and deleted objects in search."));
153        addOnToolbar = new JCheckBox(tr("add toolbar button"), false);
154        addOnToolbar.setToolTipText(tr("Add a button with this search expression to the toolbar."));
155
156        standardSearch = new JRadioButton(tr("standard"), !searchSettings.regexSearch && !searchSettings.mapCSSSearch);
157        regexSearch = new JRadioButton(tr("regular expression"), searchSettings.regexSearch);
158        mapCSSSearch = new JRadioButton(tr("MapCSS selector"), searchSettings.mapCSSSearch);
159
160        ButtonGroup bg2 = new ButtonGroup();
161        bg2.add(standardSearch);
162        bg2.add(regexSearch);
163        bg2.add(mapCSSSearch);
164
165        JPanel selectionSettings = new JPanel(new GridBagLayout());
166        selectionSettings.setBorder(BorderFactory.createTitledBorder(tr("Results")));
167        selectionSettings.add(replace, GBC.eol().anchor(GBC.WEST).fill(GBC.HORIZONTAL));
168        selectionSettings.add(add, GBC.eol());
169        selectionSettings.add(remove, GBC.eol());
170        selectionSettings.add(inSelection, GBC.eop());
171
172        JPanel additionalSettings = new JPanel(new GridBagLayout());
173        additionalSettings.setBorder(BorderFactory.createTitledBorder(tr("Options")));
174        additionalSettings.add(caseSensitive, GBC.eol().anchor(GBC.WEST).fill(GBC.HORIZONTAL));
175
176        JPanel left = new JPanel(new GridBagLayout());
177
178        left.add(selectionSettings, GBC.eol().fill(GBC.BOTH));
179        left.add(additionalSettings, GBC.eol().fill(GBC.BOTH));
180
181        if (options.expertMode) {
182            additionalSettings.add(allElements, GBC.eol());
183            additionalSettings.add(addOnToolbar, GBC.eop());
184
185            JPanel searchOptions = new JPanel(new GridBagLayout());
186            searchOptions.setBorder(BorderFactory.createTitledBorder(tr("Search syntax")));
187            searchOptions.add(standardSearch, GBC.eol().anchor(GBC.WEST).fill(GBC.HORIZONTAL));
188            searchOptions.add(regexSearch, GBC.eol());
189            searchOptions.add(mapCSSSearch, GBC.eol());
190
191            left.add(searchOptions, GBC.eol().fill(GBC.BOTH));
192        }
193
194        JPanel right = buildHintsSection(hcbSearchString, options);
195        JPanel top = new JPanel(new GridBagLayout());
196        top.add(label, GBC.std().insets(0, 0, 5, 0));
197        top.add(hcbSearchString, GBC.eol().fill(GBC.HORIZONTAL));
198
199        JTextComponent editorComponent = hcbSearchString.getEditorComponent();
200        Document document = editorComponent.getDocument();
201
202        /*
203         * Setup the logic to validate the contents of the search text field which is executed
204         * every time the content of the field has changed. If the query is incorrect, then
205         * the text field is colored red.
206         */
207        AbstractTextComponentValidator validator = new AbstractTextComponentValidator(editorComponent) {
208
209            @Override
210            public void validate() {
211                if (!isValid()) {
212                    feedbackInvalid(tr("Invalid search expression"));
213                } else {
214                    feedbackValid(tooltip);
215                }
216            }
217
218            @Override
219            public boolean isValid() {
220                try {
221                    SearchSetting ss = new SearchSetting();
222                    ss.text = hcbSearchString.getText();
223                    ss.caseSensitive = caseSensitive.isSelected();
224                    ss.regexSearch = regexSearch.isSelected();
225                    ss.mapCSSSearch = mapCSSSearch.isSelected();
226                    SearchCompiler.compile(ss);
227                    return true;
228                } catch (SearchParseError | MapCSSException e) {
229                    Logging.trace(e);
230                    return false;
231                }
232            }
233        };
234        document.addDocumentListener(validator);
235        ItemListener validateActionListener = e -> {
236            if (e.getStateChange() == ItemEvent.SELECTED) {
237                validator.validate();
238            }
239        };
240        standardSearch.addItemListener(validateActionListener);
241        regexSearch.addItemListener(validateActionListener);
242        mapCSSSearch.addItemListener(validateActionListener);
243
244        /*
245         * Setup the logic to append preset queries to the search text field according to
246         * selected preset by the user. Every query is of the form ' group/sub-group/.../presetName'
247         * if the corresponding group of the preset exists, otherwise it is simply ' presetName'.
248         */
249        selector = new TaggingPresetSelector(false, false);
250        selector.setBorder(BorderFactory.createTitledBorder(tr("Search by preset")));
251        selector.setDblClickListener(ev -> setPresetDblClickListener(selector, editorComponent));
252
253        JPanel p = new JPanel(new GridBagLayout());
254        p.add(top, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 5, 0));
255        if (!options.overpassQuery) {
256            p.add(left, GBC.std().anchor(GBC.NORTH).insets(5, 10, 10, 0).fill(GBC.VERTICAL));
257        }
258        p.add(right, GBC.std().fill(GBC.BOTH).insets(0, 10, 0, 0));
259        if (!options.overpassQuery) {
260            p.add(selector, GBC.eol().fill(GBC.BOTH).insets(0, 10, 0, 0));
261        }
262
263        return p;
264    }
265
266    @Override
267    protected void buttonAction(int buttonIndex, ActionEvent evt) {
268        if (buttonIndex == 0) {
269            try {
270                SearchSetting ss = new SearchSetting();
271                ss.text = hcbSearchString.getText();
272                ss.caseSensitive = caseSensitive.isSelected();
273                ss.regexSearch = regexSearch.isSelected();
274                ss.mapCSSSearch = mapCSSSearch.isSelected();
275                SearchCompiler.compile(ss);
276                super.buttonAction(buttonIndex, evt);
277            } catch (SearchParseError | MapCSSException e) {
278                Logging.warn(e);
279                String message = Utils.escapeReservedCharactersHTML(e.getMessage()
280                        .replace("<html>", "")
281                        .replace("</html>", ""));
282                JOptionPane.showMessageDialog(
283                        MainApplication.getMainFrame(),
284                        "<html>" + tr("Search expression is not valid: \n\n {0}", message).replace("\n", "<br>") + "</html>",
285                        tr("Invalid search expression"),
286                        JOptionPane.ERROR_MESSAGE);
287            }
288        } else {
289            super.buttonAction(buttonIndex, evt);
290        }
291    }
292
293    /**
294     * Returns the search settings chosen by user.
295     * @return the search settings chosen by user
296     */
297    public SearchSetting getSearchSettings() {
298        searchSettings.text = hcbSearchString.getText();
299        searchSettings.caseSensitive = caseSensitive.isSelected();
300        searchSettings.allElements = allElements.isSelected();
301        searchSettings.regexSearch = regexSearch.isSelected();
302        searchSettings.mapCSSSearch = mapCSSSearch.isSelected();
303
304        if (inSelection.isSelected()) {
305            searchSettings.mode = SearchMode.in_selection;
306        } else if (replace.isSelected()) {
307            searchSettings.mode = SearchMode.replace;
308        } else if (add.isSelected()) {
309            searchSettings.mode = SearchMode.add;
310        } else {
311            searchSettings.mode = SearchMode.remove;
312        }
313        return searchSettings;
314    }
315
316    /**
317     * Determines if the "add toolbar button" checkbox is selected.
318     * @return {@code true} if the "add toolbar button" checkbox is selected
319     */
320    public boolean isAddOnToolbar() {
321        return addOnToolbar.isSelected();
322    }
323
324    private static JPanel buildHintsSection(AutoCompComboBox<SearchSetting> hcbSearchString, PanelOptions options) {
325        JPanel hintPanel = new JPanel(new GridBagLayout());
326        hintPanel.setBorder(BorderFactory.createTitledBorder(tr("Hints")));
327
328        hintPanel.add(new SearchKeywordRow(hcbSearchString)
329                .addTitle(tr("basics"))
330                .addKeyword(tr("Baker Street"), null, tr("''Baker'' and ''Street'' in any key"))
331                .addKeyword(tr("\"Baker Street\""), "\"\"", tr("''Baker Street'' in any key"))
332                .addKeyword("<i>key</i>:<i>valuefragment</i>", null,
333                        tr("''valuefragment'' anywhere in ''key''"),
334                        trc("search string example", "name:str matches name=Bakerstreet"))
335                .addKeyword("-<i>key</i>:<i>valuefragment</i>", null, tr("''valuefragment'' nowhere in ''key''")),
336                GBC.eol());
337        hintPanel.add(new SearchKeywordRow(hcbSearchString)
338                .addKeyword("<i>key:</i>", null, tr("matches if ''key'' exists"))
339                .addKeyword("<i>key?</i>", null, tr("matches if ''key'' has a truthy value (''true'', ''yes'', ''1'', ''on'')"))
340                .addKeyword("<i>key</i>=<i>value</i>", null, tr("''key'' with exactly ''value''"))
341                .addKeyword("<i>key</i>~<i>regexp</i>", null, tr("value of ''key'' matching the regular expression ''regexp''"))
342                .addKeyword("<i>key</i>=*", null, tr("''key'' with any value"))
343                .addKeyword("<i>key</i>=", null, tr("''key'' with empty value"))
344                .addKeyword("*=<i>value</i>", null, tr("''value'' in any key"))
345                .addKeyword("<i>key</i>><i>value</i>", null, tr("matches if ''key'' is greater than ''value'' (analogously, less than)"))
346                .addKeyword("\"key\"=\"value\"", "\"\"=\"\"",
347                        tr("to quote operators.<br>Within quoted strings the <b>\"</b> and <b>\\</b> characters need to be escaped " +
348                                "by a preceding <b>\\</b> (e.g. <b>\\\"</b> and <b>\\\\</b>)."),
349                        trc("search string example", "name=\"Baker Street\""),
350                        "\"addr:street\""),
351                GBC.eol().anchor(GBC.CENTER));
352        hintPanel.add(new SearchKeywordRow(hcbSearchString)
353                .addTitle(tr("combinators"))
354                .addKeyword("<i>expr</i> <i>expr</i>", null,
355                        tr("logical and (both expressions have to be satisfied)"),
356                        trc("search string example", "Baker Street"))
357                .addKeyword("<i>expr</i> & <i>expr</i>", "& ", tr("logical and (both expressions have to be satisfied)"))
358                .addKeyword("<i>expr</i> AND <i>expr</i>", "AND ", tr("logical and (both expressions have to be satisfied)"))
359                .addKeyword("<i>expr</i> | <i>expr</i>", "| ", tr("logical or (at least one expression has to be satisfied)"))
360                .addKeyword("<i>expr</i> OR <i>expr</i>", "OR ", tr("logical or (at least one expression has to be satisfied)")),
361                GBC.eol());
362        hintPanel.add(new SearchKeywordRow(hcbSearchString)
363                .addKeyword("<i>expr</i> ^ <i>expr</i>", "^ ", tr("logical xor (one and only one expression has to be satisfied)"))
364                .addKeyword("<i>expr</i> XOR <i>expr</i>", "XOR ", tr("logical xor (one and only one expression has to be satisfied)"))
365                .addKeyword("-<i>expr</i>", null, tr("logical not"))
366                .addKeyword("(<i>expr</i>)", "()", tr("use parenthesis to group expressions")),
367                GBC.eol().anchor(GBC.CENTER));
368
369        SearchKeywordRow objectHints = new SearchKeywordRow(hcbSearchString)
370                .addTitle(tr("objects"))
371                .addKeyword("type:node", "type:node ", tr("all nodes"))
372                .addKeyword("type:way", "type:way ", tr("all ways"))
373                .addKeyword("type:relation", "type:relation ", tr("all relations"));
374        if (options.expertMode) {
375            objectHints
376                .addKeyword("closed", "closed ", tr("all closed ways"))
377                .addKeyword("untagged", "untagged ", tr("object without useful tags"));
378        }
379        hintPanel.add(objectHints, GBC.eol());
380
381        if (options.expertMode) {
382            hintPanel.add(new SearchKeywordRow(hcbSearchString)
383                    .addKeyword("preset:\"Annotation/Address\"", "preset:\"Annotation/Address\"",
384                            tr("all objects that use the address preset"))
385                    .addKeyword("preset:\"Geography/Nature/*\"", "preset:\"Geography/Nature/*\"",
386                            tr("all objects that use any preset under the Geography/Nature group")),
387                    GBC.eol().anchor(GBC.CENTER));
388            hintPanel.add(new SearchKeywordRow(hcbSearchString)
389                .addTitle(tr("metadata"))
390                .addKeyword("user:", "user:", tr("objects changed by author"),
391                        trc("search string example", "user:<i>OSM username</i> (objects with the author <i>OSM username</i>)"),
392                        trc("search string example", "user:anonymous (objects without an assigned author)"))
393                .addKeyword("id:", "id:", tr("objects with given ID"),
394                        trc("search string example", "id:0 (new objects)"))
395                .addKeyword("version:", "version:", tr("objects with given version"),
396                        trc("search string example", "version:0 (objects without an assigned version)"))
397                .addKeyword("changeset:", "changeset:", tr("objects with given changeset ID"),
398                        trc("search string example", "changeset:0 (objects without an assigned changeset)"))
399                .addKeyword("timestamp:", "timestamp:", tr("objects with last modification timestamp within range"), "timestamp:2012/",
400                        "timestamp:2008/2011-02-04T12"),
401                GBC.eol());
402            hintPanel.add(new SearchKeywordRow(hcbSearchString)
403                .addTitle(tr("properties"))
404                .addKeyword("nodes:<i>20-</i>", "nodes:", tr("ways with at least 20 nodes, or relations containing at least 20 nodes"))
405                .addKeyword("ways:<i>3-</i>", "ways:", tr("nodes with at least 3 referring ways, or relations containing at least 3 ways"))
406                .addKeyword("tags:<i>5-10</i>", "tags:", tr("objects having 5 to 10 tags"))
407                .addKeyword("members:<i>2</i>", "members:", tr("relations with 2 members"))
408                .addKeyword("areasize:<i>-100</i>", "areasize:", tr("closed ways with an area of 100 m\u00b2"))
409                .addKeyword("waylength:<i>200-</i>", "waylength:", tr("ways with a length of 200 m or more")),
410                GBC.eol());
411            hintPanel.add(new SearchKeywordRow(hcbSearchString)
412                .addTitle(tr("state"))
413                .addKeyword("modified", "modified ", tr("all modified objects"))
414                .addKeyword("new", "new ", tr("all new objects"))
415                .addKeyword("selected", "selected ", tr("all selected objects"))
416                .addKeyword("incomplete", "incomplete ", tr("all incomplete objects"))
417                .addKeyword("deleted", "deleted ", tr("all deleted objects (checkbox <b>{0}</b> must be enabled)", tr("all objects"))),
418                GBC.eol());
419            hintPanel.add(new SearchKeywordRow(hcbSearchString)
420                .addTitle(tr("related objects"))
421                .addKeyword("child <i>expr</i>", "child ", tr("all children of objects matching the expression"), "child building")
422                .addKeyword("parent <i>expr</i>", "parent ", tr("all parents of objects matching the expression"), "parent bus_stop")
423                .addKeyword("role:", "role:", tr("objects with given role in a relation"))
424                .addKeyword("hasRole:<i>stop</i>", "hasRole:", tr("relation containing a member of role <i>stop</i>"))
425                .addKeyword("role:<i>stop</i>", "role:", tr("objects being part of a relation as role <i>stop</i>"))
426                .addKeyword("nth:<i>7</i>", "nth:",
427                        tr("n-th member of relation and/or n-th node of way"), "nth:5 (child type:relation)", "nth:-1")
428                .addKeyword("nth%:<i>7</i>", "nth%:",
429                        tr("every n-th member of relation and/or every n-th node of way"), "nth%:100 (child waterway)"),
430                GBC.eol());
431            hintPanel.add(new SearchKeywordRow(hcbSearchString)
432                .addTitle(tr("view"))
433                .addKeyword("inview", "inview ", tr("objects in current view"))
434                .addKeyword("allinview", "allinview ", tr("objects (and all its way nodes / relation members) in current view"))
435                .addKeyword("indownloadedarea", "indownloadedarea ", tr("objects in downloaded area"))
436                .addKeyword("allindownloadedarea", "allindownloadedarea ",
437                        tr("objects (and all its way nodes / relation members) in downloaded area")),
438                GBC.eol());
439        }
440        if (options.overpassQuery) {
441            hintPanel.add(new SearchKeywordRow(hcbSearchString)
442                .addTitle(tr("location"))
443                .addKeyword("<i>key=value in <u>location</u></i>", null,
444                        tr("{0} all objects having {1} as attribute are downloaded.", "<i>tourism=hotel in Berlin</i> -", "'tourism=hotel'"))
445                .addKeyword("<i>key=value around <u>location</u></i>", null,
446                        tr("{0} all object with the corresponding key/value pair located around Berlin. Note, the default value for radius " +
447                                "is set to 1000m, but it can be changed in the generated query.", "<i>tourism=hotel around Berlin</i> -"))
448                .addKeyword("<i>key=value in bbox</i>", null,
449                        tr("{0} all objects within the current selection that have {1} as attribute.", "<i>tourism=hotel in bbox</i> -",
450                                "'tourism=hotel'")),
451                GBC.eol());
452        }
453
454        return hintPanel;
455    }
456
457    /**
458     *
459     * @param selector Selector component that the user interacts with
460     * @param searchEditor Editor for search queries
461     */
462    private static void setPresetDblClickListener(TaggingPresetSelector selector, JTextComponent searchEditor) {
463        TaggingPreset selectedPreset = selector.getSelectedPresetAndUpdateClassification();
464
465        if (selectedPreset == null) {
466            return;
467        }
468
469        // Make sure that the focus is transferred to the search text field from the selector component
470        searchEditor.requestFocusInWindow();
471
472        // In order to make interaction with the search dialog simpler, we make sure that
473        // if autocompletion triggers and the text field is not in focus, the correct area is selected.
474        // We first request focus and then execute the selection logic.
475        // invokeLater allows us to defer the selection until waiting for focus.
476        SwingUtilities.invokeLater(() -> {
477            int textOffset = searchEditor.getCaretPosition();
478            String presetSearchQuery = " preset:" +
479                    "\"" + selectedPreset.getRawName() + "\"";
480            try {
481                searchEditor.getDocument().insertString(textOffset, presetSearchQuery, null);
482            } catch (BadLocationException e1) {
483                throw new JosmRuntimeException(e1.getMessage(), e1);
484            }
485        });
486    }
487
488    private static class SearchKeywordRow extends JPanel {
489
490        private final AutoCompComboBox<SearchSetting> hcb;
491
492        SearchKeywordRow(AutoCompComboBox<SearchSetting> hcb) {
493            super(new FlowLayout(FlowLayout.LEFT));
494            this.hcb = hcb;
495        }
496
497        /**
498         * Adds the title (prefix) label at the beginning of the row. Should be called only once.
499         * @param title English title
500         * @return {@code this} for easy chaining
501         */
502        public SearchKeywordRow addTitle(String title) {
503            add(new JLabel(tr("{0}: ", title)));
504            return this;
505        }
506
507        /**
508         * Adds an example keyword label at the end of the row. Can be called several times.
509         * @param displayText displayed HTML text
510         * @param insertText optional: if set, makes the label clickable, and {@code insertText} will be inserted in search string
511         * @param description optional: HTML text to be displayed in the tooltip
512         * @param examples optional: examples joined as HTML list in the tooltip
513         * @return {@code this} for easy chaining
514         */
515        public SearchKeywordRow addKeyword(String displayText, final String insertText, String description, String... examples) {
516            JLabel label = new JLabel("<html>"
517                    + "<style>td{border:1px solid gray; font-weight:normal;}</style>"
518                    + "<table><tr><td>" + displayText + "</td></tr></table></html>");
519            add(label);
520            if (description != null || examples.length > 0) {
521                label.setToolTipText("<html>"
522                        + description
523                        + (examples.length > 0 ? Utils.joinAsHtmlUnorderedList(Arrays.asList(examples)) : "")
524                        + "</html>");
525            }
526            if (insertText != null) {
527                label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
528                label.addMouseListener(new MouseAdapter() {
529
530                    @Override
531                    public void mouseClicked(MouseEvent e) {
532                        JTextComponent tf = hcb.getEditorComponent();
533
534                        // Make sure that the focus is transferred to the search text field from the selector component
535                        if (!tf.hasFocus()) {
536                            tf.requestFocusInWindow();
537                        }
538
539                        // In order to make interaction with the search dialog simpler, we make sure that
540                        // if autocompletion triggers and the text field is not in focus, the correct area is selected.
541                        // We first request focus and then execute the selection logic.
542                        // invokeLater allows us to defer the selection until waiting for focus.
543                        SwingUtilities.invokeLater(() -> {
544                            try {
545                                tf.getDocument().insertString(tf.getCaretPosition(), ' ' + insertText, null);
546                            } catch (BadLocationException ex) {
547                                throw new JosmRuntimeException(ex.getMessage(), ex);
548                            }
549                        });
550                    }
551                });
552            }
553            return this;
554        }
555    }
556
557    @Override
558    public void dispose() {
559        if (selector != null)
560            selector.destroy();
561        super.dispose();
562    }
563}