source: josm/trunk/src/org/openstreetmap/josm/gui/dialogs/SearchDialog.java@ 15090

Last change on this file since 15090 was 15090, checked in by Don-vip, 5 years ago

fix #17526 - provide a "search string example" translation context to all new strings. The context can help to avoid translating key words. (patch by Hb---)

  • Property svn:eol-style set to native
File size: 24.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.dialogs;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trc;
6
7import java.awt.Cursor;
8import java.awt.Dimension;
9import java.awt.FlowLayout;
10import java.awt.GridBagLayout;
11import java.awt.event.ActionEvent;
12import java.awt.event.MouseAdapter;
13import java.awt.event.MouseEvent;
14import java.util.Arrays;
15import java.util.Collections;
16import java.util.List;
17
18import javax.swing.BorderFactory;
19import javax.swing.ButtonGroup;
20import javax.swing.JCheckBox;
21import javax.swing.JLabel;
22import javax.swing.JOptionPane;
23import javax.swing.JPanel;
24import javax.swing.JRadioButton;
25import javax.swing.SwingUtilities;
26import javax.swing.text.BadLocationException;
27import javax.swing.text.Document;
28import javax.swing.text.JTextComponent;
29
30import org.openstreetmap.josm.data.osm.Filter;
31import org.openstreetmap.josm.data.osm.search.SearchCompiler;
32import org.openstreetmap.josm.data.osm.search.SearchMode;
33import org.openstreetmap.josm.data.osm.search.SearchParseError;
34import org.openstreetmap.josm.data.osm.search.SearchSetting;
35import org.openstreetmap.josm.gui.ExtendedDialog;
36import org.openstreetmap.josm.gui.MainApplication;
37import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSException;
38import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
39import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetSelector;
40import org.openstreetmap.josm.gui.widgets.AbstractTextComponentValidator;
41import org.openstreetmap.josm.gui.widgets.HistoryComboBox;
42import org.openstreetmap.josm.tools.GBC;
43import org.openstreetmap.josm.tools.JosmRuntimeException;
44import org.openstreetmap.josm.tools.Logging;
45import org.openstreetmap.josm.tools.Utils;
46
47/**
48 * Search dialog to find primitives by a wide range of search criteria.
49 * @since 14927 (extracted from {@code SearchAction})
50 */
51public class SearchDialog extends ExtendedDialog {
52
53 private final SearchSetting searchSettings;
54
55 private final HistoryComboBox hcbSearchString = new HistoryComboBox();
56
57 private JCheckBox addOnToolbar;
58 private JCheckBox caseSensitive;
59 private JCheckBox allElements;
60
61 private JRadioButton standardSearch;
62 private JRadioButton regexSearch;
63 private JRadioButton mapCSSSearch;
64
65 private JRadioButton replace;
66 private JRadioButton add;
67 private JRadioButton remove;
68 private JRadioButton inSelection;
69
70 /**
71 * Constructs a new {@code SearchDialog}.
72 * @param initialValues initial search settings
73 * @param searchExpressionHistory list of all texts that were recently used in the search
74 * @param expertMode expert mode
75 */
76 public SearchDialog(SearchSetting initialValues, List<String> searchExpressionHistory, boolean expertMode) {
77 super(MainApplication.getMainFrame(),
78 initialValues instanceof Filter ? tr("Filter") : tr("Search"),
79 initialValues instanceof Filter ? tr("Submit filter") : tr("Search"),
80 tr("Cancel"));
81 this.searchSettings = new SearchSetting(initialValues);
82 setButtonIcons("dialogs/search", "cancel");
83 configureContextsensitiveHelp("/Action/Search", true /* show help button */);
84 setContent(buildPanel(searchExpressionHistory, expertMode));
85 }
86
87 private JPanel buildPanel(List<String> searchExpressionHistory, boolean expertMode) {
88
89 // prepare the combo box with the search expressions
90 JLabel label = new JLabel(searchSettings instanceof Filter ? tr("Filter string:") : tr("Search string:"));
91
92 String tooltip = tr("Enter the search expression");
93 hcbSearchString.setText(searchSettings.text);
94 hcbSearchString.setToolTipText(tooltip);
95
96 // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement()
97 Collections.reverse(searchExpressionHistory);
98 hcbSearchString.setPossibleItems(searchExpressionHistory);
99 hcbSearchString.setPreferredSize(new Dimension(40, hcbSearchString.getPreferredSize().height));
100 label.setLabelFor(hcbSearchString);
101
102 replace = new JRadioButton(tr("select"), searchSettings.mode == SearchMode.replace);
103 add = new JRadioButton(tr("add to selection"), searchSettings.mode == SearchMode.add);
104 remove = new JRadioButton(tr("remove from selection"), searchSettings.mode == SearchMode.remove);
105 inSelection = new JRadioButton(tr("find in selection"), searchSettings.mode == SearchMode.in_selection);
106 ButtonGroup bg = new ButtonGroup();
107 bg.add(replace);
108 bg.add(add);
109 bg.add(remove);
110 bg.add(inSelection);
111
112 caseSensitive = new JCheckBox(tr("case sensitive"), searchSettings.caseSensitive);
113 allElements = new JCheckBox(tr("all objects"), searchSettings.allElements);
114 allElements.setToolTipText(tr("Also include incomplete and deleted objects in search."));
115 addOnToolbar = new JCheckBox(tr("add toolbar button"), false);
116 addOnToolbar.setToolTipText(tr("Add a button with this search expression to the toolbar."));
117
118 standardSearch = new JRadioButton(tr("standard"), !searchSettings.regexSearch && !searchSettings.mapCSSSearch);
119 regexSearch = new JRadioButton(tr("regular expression"), searchSettings.regexSearch);
120 mapCSSSearch = new JRadioButton(tr("MapCSS selector"), searchSettings.mapCSSSearch);
121 ButtonGroup bg2 = new ButtonGroup();
122 bg2.add(standardSearch);
123 bg2.add(regexSearch);
124 bg2.add(mapCSSSearch);
125
126 JPanel selectionSettings = new JPanel(new GridBagLayout());
127 selectionSettings.setBorder(BorderFactory.createTitledBorder(tr("Results")));
128 selectionSettings.add(replace, GBC.eol().anchor(GBC.WEST).fill(GBC.HORIZONTAL));
129 selectionSettings.add(add, GBC.eol());
130 selectionSettings.add(remove, GBC.eol());
131 selectionSettings.add(inSelection, GBC.eop());
132
133 JPanel additionalSettings = new JPanel(new GridBagLayout());
134 additionalSettings.setBorder(BorderFactory.createTitledBorder(tr("Options")));
135 additionalSettings.add(caseSensitive, GBC.eol().anchor(GBC.WEST).fill(GBC.HORIZONTAL));
136
137 JPanel left = new JPanel(new GridBagLayout());
138
139 left.add(selectionSettings, GBC.eol().fill(GBC.BOTH));
140 left.add(additionalSettings, GBC.eol().fill(GBC.BOTH));
141
142 if (expertMode) {
143 additionalSettings.add(allElements, GBC.eol());
144 additionalSettings.add(addOnToolbar, GBC.eop());
145
146 JPanel searchOptions = new JPanel(new GridBagLayout());
147 searchOptions.setBorder(BorderFactory.createTitledBorder(tr("Search syntax")));
148 searchOptions.add(standardSearch, GBC.eol().anchor(GBC.WEST).fill(GBC.HORIZONTAL));
149 searchOptions.add(regexSearch, GBC.eol());
150 searchOptions.add(mapCSSSearch, GBC.eol());
151
152 left.add(searchOptions, GBC.eol().fill(GBC.BOTH));
153 }
154
155 JPanel right = buildHintsSection(hcbSearchString, expertMode);
156 JPanel top = new JPanel(new GridBagLayout());
157 top.add(label, GBC.std().insets(0, 0, 5, 0));
158 top.add(hcbSearchString, GBC.eol().fill(GBC.HORIZONTAL));
159
160 JTextComponent editorComponent = hcbSearchString.getEditorComponent();
161 Document document = editorComponent.getDocument();
162
163 /*
164 * Setup the logic to validate the contents of the search text field which is executed
165 * every time the content of the field has changed. If the query is incorrect, then
166 * the text field is colored red.
167 */
168 document.addDocumentListener(new AbstractTextComponentValidator(editorComponent) {
169
170 @Override
171 public void validate() {
172 if (!isValid()) {
173 feedbackInvalid(tr("Invalid search expression"));
174 } else {
175 feedbackValid(tooltip);
176 }
177 }
178
179 @Override
180 public boolean isValid() {
181 try {
182 SearchSetting ss = new SearchSetting();
183 ss.text = hcbSearchString.getText();
184 ss.caseSensitive = caseSensitive.isSelected();
185 ss.regexSearch = regexSearch.isSelected();
186 ss.mapCSSSearch = mapCSSSearch.isSelected();
187 SearchCompiler.compile(ss);
188 return true;
189 } catch (SearchParseError | MapCSSException e) {
190 return false;
191 }
192 }
193 });
194
195 /*
196 * Setup the logic to append preset queries to the search text field according to
197 * selected preset by the user. Every query is of the form ' group/sub-group/.../presetName'
198 * if the corresponding group of the preset exists, otherwise it is simply ' presetName'.
199 */
200 TaggingPresetSelector selector = new TaggingPresetSelector(false, false);
201 selector.setBorder(BorderFactory.createTitledBorder(tr("Search by preset")));
202 selector.setDblClickListener(ev -> setPresetDblClickListener(selector, editorComponent));
203
204 JPanel p = new JPanel(new GridBagLayout());
205 p.add(top, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 5, 0));
206 p.add(left, GBC.std().anchor(GBC.NORTH).insets(5, 10, 10, 0).fill(GBC.VERTICAL));
207 p.add(right, GBC.std().fill(GBC.BOTH).insets(0, 10, 0, 0));
208 p.add(selector, GBC.eol().fill(GBC.BOTH).insets(0, 10, 0, 0));
209
210 return p;
211 }
212
213 @Override
214 protected void buttonAction(int buttonIndex, ActionEvent evt) {
215 if (buttonIndex == 0) {
216 try {
217 SearchSetting ss = new SearchSetting();
218 ss.text = hcbSearchString.getText();
219 ss.caseSensitive = caseSensitive.isSelected();
220 ss.regexSearch = regexSearch.isSelected();
221 ss.mapCSSSearch = mapCSSSearch.isSelected();
222 SearchCompiler.compile(ss);
223 super.buttonAction(buttonIndex, evt);
224 } catch (SearchParseError | MapCSSException e) {
225 Logging.debug(e);
226 JOptionPane.showMessageDialog(
227 MainApplication.getMainFrame(),
228 "<html>" + tr("Search expression is not valid: \n\n {0}",
229 e.getMessage().replace("<html>", "").replace("</html>", "")).replace("\n", "<br>") +
230 "</html>",
231 tr("Invalid search expression"),
232 JOptionPane.ERROR_MESSAGE);
233 }
234 } else {
235 super.buttonAction(buttonIndex, evt);
236 }
237 }
238
239 /**
240 * Returns the search settings chosen by user.
241 * @return the search settings chosen by user
242 */
243 public SearchSetting getSearchSettings() {
244 searchSettings.text = hcbSearchString.getText();
245 searchSettings.caseSensitive = caseSensitive.isSelected();
246 searchSettings.allElements = allElements.isSelected();
247 searchSettings.regexSearch = regexSearch.isSelected();
248 searchSettings.mapCSSSearch = mapCSSSearch.isSelected();
249
250 if (inSelection.isSelected()) {
251 searchSettings.mode = SearchMode.in_selection;
252 } else if (replace.isSelected()) {
253 searchSettings.mode = SearchMode.replace;
254 } else if (add.isSelected()) {
255 searchSettings.mode = SearchMode.add;
256 } else {
257 searchSettings.mode = SearchMode.remove;
258 }
259 return searchSettings;
260 }
261
262 /**
263 * Determines if the "add toolbar button" checkbox is selected.
264 * @return {@code true} if the "add toolbar button" checkbox is selected
265 */
266 public boolean isAddOnToolbar() {
267 return addOnToolbar.isSelected();
268 }
269
270 private static JPanel buildHintsSection(HistoryComboBox hcbSearchString, boolean expertMode) {
271 JPanel hintPanel = new JPanel(new GridBagLayout());
272 hintPanel.setBorder(BorderFactory.createTitledBorder(tr("Hints")));
273
274 hintPanel.add(new SearchKeywordRow(hcbSearchString)
275 .addTitle(tr("basics"))
276 .addKeyword(tr("Baker Street"), null, tr("''Baker'' and ''Street'' in any key"))
277 .addKeyword(tr("\"Baker Street\""), "\"\"", tr("''Baker Street'' in any key"))
278 .addKeyword("<i>key</i>:<i>valuefragment</i>", null,
279 tr("''valuefragment'' anywhere in ''key''"),
280 trc("search string example", "name:str matches name=Bakerstreet"))
281 .addKeyword("-<i>key</i>:<i>valuefragment</i>", null, tr("''valuefragment'' nowhere in ''key''")),
282 GBC.eol());
283 hintPanel.add(new SearchKeywordRow(hcbSearchString)
284 .addKeyword("<i>key</i>", null, tr("matches if ''key'' exists"))
285 .addKeyword("<i>key</i>=<i>value</i>", null, tr("''key'' with exactly ''value''"))
286 .addKeyword("<i>key</i>=*", null, tr("''key'' with any value"))
287 .addKeyword("<i>key</i>=", null, tr("''key'' with empty value"))
288 .addKeyword("*=<i>value</i>", null, tr("''value'' in any key"))
289 .addKeyword("<i>key</i>><i>value</i>", null, tr("matches if ''key'' is greater than ''value'' (analogously, less than)"))
290 .addKeyword("\"key\"=\"value\"", "\"\"=\"\"",
291 tr("to quote operators.<br>Within quoted strings the <b>\"</b> and <b>\\</b> characters need to be escaped " +
292 "by a preceding <b>\\</b> (e.g. <b>\\\"</b> and <b>\\\\</b>)."),
293 trc("search string example", "name=\"Baker Street\""),
294 "\"addr:street\""),
295 GBC.eol().anchor(GBC.CENTER));
296 hintPanel.add(new SearchKeywordRow(hcbSearchString)
297 .addTitle(tr("combinators"))
298 .addKeyword("<i>expr</i> <i>expr</i>", null,
299 tr("logical and (both expressions have to be satisfied)"),
300 trc("search string example", "Baker Street"))
301 .addKeyword("<i>expr</i> | <i>expr</i>", "| ", tr("logical or (at least one expression has to be satisfied)"))
302 .addKeyword("<i>expr</i> OR <i>expr</i>", "OR ", tr("logical or (at least one expression has to be satisfied)"))
303 .addKeyword("-<i>expr</i>", null, tr("logical not"))
304 .addKeyword("(<i>expr</i>)", "()", tr("use parenthesis to group expressions")),
305 GBC.eol());
306
307 if (expertMode) {
308 hintPanel.add(new SearchKeywordRow(hcbSearchString)
309 .addTitle(tr("objects"))
310 .addKeyword("type:node", "type:node ", tr("all nodes"))
311 .addKeyword("type:way", "type:way ", tr("all ways"))
312 .addKeyword("type:relation", "type:relation ", tr("all relations"))
313 .addKeyword("closed", "closed ", tr("all closed ways"))
314 .addKeyword("untagged", "untagged ", tr("object without useful tags")),
315 GBC.eol());
316 hintPanel.add(new SearchKeywordRow(hcbSearchString)
317 .addKeyword("preset:\"Annotation/Address\"", "preset:\"Annotation/Address\"",
318 tr("all objects that use the address preset"))
319 .addKeyword("preset:\"Geography/Nature/*\"", "preset:\"Geography/Nature/*\"",
320 tr("all objects that use any preset under the Geography/Nature group")),
321 GBC.eol().anchor(GBC.CENTER));
322 hintPanel.add(new SearchKeywordRow(hcbSearchString)
323 .addTitle(tr("metadata"))
324 .addKeyword("user:", "user:", tr("objects changed by author"),
325 trc("search string example", "user:<i>OSM username</i> (objects with the author <i>OSM username</i>)"),
326 trc("search string example", "user:anonymous (objects without an assigned author)"))
327 .addKeyword("id:", "id:", tr("objects with given ID"),
328 trc("search string example", "id:0 (new objects)"))
329 .addKeyword("version:", "version:", tr("objects with given version"),
330 trc("search string example", "version:0 (objects without an assigned version)"))
331 .addKeyword("changeset:", "changeset:", tr("objects with given changeset ID"),
332 trc("search string example", "changeset:0 (objects without an assigned changeset)"))
333 .addKeyword("timestamp:", "timestamp:", tr("objects with last modification timestamp within range"), "timestamp:2012/",
334 "timestamp:2008/2011-02-04T12"),
335 GBC.eol());
336 hintPanel.add(new SearchKeywordRow(hcbSearchString)
337 .addTitle(tr("properties"))
338 .addKeyword("nodes:<i>20-</i>", "nodes:", tr("ways with at least 20 nodes, or relations containing at least 20 nodes"))
339 .addKeyword("ways:<i>3-</i>", "ways:", tr("nodes with at least 3 referring ways, or relations containing at least 3 ways"))
340 .addKeyword("tags:<i>5-10</i>", "tags:", tr("objects having 5 to 10 tags"))
341 .addKeyword("role:", "role:", tr("objects with given role in a relation"))
342 .addKeyword("areasize:<i>-100</i>", "areasize:", tr("closed ways with an area of 100 m\u00b2"))
343 .addKeyword("waylength:<i>200-</i>", "waylength:", tr("ways with a length of 200 m or more")),
344 GBC.eol());
345 hintPanel.add(new SearchKeywordRow(hcbSearchString)
346 .addTitle(tr("state"))
347 .addKeyword("modified", "modified ", tr("all modified objects"))
348 .addKeyword("new", "new ", tr("all new objects"))
349 .addKeyword("selected", "selected ", tr("all selected objects"))
350 .addKeyword("incomplete", "incomplete ", tr("all incomplete objects"))
351 .addKeyword("deleted", "deleted ", tr("all deleted objects (checkbox <b>{0}</b> must be enabled)", tr("all objects"))),
352 GBC.eol());
353 hintPanel.add(new SearchKeywordRow(hcbSearchString)
354 .addTitle(tr("related objects"))
355 .addKeyword("child <i>expr</i>", "child ", tr("all children of objects matching the expression"), "child building")
356 .addKeyword("parent <i>expr</i>", "parent ", tr("all parents of objects matching the expression"), "parent bus_stop")
357 .addKeyword("hasRole:<i>stop</i>", "hasRole:", tr("relation containing a member of role <i>stop</i>"))
358 .addKeyword("role:<i>stop</i>", "role:", tr("objects being part of a relation as role <i>stop</i>"))
359 .addKeyword("nth:<i>7</i>", "nth:",
360 tr("n-th member of relation and/or n-th node of way"), "nth:5 (child type:relation)", "nth:-1")
361 .addKeyword("nth%:<i>7</i>", "nth%:",
362 tr("every n-th member of relation and/or every n-th node of way"), "nth%:100 (child waterway)"),
363 GBC.eol());
364 hintPanel.add(new SearchKeywordRow(hcbSearchString)
365 .addTitle(tr("view"))
366 .addKeyword("inview", "inview ", tr("objects in current view"))
367 .addKeyword("allinview", "allinview ", tr("objects (and all its way nodes / relation members) in current view"))
368 .addKeyword("indownloadedarea", "indownloadedarea ", tr("objects in downloaded area"))
369 .addKeyword("allindownloadedarea", "allindownloadedarea ",
370 tr("objects (and all its way nodes / relation members) in downloaded area")),
371 GBC.eol());
372 }
373
374 return hintPanel;
375 }
376
377 /**
378 *
379 * @param selector Selector component that the user interacts with
380 * @param searchEditor Editor for search queries
381 */
382 private static void setPresetDblClickListener(TaggingPresetSelector selector, JTextComponent searchEditor) {
383 TaggingPreset selectedPreset = selector.getSelectedPresetAndUpdateClassification();
384
385 if (selectedPreset == null) {
386 return;
387 }
388
389 // Make sure that the focus is transferred to the search text field from the selector component
390 searchEditor.requestFocusInWindow();
391
392 // In order to make interaction with the search dialog simpler, we make sure that
393 // if autocompletion triggers and the text field is not in focus, the correct area is selected.
394 // We first request focus and then execute the selection logic.
395 // invokeLater allows us to defer the selection until waiting for focus.
396 SwingUtilities.invokeLater(() -> {
397 int textOffset = searchEditor.getCaretPosition();
398 String presetSearchQuery = " preset:" +
399 "\"" + selectedPreset.getRawName() + "\"";
400 try {
401 searchEditor.getDocument().insertString(textOffset, presetSearchQuery, null);
402 } catch (BadLocationException e1) {
403 throw new JosmRuntimeException(e1.getMessage(), e1);
404 }
405 });
406 }
407
408 private static class SearchKeywordRow extends JPanel {
409
410 private final HistoryComboBox hcb;
411
412 SearchKeywordRow(HistoryComboBox hcb) {
413 super(new FlowLayout(FlowLayout.LEFT));
414 this.hcb = hcb;
415 }
416
417 /**
418 * Adds the title (prefix) label at the beginning of the row. Should be called only once.
419 * @param title English title
420 * @return {@code this} for easy chaining
421 */
422 public SearchKeywordRow addTitle(String title) {
423 add(new JLabel(tr("{0}: ", title)));
424 return this;
425 }
426
427 /**
428 * Adds an example keyword label at the end of the row. Can be called several times.
429 * @param displayText displayed HTML text
430 * @param insertText optional: if set, makes the label clickable, and {@code insertText} will be inserted in search string
431 * @param description optional: HTML text to be displayed in the tooltip
432 * @param examples optional: examples joined as HTML list in the tooltip
433 * @return {@code this} for easy chaining
434 */
435 public SearchKeywordRow addKeyword(String displayText, final String insertText, String description, String... examples) {
436 JLabel label = new JLabel("<html>"
437 + "<style>td{border:1px solid gray; font-weight:normal;}</style>"
438 + "<table><tr><td>" + displayText + "</td></tr></table></html>");
439 add(label);
440 if (description != null || examples.length > 0) {
441 label.setToolTipText("<html>"
442 + description
443 + (examples.length > 0 ? Utils.joinAsHtmlUnorderedList(Arrays.asList(examples)) : "")
444 + "</html>");
445 }
446 if (insertText != null) {
447 label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
448 label.addMouseListener(new MouseAdapter() {
449
450 @Override
451 public void mouseClicked(MouseEvent e) {
452 JTextComponent tf = hcb.getEditorComponent();
453
454 // Make sure that the focus is transferred to the search text field from the selector component
455 if (!tf.hasFocus()) {
456 tf.requestFocusInWindow();
457 }
458
459 // In order to make interaction with the search dialog simpler, we make sure that
460 // if autocompletion triggers and the text field is not in focus, the correct area is selected.
461 // We first request focus and then execute the selection logic.
462 // invokeLater allows us to defer the selection until waiting for focus.
463 SwingUtilities.invokeLater(() -> {
464 try {
465 tf.getDocument().insertString(tf.getCaretPosition(), ' ' + insertText, null);
466 } catch (BadLocationException ex) {
467 throw new JosmRuntimeException(ex.getMessage(), ex);
468 }
469 });
470 }
471 });
472 }
473 return this;
474 }
475 }
476}
Note: See TracBrowser for help on using the repository browser.