source: josm/trunk/src/org/openstreetmap/josm/gui/dialogs/properties/TagEditHelper.java@ 12656

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

see #15182 - move SearchCompiler from actions.search to data.osm.search

  • Property svn:eol-style set to native
File size: 46.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.dialogs.properties;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.BorderLayout;
8import java.awt.Component;
9import java.awt.Container;
10import java.awt.Cursor;
11import java.awt.Dimension;
12import java.awt.FlowLayout;
13import java.awt.Font;
14import java.awt.GridBagConstraints;
15import java.awt.GridBagLayout;
16import java.awt.datatransfer.Clipboard;
17import java.awt.datatransfer.Transferable;
18import java.awt.event.ActionEvent;
19import java.awt.event.FocusAdapter;
20import java.awt.event.FocusEvent;
21import java.awt.event.InputEvent;
22import java.awt.event.KeyEvent;
23import java.awt.event.MouseAdapter;
24import java.awt.event.MouseEvent;
25import java.awt.event.WindowAdapter;
26import java.awt.event.WindowEvent;
27import java.awt.image.BufferedImage;
28import java.text.Normalizer;
29import java.util.ArrayList;
30import java.util.Arrays;
31import java.util.Collection;
32import java.util.Collections;
33import java.util.Comparator;
34import java.util.HashMap;
35import java.util.List;
36import java.util.Map;
37import java.util.Objects;
38import java.util.TreeMap;
39import java.util.stream.IntStream;
40
41import javax.swing.AbstractAction;
42import javax.swing.Action;
43import javax.swing.Box;
44import javax.swing.ButtonGroup;
45import javax.swing.DefaultListCellRenderer;
46import javax.swing.ImageIcon;
47import javax.swing.JCheckBoxMenuItem;
48import javax.swing.JComponent;
49import javax.swing.JLabel;
50import javax.swing.JList;
51import javax.swing.JMenu;
52import javax.swing.JOptionPane;
53import javax.swing.JPanel;
54import javax.swing.JPopupMenu;
55import javax.swing.JRadioButtonMenuItem;
56import javax.swing.JTable;
57import javax.swing.KeyStroke;
58import javax.swing.ListCellRenderer;
59import javax.swing.SwingUtilities;
60import javax.swing.table.DefaultTableModel;
61import javax.swing.text.JTextComponent;
62
63import org.openstreetmap.josm.Main;
64import org.openstreetmap.josm.actions.JosmAction;
65import org.openstreetmap.josm.actions.search.SearchAction;
66import org.openstreetmap.josm.command.ChangePropertyCommand;
67import org.openstreetmap.josm.command.Command;
68import org.openstreetmap.josm.command.SequenceCommand;
69import org.openstreetmap.josm.data.osm.OsmPrimitive;
70import org.openstreetmap.josm.data.osm.Tag;
71import org.openstreetmap.josm.data.osm.search.SearchParseError;
72import org.openstreetmap.josm.data.osm.search.SearchCompiler;
73import org.openstreetmap.josm.data.preferences.BooleanProperty;
74import org.openstreetmap.josm.data.preferences.CollectionProperty;
75import org.openstreetmap.josm.data.preferences.EnumProperty;
76import org.openstreetmap.josm.data.preferences.IntegerProperty;
77import org.openstreetmap.josm.data.preferences.StringProperty;
78import org.openstreetmap.josm.gui.ExtendedDialog;
79import org.openstreetmap.josm.gui.IExtendedDialog;
80import org.openstreetmap.josm.gui.MainApplication;
81import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils;
82import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
83import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingComboBox;
84import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionListItem;
85import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
86import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
87import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
88import org.openstreetmap.josm.gui.util.GuiHelper;
89import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
90import org.openstreetmap.josm.io.XmlWriter;
91import org.openstreetmap.josm.tools.GBC;
92import org.openstreetmap.josm.tools.Logging;
93import org.openstreetmap.josm.tools.Shortcut;
94import org.openstreetmap.josm.tools.Utils;
95import org.openstreetmap.josm.tools.WindowGeometry;
96
97/**
98 * Class that helps PropertiesDialog add and edit tag values.
99 * @since 5633
100 */
101public class TagEditHelper {
102
103 private final JTable tagTable;
104 private final DefaultTableModel tagData;
105 private final Map<String, Map<String, Integer>> valueCount;
106
107 // Selection that we are editing by using both dialogs
108 protected Collection<OsmPrimitive> sel;
109
110 private String changedKey;
111 private String objKey;
112
113 static final Comparator<AutoCompletionListItem> DEFAULT_AC_ITEM_COMPARATOR =
114 (o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
115
116 /** Default number of recent tags */
117 public static final int DEFAULT_LRU_TAGS_NUMBER = 5;
118 /** Maximum number of recent tags */
119 public static final int MAX_LRU_TAGS_NUMBER = 30;
120
121 /** Use English language for tag by default */
122 public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE = new BooleanProperty("properties.fix-tag-combobox-locale", false);
123 /** Whether recent tags must be remembered */
124 public static final BooleanProperty PROPERTY_REMEMBER_TAGS = new BooleanProperty("properties.remember-recently-added-tags", true);
125 /** Number of recent tags */
126 public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER = new IntegerProperty("properties.recently-added-tags",
127 DEFAULT_LRU_TAGS_NUMBER);
128 /** The preference storage of recent tags */
129 public static final CollectionProperty PROPERTY_RECENT_TAGS = new CollectionProperty("properties.recent-tags",
130 Collections.<String>emptyList());
131 public static final StringProperty PROPERTY_TAGS_TO_IGNORE = new StringProperty("properties.recent-tags.ignore",
132 new SearchAction.SearchSetting().writeToString());
133
134 /**
135 * What to do with recent tags where keys already exist
136 */
137 private enum RecentExisting {
138 ENABLE,
139 DISABLE,
140 HIDE
141 }
142
143 /**
144 * Preference setting for popup menu item "Recent tags with existing key"
145 */
146 public static final EnumProperty<RecentExisting> PROPERTY_RECENT_EXISTING = new EnumProperty<>(
147 "properties.recently-added-tags-existing-key", RecentExisting.class, RecentExisting.DISABLE);
148
149 /**
150 * What to do after applying tag
151 */
152 private enum RefreshRecent {
153 NO,
154 STATUS,
155 REFRESH
156 }
157
158 /**
159 * Preference setting for popup menu item "Refresh recent tags list after applying tag"
160 */
161 public static final EnumProperty<RefreshRecent> PROPERTY_REFRESH_RECENT = new EnumProperty<>(
162 "properties.refresh-recently-added-tags", RefreshRecent.class, RefreshRecent.STATUS);
163
164 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER);
165 SearchAction.SearchSetting tagsToIgnore;
166
167 /**
168 * Copy of recently added tags in sorted from newest to oldest order.
169 *
170 * We store the maximum number of recent tags to allow dynamic change of number of tags shown in the preferences.
171 * Used to cache initial status.
172 */
173 private List<Tag> tags;
174
175 static {
176 // init user input based on recent tags
177 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER);
178 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS);
179 recentTags.toList().forEach(tag -> AutoCompletionManager.rememberUserInput(tag.getKey(), tag.getValue(), false));
180 }
181
182 /**
183 * Constructs a new {@code TagEditHelper}.
184 * @param tagTable tag table
185 * @param propertyData table model
186 * @param valueCount tag value count
187 */
188 public TagEditHelper(JTable tagTable, DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
189 this.tagTable = tagTable;
190 this.tagData = propertyData;
191 this.valueCount = valueCount;
192 }
193
194 /**
195 * Finds the key from given row of tag editor.
196 * @param viewRow index of row
197 * @return key of tag
198 */
199 public final String getDataKey(int viewRow) {
200 return tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 0).toString();
201 }
202
203 /**
204 * Determines if the given tag key is already used (by all selected primitives, not just some of them)
205 * @param key the key to check
206 * @return {@code true} if the key is used by all selected primitives (key not unset for at least one primitive)
207 */
208 @SuppressWarnings("unchecked")
209 boolean containsDataKey(String key) {
210 return IntStream.range(0, tagData.getRowCount())
211 .anyMatch(i -> key.equals(tagData.getValueAt(i, 0)) /* sic! do not use getDataKey*/
212 && !((Map<String, Integer>) tagData.getValueAt(i, 1)).containsKey("") /* sic! do not use getDataValues*/);
213 }
214
215 /**
216 * Finds the values from given row of tag editor.
217 * @param viewRow index of row
218 * @return map of values and number of occurrences
219 */
220 @SuppressWarnings("unchecked")
221 public final Map<String, Integer> getDataValues(int viewRow) {
222 return (Map<String, Integer>) tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 1);
223 }
224
225 /**
226 * Open the add selection dialog and add a new key/value to the table (and
227 * to the dataset, of course).
228 */
229 public void addTag() {
230 changedKey = null;
231 sel = Main.main.getInProgressSelection();
232 if (sel == null || sel.isEmpty())
233 return;
234
235 final AddTagsDialog addDialog = getAddTagsDialog();
236
237 addDialog.showDialog();
238
239 addDialog.destroyActions();
240 if (addDialog.getValue() == 1)
241 addDialog.performTagAdding();
242 else
243 addDialog.undoAllTagsAdding();
244 }
245
246 /**
247 * Returns a new {@code AddTagsDialog}.
248 * @return a new {@code AddTagsDialog}
249 */
250 protected AddTagsDialog getAddTagsDialog() {
251 return new AddTagsDialog();
252 }
253
254 /**
255 * Edit the value in the tags table row.
256 * @param row The row of the table from which the value is edited.
257 * @param focusOnKey Determines if the initial focus should be set on key instead of value
258 * @since 5653
259 */
260 public void editTag(final int row, boolean focusOnKey) {
261 changedKey = null;
262 sel = Main.main.getInProgressSelection();
263 if (sel == null || sel.isEmpty())
264 return;
265
266 String key = getDataKey(row);
267 objKey = key;
268
269 final IEditTagDialog editDialog = getEditTagDialog(row, focusOnKey, key);
270 editDialog.showDialog();
271 if (editDialog.getValue() != 1)
272 return;
273 editDialog.performTagEdit();
274 }
275
276 /**
277 * Extracted interface of {@link EditTagDialog}.
278 */
279 protected interface IEditTagDialog extends IExtendedDialog {
280 /**
281 * Edit tags of multiple selected objects according to selected ComboBox values
282 * If value == "", tag will be deleted
283 * Confirmations may be needed.
284 */
285 void performTagEdit();
286 }
287
288 protected IEditTagDialog getEditTagDialog(int row, boolean focusOnKey, String key) {
289 return new EditTagDialog(key, getDataValues(row), focusOnKey);
290 }
291
292 /**
293 * If during last editProperty call user changed the key name, this key will be returned
294 * Elsewhere, returns null.
295 * @return The modified key, or {@code null}
296 */
297 public String getChangedKey() {
298 return changedKey;
299 }
300
301 /**
302 * Reset last changed key.
303 */
304 public void resetChangedKey() {
305 changedKey = null;
306 }
307
308 /**
309 * For a given key k, return a list of keys which are used as keys for
310 * auto-completing values to increase the search space.
311 * @param key the key k
312 * @return a list of keys
313 */
314 private static List<String> getAutocompletionKeys(String key) {
315 if ("name".equals(key) || "addr:street".equals(key))
316 return Arrays.asList("addr:street", "name");
317 else
318 return Arrays.asList(key);
319 }
320
321 /**
322 * Load recently used tags from preferences if needed.
323 */
324 public void loadTagsIfNeeded() {
325 loadTagsToIgnore();
326 if (PROPERTY_REMEMBER_TAGS.get() && recentTags.isEmpty()) {
327 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS);
328 }
329 }
330
331 void loadTagsToIgnore() {
332 final SearchAction.SearchSetting searchSetting = Utils.firstNonNull(
333 SearchAction.SearchSetting.readFromString(PROPERTY_TAGS_TO_IGNORE.get()), new SearchAction.SearchSetting());
334 if (!Objects.equals(tagsToIgnore, searchSetting)) {
335 try {
336 tagsToIgnore = searchSetting;
337 recentTags.setTagsToIgnore(tagsToIgnore);
338 } catch (SearchParseError parseError) {
339 warnAboutParseError(parseError);
340 tagsToIgnore = new SearchAction.SearchSetting();
341 recentTags.setTagsToIgnore(SearchCompiler.Never.INSTANCE);
342 }
343 }
344 }
345
346 private static void warnAboutParseError(SearchParseError parseError) {
347 Logging.warn(parseError);
348 JOptionPane.showMessageDialog(
349 Main.parent,
350 parseError.getMessage(),
351 tr("Error"),
352 JOptionPane.ERROR_MESSAGE
353 );
354 }
355
356 /**
357 * Store recently used tags in preferences if needed.
358 */
359 public void saveTagsIfNeeded() {
360 if (PROPERTY_REMEMBER_TAGS.get() && !recentTags.isEmpty()) {
361 recentTags.saveToPreference(PROPERTY_RECENT_TAGS);
362 }
363 }
364
365 /**
366 * Update cache of recent tags used for displaying tags.
367 */
368 private void cacheRecentTags() {
369 tags = recentTags.toList();
370 Collections.reverse(tags);
371 }
372
373 /**
374 * Warns user about a key being overwritten.
375 * @param action The action done by the user. Must state what key is changed
376 * @param togglePref The preference to save the checkbox state to
377 * @return {@code true} if the user accepts to overwrite key, {@code false} otherwise
378 */
379 private static boolean warnOverwriteKey(String action, String togglePref) {
380 return new ExtendedDialog(
381 Main.parent,
382 tr("Overwrite key"),
383 tr("Replace"), tr("Cancel"))
384 .setButtonIcons("purge", "cancel")
385 .setContent(action+'\n'+ tr("The new key is already used, overwrite values?"))
386 .setCancelButton(2)
387 .toggleEnable(togglePref)
388 .showDialog().getValue() == 1;
389 }
390
391 protected class EditTagDialog extends AbstractTagsDialog implements IEditTagDialog {
392 private final String key;
393 private final transient Map<String, Integer> m;
394 private final transient Comparator<AutoCompletionListItem> usedValuesAwareComparator;
395
396 private final transient ListCellRenderer<AutoCompletionListItem> cellRenderer = new ListCellRenderer<AutoCompletionListItem>() {
397 private final DefaultListCellRenderer def = new DefaultListCellRenderer();
398 @Override
399 public Component getListCellRendererComponent(JList<? extends AutoCompletionListItem> list,
400 AutoCompletionListItem value, int index, boolean isSelected, boolean cellHasFocus) {
401 Component c = def.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
402 if (c instanceof JLabel) {
403 String str = value.getValue();
404 if (valueCount.containsKey(objKey)) {
405 Map<String, Integer> map = valueCount.get(objKey);
406 if (map.containsKey(str)) {
407 str = tr("{0} ({1})", str, map.get(str));
408 c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD));
409 }
410 }
411 ((JLabel) c).setText(str);
412 }
413 return c;
414 }
415 };
416
417 protected EditTagDialog(String key, Map<String, Integer> map, final boolean initialFocusOnKey) {
418 super(Main.parent, trn("Change value?", "Change values?", map.size()), tr("OK"), tr("Cancel"));
419 setButtonIcons("ok", "cancel");
420 setCancelButton(2);
421 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);
422 this.key = key;
423 this.m = map;
424
425 usedValuesAwareComparator = (o1, o2) -> {
426 boolean c1 = m.containsKey(o1.getValue());
427 boolean c2 = m.containsKey(o2.getValue());
428 if (c1 == c2)
429 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
430 else if (c1)
431 return -1;
432 else
433 return +1;
434 };
435
436 JPanel mainPanel = new JPanel(new BorderLayout());
437
438 String msg = "<html>"+trn("This will change {0} object.",
439 "This will change up to {0} objects.", sel.size(), sel.size())
440 +"<br><br>("+tr("An empty value deletes the tag.", key)+")</html>";
441
442 mainPanel.add(new JLabel(msg), BorderLayout.NORTH);
443
444 JPanel p = new JPanel(new GridBagLayout());
445 mainPanel.add(p, BorderLayout.CENTER);
446
447 AutoCompletionManager autocomplete = MainApplication.getLayerManager().getEditLayer().data.getAutoCompletionManager();
448 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
449 keyList.sort(DEFAULT_AC_ITEM_COMPARATOR);
450
451 keys = new AutoCompletingComboBox(key);
452 keys.setPossibleACItems(keyList);
453 keys.setEditable(true);
454 keys.setSelectedItem(key);
455
456 p.add(Box.createVerticalStrut(5), GBC.eol());
457 p.add(new JLabel(tr("Key")), GBC.std());
458 p.add(Box.createHorizontalStrut(10), GBC.std());
459 p.add(keys, GBC.eol().fill(GBC.HORIZONTAL));
460
461 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
462 valueList.sort(usedValuesAwareComparator);
463
464 final String selection = m.size() != 1 ? tr("<different>") : m.entrySet().iterator().next().getKey();
465
466 values = new AutoCompletingComboBox(selection);
467 values.setRenderer(cellRenderer);
468
469 values.setEditable(true);
470 values.setPossibleACItems(valueList);
471 values.setSelectedItem(selection);
472 values.getEditor().setItem(selection);
473 p.add(Box.createVerticalStrut(5), GBC.eol());
474 p.add(new JLabel(tr("Value")), GBC.std());
475 p.add(Box.createHorizontalStrut(10), GBC.std());
476 p.add(values, GBC.eol().fill(GBC.HORIZONTAL));
477 values.getEditor().addActionListener(e -> buttonAction(0, null));
478 addFocusAdapter(autocomplete, usedValuesAwareComparator);
479
480 setContent(mainPanel, false);
481
482 addWindowListener(new WindowAdapter() {
483 @Override
484 public void windowOpened(WindowEvent e) {
485 if (initialFocusOnKey) {
486 selectKeysComboBox();
487 } else {
488 selectValuesCombobox();
489 }
490 }
491 });
492 }
493
494 @Override
495 public void performTagEdit() {
496 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
497 value = Normalizer.normalize(value, Normalizer.Form.NFC);
498 if (value.isEmpty()) {
499 value = null; // delete the key
500 }
501 String newkey = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
502 newkey = Normalizer.normalize(newkey, Normalizer.Form.NFC);
503 if (newkey.isEmpty()) {
504 newkey = key;
505 value = null; // delete the key instead
506 }
507 if (key.equals(newkey) && tr("<different>").equals(value))
508 return;
509 if (key.equals(newkey) || value == null) {
510 MainApplication.undoRedo.add(new ChangePropertyCommand(sel, newkey, value));
511 AutoCompletionManager.rememberUserInput(newkey, value, true);
512 } else {
513 for (OsmPrimitive osm: sel) {
514 if (osm.get(newkey) != null) {
515 if (!warnOverwriteKey(tr("You changed the key from ''{0}'' to ''{1}''.", key, newkey),
516 "overwriteEditKey"))
517 return;
518 break;
519 }
520 }
521 Collection<Command> commands = new ArrayList<>();
522 commands.add(new ChangePropertyCommand(sel, key, null));
523 if (value.equals(tr("<different>"))) {
524 Map<String, List<OsmPrimitive>> map = new HashMap<>();
525 for (OsmPrimitive osm: sel) {
526 String val = osm.get(key);
527 if (val != null) {
528 if (map.containsKey(val)) {
529 map.get(val).add(osm);
530 } else {
531 List<OsmPrimitive> v = new ArrayList<>();
532 v.add(osm);
533 map.put(val, v);
534 }
535 }
536 }
537 for (Map.Entry<String, List<OsmPrimitive>> e: map.entrySet()) {
538 commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey()));
539 }
540 } else {
541 commands.add(new ChangePropertyCommand(sel, newkey, value));
542 AutoCompletionManager.rememberUserInput(newkey, value, false);
543 }
544 MainApplication.undoRedo.add(new SequenceCommand(
545 trn("Change properties of up to {0} object",
546 "Change properties of up to {0} objects", sel.size(), sel.size()),
547 commands));
548 }
549
550 changedKey = newkey;
551 }
552 }
553
554 protected abstract class AbstractTagsDialog extends ExtendedDialog {
555 protected AutoCompletingComboBox keys;
556 protected AutoCompletingComboBox values;
557
558 AbstractTagsDialog(Component parent, String title, String... buttonTexts) {
559 super(parent, title, buttonTexts);
560 addMouseListener(new PopupMenuLauncher(popupMenu));
561 }
562
563 @Override
564 public void setupDialog() {
565 super.setupDialog();
566 final Dimension size = getSize();
567 // Set resizable only in width
568 setMinimumSize(size);
569 setPreferredSize(size);
570 // setMaximumSize does not work, and never worked, but still it seems not to bother Oracle to fix this 10-year-old bug
571 // https://bugs.openjdk.java.net/browse/JDK-6200438
572 // https://bugs.openjdk.java.net/browse/JDK-6464548
573
574 setRememberWindowGeometry(getClass().getName() + ".geometry",
575 WindowGeometry.centerInWindow(Main.parent, size));
576 }
577
578 @Override
579 public void setVisible(boolean visible) {
580 // Do not want dialog to be resizable in height, as its size may increase each time because of the recently added tags
581 // So need to modify the stored geometry (size part only) in order to use the automatic positioning mechanism
582 if (visible) {
583 WindowGeometry geometry = initWindowGeometry();
584 Dimension storedSize = geometry.getSize();
585 Dimension size = getSize();
586 if (!storedSize.equals(size)) {
587 if (storedSize.width < size.width) {
588 storedSize.width = size.width;
589 }
590 if (storedSize.height != size.height) {
591 storedSize.height = size.height;
592 }
593 rememberWindowGeometry(geometry);
594 }
595 keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
596 }
597 super.setVisible(visible);
598 }
599
600 private void selectACComboBoxSavingUnixBuffer(AutoCompletingComboBox cb) {
601 // select combobox with saving unix system selection (middle mouse paste)
602 Clipboard sysSel = ClipboardUtils.getSystemSelection();
603 if (sysSel != null) {
604 Transferable old = ClipboardUtils.getClipboardContent(sysSel);
605 cb.requestFocusInWindow();
606 cb.getEditor().selectAll();
607 if (old != null) {
608 sysSel.setContents(old, null);
609 }
610 } else {
611 cb.requestFocusInWindow();
612 cb.getEditor().selectAll();
613 }
614 }
615
616 public void selectKeysComboBox() {
617 selectACComboBoxSavingUnixBuffer(keys);
618 }
619
620 public void selectValuesCombobox() {
621 selectACComboBoxSavingUnixBuffer(values);
622 }
623
624 /**
625 * Create a focus handling adapter and apply in to the editor component of value
626 * autocompletion box.
627 * @param autocomplete Manager handling the autocompletion
628 * @param comparator Class to decide what values are offered on autocompletion
629 * @return The created adapter
630 */
631 protected FocusAdapter addFocusAdapter(final AutoCompletionManager autocomplete, final Comparator<AutoCompletionListItem> comparator) {
632 // get the combo box' editor component
633 final JTextComponent editor = values.getEditorComponent();
634 // Refresh the values model when focus is gained
635 FocusAdapter focus = new FocusAdapter() {
636 @Override
637 public void focusGained(FocusEvent e) {
638 String key = keys.getEditor().getItem().toString();
639
640 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
641 valueList.sort(comparator);
642 Logging.trace("Focus gained by {0}, e={1}", values, e);
643 values.setPossibleACItems(valueList);
644 values.getEditor().selectAll();
645 objKey = key;
646 }
647 };
648 editor.addFocusListener(focus);
649 return focus;
650 }
651
652 protected JPopupMenu popupMenu = new JPopupMenu() {
653 private final JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem(
654 new AbstractAction(tr("Use English language for tag by default")) {
655 @Override
656 public void actionPerformed(ActionEvent e) {
657 boolean use = ((JCheckBoxMenuItem) e.getSource()).getState();
658 PROPERTY_FIX_TAG_LOCALE.put(use);
659 keys.setFixedLocale(use);
660 }
661 });
662 {
663 add(fixTagLanguageCb);
664 fixTagLanguageCb.setState(PROPERTY_FIX_TAG_LOCALE.get());
665 }
666 };
667 }
668
669 protected class AddTagsDialog extends AbstractTagsDialog {
670 private final List<JosmAction> recentTagsActions = new ArrayList<>();
671 protected final transient FocusAdapter focus;
672 private final JPanel mainPanel;
673 private JPanel recentTagsPanel;
674
675 // Counter of added commands for possible undo
676 private int commandCount;
677
678 protected AddTagsDialog() {
679 super(Main.parent, tr("Add value?"), tr("OK"), tr("Cancel"));
680 setButtonIcons("ok", "cancel");
681 setCancelButton(2);
682 configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */);
683
684 mainPanel = new JPanel(new GridBagLayout());
685 keys = new AutoCompletingComboBox();
686 values = new AutoCompletingComboBox();
687
688 mainPanel.add(new JLabel("<html>"+trn("This will change up to {0} object.",
689 "This will change up to {0} objects.", sel.size(), sel.size())
690 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL));
691
692 cacheRecentTags();
693 AutoCompletionManager autocomplete = MainApplication.getLayerManager().getEditLayer().data.getAutoCompletionManager();
694 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
695
696 // remove the object's tag keys from the list
697 keyList.removeIf(item -> containsDataKey(item.getValue()));
698
699 keyList.sort(DEFAULT_AC_ITEM_COMPARATOR);
700 keys.setPossibleACItems(keyList);
701 keys.setEditable(true);
702
703 mainPanel.add(keys, GBC.eop().fill(GBC.HORIZONTAL));
704
705 mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol());
706 values.setEditable(true);
707 mainPanel.add(values, GBC.eop().fill(GBC.HORIZONTAL));
708
709 // pre-fill first recent tag for which the key is not already present
710 tags.stream()
711 .filter(tag -> !containsDataKey(tag.getKey()))
712 .findFirst()
713 .ifPresent(tag -> {
714 keys.setSelectedItem(tag.getKey());
715 values.setSelectedItem(tag.getValue());
716 });
717
718 focus = addFocusAdapter(autocomplete, DEFAULT_AC_ITEM_COMPARATOR);
719 // fire focus event in advance or otherwise the popup list will be too small at first
720 focus.focusGained(null);
721
722 // Add tag on Shift-Enter
723 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
724 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK), "addAndContinue");
725 mainPanel.getActionMap().put("addAndContinue", new AbstractAction() {
726 @Override
727 public void actionPerformed(ActionEvent e) {
728 performTagAdding();
729 refreshRecentTags();
730 selectKeysComboBox();
731 }
732 });
733
734 suggestRecentlyAddedTags();
735
736 mainPanel.add(Box.createVerticalGlue(), GBC.eop().fill());
737 setContent(mainPanel, false);
738
739 selectKeysComboBox();
740
741 popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) {
742 @Override
743 public void actionPerformed(ActionEvent e) {
744 selectNumberOfTags();
745 suggestRecentlyAddedTags();
746 }
747 });
748
749 popupMenu.add(buildMenuRecentExisting());
750 popupMenu.add(buildMenuRefreshRecent());
751
752 JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem(
753 new AbstractAction(tr("Remember last used tags after a restart")) {
754 @Override
755 public void actionPerformed(ActionEvent e) {
756 boolean state = ((JCheckBoxMenuItem) e.getSource()).getState();
757 PROPERTY_REMEMBER_TAGS.put(state);
758 if (state)
759 saveTagsIfNeeded();
760 }
761 });
762 rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get());
763 popupMenu.add(rememberLastTags);
764 }
765
766 private JMenu buildMenuRecentExisting() {
767 JMenu menu = new JMenu(tr("Recent tags with existing key"));
768 TreeMap<RecentExisting, String> radios = new TreeMap<>();
769 radios.put(RecentExisting.ENABLE, tr("Enable"));
770 radios.put(RecentExisting.DISABLE, tr("Disable"));
771 radios.put(RecentExisting.HIDE, tr("Hide"));
772 ButtonGroup buttonGroup = new ButtonGroup();
773 for (final Map.Entry<RecentExisting, String> entry : radios.entrySet()) {
774 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) {
775 @Override
776 public void actionPerformed(ActionEvent e) {
777 PROPERTY_RECENT_EXISTING.put(entry.getKey());
778 suggestRecentlyAddedTags();
779 }
780 });
781 buttonGroup.add(radio);
782 radio.setSelected(PROPERTY_RECENT_EXISTING.get() == entry.getKey());
783 menu.add(radio);
784 }
785 return menu;
786 }
787
788 private JMenu buildMenuRefreshRecent() {
789 JMenu menu = new JMenu(tr("Refresh recent tags list after applying tag"));
790 TreeMap<RefreshRecent, String> radios = new TreeMap<>();
791 radios.put(RefreshRecent.NO, tr("No refresh"));
792 radios.put(RefreshRecent.STATUS, tr("Refresh tag status only (enabled / disabled)"));
793 radios.put(RefreshRecent.REFRESH, tr("Refresh tag status and list of recently added tags"));
794 ButtonGroup buttonGroup = new ButtonGroup();
795 for (final Map.Entry<RefreshRecent, String> entry : radios.entrySet()) {
796 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) {
797 @Override
798 public void actionPerformed(ActionEvent e) {
799 PROPERTY_REFRESH_RECENT.put(entry.getKey());
800 }
801 });
802 buttonGroup.add(radio);
803 radio.setSelected(PROPERTY_REFRESH_RECENT.get() == entry.getKey());
804 menu.add(radio);
805 }
806 return menu;
807 }
808
809 @Override
810 public void setContentPane(Container contentPane) {
811 final int commandDownMask = GuiHelper.getMenuShortcutKeyMaskEx();
812 List<String> lines = new ArrayList<>();
813 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask).ifPresent(sc ->
814 lines.add(sc.getKeyText() + ' ' + tr("to apply first suggestion"))
815 );
816 lines.add(Shortcut.getKeyText(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK)) + ' '
817 +tr("to add without closing the dialog"));
818 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask | KeyEvent.SHIFT_DOWN_MASK).ifPresent(sc ->
819 lines.add(sc.getKeyText() + ' ' + tr("to add first suggestion without closing the dialog"))
820 );
821 final JLabel helpLabel = new JLabel("<html>" + Utils.join("<br>", lines) + "</html>");
822 helpLabel.setFont(helpLabel.getFont().deriveFont(Font.PLAIN));
823 contentPane.add(helpLabel, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(5, 5, 5, 5));
824 super.setContentPane(contentPane);
825 }
826
827 protected void selectNumberOfTags() {
828 String s = String.format("%d", PROPERTY_RECENT_TAGS_NUMBER.get());
829 while (true) {
830 s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"), s);
831 if (s == null || s.isEmpty()) {
832 return;
833 }
834 try {
835 int v = Integer.parseInt(s);
836 if (v >= 0 && v <= MAX_LRU_TAGS_NUMBER) {
837 PROPERTY_RECENT_TAGS_NUMBER.put(v);
838 return;
839 }
840 } catch (NumberFormatException ex) {
841 Logging.warn(ex);
842 }
843 JOptionPane.showMessageDialog(this, tr("Please enter integer number between 0 and {0}", MAX_LRU_TAGS_NUMBER));
844 }
845 }
846
847 protected void suggestRecentlyAddedTags() {
848 if (recentTagsPanel == null) {
849 recentTagsPanel = new JPanel(new GridBagLayout());
850 buildRecentTagsPanel();
851 mainPanel.add(recentTagsPanel, GBC.eol().fill(GBC.HORIZONTAL));
852 } else {
853 Dimension panelOldSize = recentTagsPanel.getPreferredSize();
854 recentTagsPanel.removeAll();
855 buildRecentTagsPanel();
856 Dimension panelNewSize = recentTagsPanel.getPreferredSize();
857 Dimension dialogOldSize = getMinimumSize();
858 Dimension dialogNewSize = new Dimension(dialogOldSize.width, dialogOldSize.height-panelOldSize.height+panelNewSize.height);
859 setMinimumSize(dialogNewSize);
860 setPreferredSize(dialogNewSize);
861 setSize(dialogNewSize);
862 revalidate();
863 repaint();
864 }
865 }
866
867 protected void buildRecentTagsPanel() {
868 final int tagsToShow = Math.min(PROPERTY_RECENT_TAGS_NUMBER.get(), MAX_LRU_TAGS_NUMBER);
869 if (!(tagsToShow > 0 && !recentTags.isEmpty()))
870 return;
871 recentTagsPanel.add(new JLabel(tr("Recently added tags")), GBC.eol());
872
873 int count = 0;
874 destroyActions();
875 for (int i = 0; i < tags.size() && count < tagsToShow; i++) {
876 final Tag t = tags.get(i);
877 boolean keyExists = containsDataKey(t.getKey());
878 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.HIDE)
879 continue;
880 count++;
881 // Create action for reusing the tag, with keyboard shortcut
882 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */
883 final Shortcut sc = count > 10 ? null : Shortcut.registerShortcut("properties:recent:" + count,
884 tr("Choose recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL);
885 final JosmAction action = new JosmAction(
886 tr("Choose recent tag {0}", count), null, tr("Use this tag again"), sc, false) {
887 @Override
888 public void actionPerformed(ActionEvent e) {
889 keys.setSelectedItem(t.getKey());
890 // fix #7951, #8298 - update list of values before setting value (?)
891 focus.focusGained(null);
892 values.setSelectedItem(t.getValue());
893 selectValuesCombobox();
894 }
895 };
896 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */
897 final Shortcut scShift = count > 10 ? null : Shortcut.registerShortcut("properties:recent:apply:" + count,
898 tr("Apply recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL_SHIFT);
899 final JosmAction actionShift = new JosmAction(
900 tr("Apply recent tag {0}", count), null, tr("Use this tag again"), scShift, false) {
901 @Override
902 public void actionPerformed(ActionEvent e) {
903 action.actionPerformed(null);
904 performTagAdding();
905 refreshRecentTags();
906 selectKeysComboBox();
907 }
908 };
909 recentTagsActions.add(action);
910 recentTagsActions.add(actionShift);
911 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.DISABLE) {
912 action.setEnabled(false);
913 }
914 // Find and display icon
915 ImageIcon icon = MapPaintStyles.getNodeIcon(t, false); // Filters deprecated icon
916 if (icon == null) {
917 // If no icon found in map style look at presets
918 Map<String, String> map = new HashMap<>();
919 map.put(t.getKey(), t.getValue());
920 for (TaggingPreset tp : TaggingPresets.getMatchingPresets(null, map, false)) {
921 icon = tp.getIcon();
922 if (icon != null) {
923 break;
924 }
925 }
926 // If still nothing display an empty icon
927 if (icon == null) {
928 icon = new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB));
929 }
930 }
931 GridBagConstraints gbc = new GridBagConstraints();
932 gbc.ipadx = 5;
933 recentTagsPanel.add(new JLabel(action.isEnabled() ? icon : GuiHelper.getDisabledIcon(icon)), gbc);
934 // Create tag label
935 final String color = action.isEnabled() ? "" : "; color:gray";
936 final JLabel tagLabel = new JLabel("<html>"
937 + "<style>td{" + color + "}</style>"
938 + "<table><tr>"
939 + "<td>" + count + ".</td>"
940 + "<td style='border:1px solid gray'>" + XmlWriter.encode(t.toString(), true) + '<' +
941 "/td></tr></table></html>");
942 tagLabel.setFont(tagLabel.getFont().deriveFont(Font.PLAIN));
943 if (action.isEnabled() && sc != null && scShift != null) {
944 // Register action
945 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), "choose"+count);
946 recentTagsPanel.getActionMap().put("choose"+count, action);
947 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), "apply"+count);
948 recentTagsPanel.getActionMap().put("apply"+count, actionShift);
949 }
950 if (action.isEnabled()) {
951 // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut)
952 tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
953 tagLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
954 tagLabel.addMouseListener(new MouseAdapter() {
955 @Override
956 public void mouseClicked(MouseEvent e) {
957 action.actionPerformed(null);
958 if (SwingUtilities.isRightMouseButton(e)) {
959 new TagPopupMenu(t).show(e.getComponent(), e.getX(), e.getY());
960 } else if (e.isShiftDown()) {
961 // add tags on Shift-Click
962 performTagAdding();
963 refreshRecentTags();
964 selectKeysComboBox();
965 } else if (e.getClickCount() > 1) {
966 // add tags and close window on double-click
967 buttonAction(0, null); // emulate OK click and close the dialog
968 }
969 }
970 });
971 } else {
972 // Disable tag label
973 tagLabel.setEnabled(false);
974 // Explain in the tooltip why
975 tagLabel.setToolTipText(tr("The key ''{0}'' is already used", t.getKey()));
976 }
977 // Finally add label to the resulting panel
978 JPanel tagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
979 tagPanel.add(tagLabel);
980 recentTagsPanel.add(tagPanel, GBC.eol().fill(GBC.HORIZONTAL));
981 }
982 // Clear label if no tags were added
983 if (count == 0) {
984 recentTagsPanel.removeAll();
985 }
986 }
987
988 class TagPopupMenu extends JPopupMenu {
989
990 TagPopupMenu(Tag t) {
991 add(new IgnoreTagAction(tr("Ignore key ''{0}''", t.getKey()), new Tag(t.getKey(), "")));
992 add(new IgnoreTagAction(tr("Ignore tag ''{0}''", t), t));
993 add(new EditIgnoreTagsAction());
994 }
995 }
996
997 class IgnoreTagAction extends AbstractAction {
998 final transient Tag tag;
999
1000 IgnoreTagAction(String name, Tag tag) {
1001 super(name);
1002 this.tag = tag;
1003 }
1004
1005 @Override
1006 public void actionPerformed(ActionEvent e) {
1007 try {
1008 if (tagsToIgnore != null) {
1009 recentTags.ignoreTag(tag, tagsToIgnore);
1010 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString());
1011 }
1012 } catch (SearchParseError parseError) {
1013 throw new IllegalStateException(parseError);
1014 }
1015 }
1016 }
1017
1018 class EditIgnoreTagsAction extends AbstractAction {
1019
1020 EditIgnoreTagsAction() {
1021 super(tr("Edit ignore list"));
1022 }
1023
1024 @Override
1025 public void actionPerformed(ActionEvent e) {
1026 final SearchAction.SearchSetting newTagsToIngore = SearchAction.showSearchDialog(tagsToIgnore);
1027 if (newTagsToIngore == null) {
1028 return;
1029 }
1030 try {
1031 tagsToIgnore = newTagsToIngore;
1032 recentTags.setTagsToIgnore(tagsToIgnore);
1033 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString());
1034 } catch (SearchParseError parseError) {
1035 warnAboutParseError(parseError);
1036 }
1037 }
1038 }
1039
1040 /**
1041 * Destroy the recentTagsActions.
1042 */
1043 public void destroyActions() {
1044 for (JosmAction action : recentTagsActions) {
1045 action.destroy();
1046 }
1047 recentTagsActions.clear();
1048 }
1049
1050 /**
1051 * Read tags from comboboxes and add it to all selected objects
1052 */
1053 public final void performTagAdding() {
1054 String key = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
1055 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
1056 if (key.isEmpty() || value.isEmpty())
1057 return;
1058 for (OsmPrimitive osm : sel) {
1059 String val = osm.get(key);
1060 if (val != null && !val.equals(value)) {
1061 if (!warnOverwriteKey(tr("You changed the value of ''{0}'' from ''{1}'' to ''{2}''.", key, val, value),
1062 "overwriteAddKey"))
1063 return;
1064 break;
1065 }
1066 }
1067 recentTags.add(new Tag(key, value));
1068 valueCount.put(key, new TreeMap<String, Integer>());
1069 AutoCompletionManager.rememberUserInput(key, value, false);
1070 commandCount++;
1071 MainApplication.undoRedo.add(new ChangePropertyCommand(sel, key, value));
1072 changedKey = key;
1073 clearEntries();
1074 }
1075
1076 protected void clearEntries() {
1077 keys.getEditor().setItem("");
1078 values.getEditor().setItem("");
1079 }
1080
1081 public void undoAllTagsAdding() {
1082 MainApplication.undoRedo.undo(commandCount);
1083 }
1084
1085 private void refreshRecentTags() {
1086 switch (PROPERTY_REFRESH_RECENT.get()) {
1087 case REFRESH:
1088 cacheRecentTags();
1089 suggestRecentlyAddedTags();
1090 break;
1091 case STATUS:
1092 suggestRecentlyAddedTags();
1093 break;
1094 default: // Do nothing
1095 }
1096 }
1097 }
1098}
Note: See TracBrowser for help on using the repository browser.