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

Last change on this file was 19115, checked in by taylor.smock, 10 days ago

Fix some checkstyle issues

  • Property svn:eol-style set to native
File size: 54.7 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.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.BorderLayout;
9import java.awt.Component;
10import java.awt.ComponentOrientation;
11import java.awt.Container;
12import java.awt.Cursor;
13import java.awt.Dimension;
14import java.awt.FlowLayout;
15import java.awt.Font;
16import java.awt.GridBagConstraints;
17import java.awt.GridBagLayout;
18import java.awt.event.ActionEvent;
19import java.awt.event.FocusEvent;
20import java.awt.event.FocusListener;
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.Iterator;
35import java.util.List;
36import java.util.Map;
37import java.util.Objects;
38import java.util.Optional;
39import java.util.TreeMap;
40import java.util.stream.Collectors;
41import java.util.stream.IntStream;
42
43import javax.swing.AbstractAction;
44import javax.swing.Action;
45import javax.swing.Box;
46import javax.swing.ButtonGroup;
47import javax.swing.ImageIcon;
48import javax.swing.JCheckBoxMenuItem;
49import javax.swing.JComponent;
50import javax.swing.JLabel;
51import javax.swing.JList;
52import javax.swing.JMenu;
53import javax.swing.JOptionPane;
54import javax.swing.JPanel;
55import javax.swing.JPopupMenu;
56import javax.swing.JRadioButtonMenuItem;
57import javax.swing.JTable;
58import javax.swing.KeyStroke;
59import javax.swing.ListCellRenderer;
60import javax.swing.SwingUtilities;
61import javax.swing.event.PopupMenuEvent;
62import javax.swing.event.PopupMenuListener;
63import javax.swing.table.DefaultTableModel;
64
65import org.openstreetmap.josm.actions.JosmAction;
66import org.openstreetmap.josm.actions.search.SearchAction;
67import org.openstreetmap.josm.command.ChangePropertyCommand;
68import org.openstreetmap.josm.command.Command;
69import org.openstreetmap.josm.command.SequenceCommand;
70import org.openstreetmap.josm.data.UndoRedoHandler;
71import org.openstreetmap.josm.data.osm.DataSet;
72import org.openstreetmap.josm.data.osm.OsmDataManager;
73import org.openstreetmap.josm.data.osm.OsmPrimitive;
74import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
75import org.openstreetmap.josm.data.osm.Tag;
76import org.openstreetmap.josm.data.osm.Tagged;
77import org.openstreetmap.josm.data.osm.search.SearchCompiler;
78import org.openstreetmap.josm.data.osm.search.SearchParseError;
79import org.openstreetmap.josm.data.osm.search.SearchSetting;
80import org.openstreetmap.josm.data.preferences.BooleanProperty;
81import org.openstreetmap.josm.data.preferences.EnumProperty;
82import org.openstreetmap.josm.data.preferences.IntegerProperty;
83import org.openstreetmap.josm.data.preferences.ListProperty;
84import org.openstreetmap.josm.data.preferences.StringProperty;
85import org.openstreetmap.josm.data.tagging.ac.AutoCompletionItem;
86import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
87import org.openstreetmap.josm.gui.ExtendedDialog;
88import org.openstreetmap.josm.gui.IExtendedDialog;
89import org.openstreetmap.josm.gui.MainApplication;
90import org.openstreetmap.josm.gui.tagging.ac.AutoCompComboBox;
91import org.openstreetmap.josm.gui.tagging.ac.AutoCompEvent;
92import org.openstreetmap.josm.gui.tagging.ac.AutoCompListener;
93import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
94import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem;
95import org.openstreetmap.josm.gui.util.GuiHelper;
96import org.openstreetmap.josm.gui.util.WindowGeometry;
97import org.openstreetmap.josm.gui.widgets.JosmListCellRenderer;
98import org.openstreetmap.josm.gui.widgets.OrientationAction;
99import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
100import org.openstreetmap.josm.io.XmlWriter;
101import org.openstreetmap.josm.tools.GBC;
102import org.openstreetmap.josm.tools.ImageProvider;
103import org.openstreetmap.josm.tools.Logging;
104import org.openstreetmap.josm.tools.OsmPrimitiveImageProvider;
105import org.openstreetmap.josm.tools.PlatformManager;
106import org.openstreetmap.josm.tools.Shortcut;
107import org.openstreetmap.josm.tools.Utils;
108
109/**
110 * Class that helps PropertiesDialog add and edit tag values.
111 * @since 5633
112 */
113public class TagEditHelper {
114
115 private final JTable tagTable;
116 private final DefaultTableModel tagData;
117 private final Map<String, Map<String, Integer>> valueCount;
118
119 // Selection that we are editing by using both dialogs
120 protected Collection<OsmPrimitive> sel;
121
122 private String changedKey;
123
124 static final Comparator<AutoCompletionItem> DEFAULT_AC_ITEM_COMPARATOR =
125 (o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
126
127 private static final String CANCEL_TR = marktr("Cancel");
128 private static final String CANCEL = "cancel";
129 private static final String HTML = "<html>";
130 private static final String DUMMY = "dummy";
131 /** Default number of recent tags */
132 public static final int DEFAULT_LRU_TAGS_NUMBER = 5;
133 /** Maximum number of recent tags */
134 public static final int MAX_LRU_TAGS_NUMBER = 30;
135 /** Autocomplete keys by default */
136 public static final BooleanProperty AUTOCOMPLETE_KEYS = new BooleanProperty("properties.autocomplete-keys", true);
137 /** Autocomplete values by default */
138 public static final BooleanProperty AUTOCOMPLETE_VALUES = new BooleanProperty("properties.autocomplete-values", true);
139 /** Use English language for tag by default */
140 public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE = new BooleanProperty("properties.fix-tag-combobox-locale", false);
141 /** Whether recent tags must be remembered */
142 public static final BooleanProperty PROPERTY_REMEMBER_TAGS = new BooleanProperty("properties.remember-recently-added-tags", true);
143 /** Number of recent tags */
144 public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER = new IntegerProperty("properties.recently-added-tags",
145 DEFAULT_LRU_TAGS_NUMBER);
146 /** The preference storage of recent tags */
147 public static final ListProperty PROPERTY_RECENT_TAGS = new ListProperty("properties.recent-tags",
148 Collections.emptyList());
149 /** The preference list of tags which should not be remembered, since r9940 */
150 public static final StringProperty PROPERTY_TAGS_TO_IGNORE = new StringProperty("properties.recent-tags.ignore",
151 new SearchSetting().writeToString());
152
153 /**
154 * What to do with recent tags where keys already exist
155 */
156 private enum RecentExisting {
157 ENABLE,
158 DISABLE,
159 HIDE
160 }
161
162 /**
163 * Preference setting for popup menu item "Recent tags with existing key"
164 */
165 public static final EnumProperty<RecentExisting> PROPERTY_RECENT_EXISTING = new EnumProperty<>(
166 "properties.recently-added-tags-existing-key", RecentExisting.class, RecentExisting.DISABLE);
167
168 /**
169 * What to do after applying tag
170 */
171 private enum RefreshRecent {
172 NO,
173 STATUS,
174 REFRESH
175 }
176
177 /**
178 * Preference setting for popup menu item "Refresh recent tags list after applying tag"
179 */
180 public static final EnumProperty<RefreshRecent> PROPERTY_REFRESH_RECENT = new EnumProperty<>(
181 "properties.refresh-recently-added-tags", RefreshRecent.class, RefreshRecent.STATUS);
182
183 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER);
184 SearchSetting tagsToIgnore;
185
186 /**
187 * Copy of recently added tags in sorted from newest to oldest order.
188 * <p>
189 * We store the maximum number of recent tags to allow dynamic change of number of tags shown in the preferences.
190 * Used to cache initial status.
191 */
192 private List<Tag> tags;
193
194 static {
195 // init user input based on recent tags
196 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER);
197 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS);
198 recentTags.toList().forEach(tag -> AutoCompletionManager.rememberUserInput(tag.getKey(), tag.getValue(), false));
199 }
200
201 /**
202 * A custom list cell renderer that adds the value count to some items.
203 */
204 static class TEHListCellRenderer extends JosmListCellRenderer<AutoCompletionItem> {
205 protected Map<String, Integer> map;
206
207 TEHListCellRenderer(Component component, ListCellRenderer<? super AutoCompletionItem> renderer, Map<String, Integer> map) {
208 super(component, renderer);
209 this.map = map;
210 }
211
212 @Override
213 public Component getListCellRendererComponent(JList<? extends AutoCompletionItem> list, AutoCompletionItem value,
214 int index, boolean isSelected, boolean cellHasFocus) {
215 Integer count = null;
216 // if there is a value count add it to the text
217 if (map != null) {
218 String text = value == null ? "" : value.toString();
219 count = map.get(text);
220 if (count != null) {
221 value = new AutoCompletionItem(tr("{0} ({1})", text, count));
222 }
223 }
224 Component l = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
225 l.setComponentOrientation(component.getComponentOrientation());
226 if (count != null) {
227 l.setFont(l.getFont().deriveFont(Font.ITALIC + Font.BOLD));
228 }
229 return l;
230 }
231 }
232
233 /**
234 * Constructs a new {@code TagEditHelper}.
235 * @param tagTable tag table
236 * @param propertyData table model
237 * @param valueCount tag value count
238 */
239 public TagEditHelper(JTable tagTable, DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
240 this.tagTable = tagTable;
241 this.tagData = propertyData;
242 this.valueCount = valueCount;
243 }
244
245 /**
246 * Finds the key from given row of tag editor.
247 * @param viewRow index of row
248 * @return key of tag
249 */
250 public final String getDataKey(int viewRow) {
251 return tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 0).toString();
252 }
253
254 /**
255 * Determines if the given tag key is already used (by all selected primitives, not just some of them)
256 * @param key the key to check
257 * @return {@code true} if the key is used by all selected primitives (key not unset for at least one primitive)
258 */
259 @SuppressWarnings("unchecked")
260 boolean containsDataKey(String key) {
261 return IntStream.range(0, tagData.getRowCount())
262 .anyMatch(i -> key.equals(tagData.getValueAt(i, 0)) /* sic! do not use getDataKey*/
263 && !((Map<String, Integer>) tagData.getValueAt(i, 1)).containsKey("") /* sic! do not use getDataValues*/);
264 }
265
266 /**
267 * Finds the values from given row of tag editor.
268 * @param viewRow index of row
269 * @return map of values and number of occurrences
270 */
271 @SuppressWarnings("unchecked")
272 public final Map<String, Integer> getDataValues(int viewRow) {
273 return (Map<String, Integer>) tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 1);
274 }
275
276 /**
277 * Open the add selection dialog and add a new key/value to the table (and
278 * to the dataset, of course).
279 */
280 public void addTag() {
281 changedKey = null;
282 DataSet activeDataSet = OsmDataManager.getInstance().getActiveDataSet();
283 if (activeDataSet == null)
284 return;
285 final Collection<OsmPrimitive> selection = updateSelection();
286
287 if (Utils.isEmpty(selection))
288 return;
289
290 final AddTagsDialog addDialog = getAddTagsDialog();
291
292 addDialog.showDialog();
293
294 addDialog.destroyActions();
295 activeDataSet.update(() -> {
296 // Remote control can cause the selection to change, see #23191.
297 if (addDialog.getValue() == 1 && (selection.equals(updateSelection()) || warnSelectionChanged())) {
298 addDialog.performTagAdding(selection);
299 } else {
300 addDialog.undoAllTagsAdding();
301 }
302 });
303 }
304
305 /**
306 * Returns a new {@code AddTagsDialog}.
307 * @return a new {@code AddTagsDialog}
308 */
309 protected AddTagsDialog getAddTagsDialog() {
310 return new AddTagsDialog();
311 }
312
313 /**
314 * Edit the value in the tags table row.
315 * @param row The row of the table from which the value is edited.
316 * @param focusOnKey Determines if the initial focus should be set on key instead of value
317 * @since 5653
318 */
319 public void editTag(final int row, boolean focusOnKey) {
320 changedKey = null;
321 updateSelection();
322 if (Utils.isEmpty(sel))
323 return;
324
325 final IEditTagDialog editDialog = getEditTagDialog(row, focusOnKey, getDataKey(row));
326 editDialog.showDialog();
327 if (editDialog.getValue() != 1)
328 return;
329 editDialog.performTagEdit();
330 }
331
332 /**
333 * Extracted interface of {@link EditTagDialog}.
334 */
335 protected interface IEditTagDialog extends IExtendedDialog {
336 /**
337 * Edit tags of multiple selected objects according to selected ComboBox values
338 * If value == "", tag will be deleted
339 * Confirmations may be needed.
340 */
341 void performTagEdit();
342 }
343
344 protected IEditTagDialog getEditTagDialog(int row, boolean focusOnKey, String key) {
345 return new EditTagDialog(key, getDataValues(row), focusOnKey);
346 }
347
348 /**
349 * If during last editProperty call user changed the key name, this key will be returned
350 * Elsewhere, returns null.
351 * @return The modified key, or {@code null}
352 */
353 public String getChangedKey() {
354 return changedKey;
355 }
356
357 /**
358 * Reset last changed key.
359 */
360 public void resetChangedKey() {
361 changedKey = null;
362 }
363
364 /**
365 * Update the current selection for this editor
366 */
367 private Collection<OsmPrimitive> updateSelection() {
368 final DataSet activeDataSet = OsmDataManager.getInstance().getActiveDataSet();
369 activeDataSet.getReadLock().lock();
370 try {
371 Collection<OsmPrimitive> selection = new ArrayList<>(OsmDataManager.getInstance().getInProgressSelection());
372 this.sel = selection;
373 return selection;
374 } finally {
375 activeDataSet.getReadLock().unlock();
376 }
377 }
378
379 /**
380 * For a given key k, return a list of keys which are used as keys for
381 * auto-completing values to increase the search space.
382 * @param key the key k
383 * @return a list of keys
384 */
385 private static List<String> getAutocompletionKeys(String key) {
386 if ("name".equals(key) || "addr:street".equals(key))
387 return Arrays.asList("addr:street", "name");
388 else
389 return Collections.singletonList(key);
390 }
391
392 /**
393 * Load recently used tags from preferences if needed.
394 */
395 public void loadTagsIfNeeded() {
396 loadTagsToIgnore();
397 if (Boolean.TRUE.equals(PROPERTY_REMEMBER_TAGS.get()) && recentTags.isEmpty()) {
398 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS);
399 }
400 }
401
402 void loadTagsToIgnore() {
403 final SearchSetting searchSetting = Utils.firstNonNull(
404 SearchSetting.readFromString(PROPERTY_TAGS_TO_IGNORE.get()), new SearchSetting());
405 if (!Objects.equals(tagsToIgnore, searchSetting)) {
406 try {
407 tagsToIgnore = searchSetting;
408 recentTags.setTagsToIgnore(tagsToIgnore);
409 } catch (SearchParseError parseError) {
410 warnAboutParseError(parseError);
411 tagsToIgnore = new SearchSetting();
412 recentTags.setTagsToIgnore(SearchCompiler.Never.INSTANCE);
413 }
414 }
415 }
416
417 private static void warnAboutParseError(SearchParseError parseError) {
418 Logging.warn(parseError);
419 JOptionPane.showMessageDialog(
420 MainApplication.getMainFrame(),
421 parseError.getMessage(),
422 tr("Error"),
423 JOptionPane.ERROR_MESSAGE
424 );
425 }
426
427 /**
428 * Store recently used tags in preferences if needed.
429 */
430 public void saveTagsIfNeeded() {
431 if (Boolean.TRUE.equals(PROPERTY_REMEMBER_TAGS.get()) && !recentTags.isEmpty()) {
432 recentTags.saveToPreference(PROPERTY_RECENT_TAGS);
433 }
434 }
435
436 /**
437 * Forget recently selected primitives to allow GC.
438 * @since 14509
439 */
440 public void resetSelection() {
441 sel = null;
442 }
443
444 /**
445 * Update cache of recent tags used for displaying tags.
446 */
447 private void cacheRecentTags() {
448 tags = recentTags.toList();
449 Collections.reverse(tags);
450 }
451
452 /**
453 * Returns the edited item with whitespaces removed
454 * @param cb the combobox
455 * @return the edited item with whitespaces removed
456 * @since 18173
457 */
458 public static String getEditItem(AutoCompComboBox<AutoCompletionItem> cb) {
459 return Utils.removeWhiteSpaces(cb.getEditorItemAsString());
460 }
461
462 /**
463 * Returns the selected item or the edited item as string
464 * @param cb the combobox
465 * @return the selected item or the edited item as string
466 * @since 18173
467 */
468 public static String getSelectedOrEditItem(AutoCompComboBox<AutoCompletionItem> cb) {
469 final Object selectedItem = cb.getSelectedItem();
470 if (selectedItem != null)
471 return selectedItem.toString();
472 return getEditItem(cb);
473 }
474
475 /**
476 * Warn user about a selection change
477 * @return {@code true} if the user wants to apply the tag change to the old selection
478 */
479 private static boolean warnSelectionChanged() {
480 return ConditionalOptionPaneUtil.showConfirmationDialog("properties.selection-changed",
481 MainApplication.getMainFrame(),
482 tr("Data selection has changed since the dialog was opened"),
483 tr("Apply tag change to old selection?"),
484 JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, JOptionPane.YES_OPTION);
485 }
486
487 /**
488 * Warns user about a key being overwritten.
489 * @param action The action done by the user. Must state what key is changed
490 * @param togglePref The preference to save the checkbox state to
491 * @return {@code true} if the user accepts to overwrite key, {@code false} otherwise
492 */
493 private static boolean warnOverwriteKey(String action, String togglePref) {
494 return new ExtendedDialog(
495 MainApplication.getMainFrame(),
496 tr("Overwrite tag"),
497 tr("Overwrite"), tr(CANCEL_TR))
498 .setButtonIcons("ok", CANCEL)
499 .setContent(action)
500 .setCancelButton(2)
501 .toggleEnable(togglePref)
502 .showDialog().getValue() == 1;
503 }
504
505 protected class EditTagDialog extends AbstractTagsDialog implements IEditTagDialog {
506 private final String key;
507 private final transient Map<String, Integer> m;
508 private final transient Comparator<AutoCompletionItem> usedValuesAwareComparator;
509 private final transient AutoCompletionManager autocomplete;
510
511 protected EditTagDialog(String key, Map<String, Integer> map, boolean initialFocusOnKey) {
512 super(MainApplication.getMainFrame(), trn("Change value?", "Change values?", map.size()), tr("OK"), tr(CANCEL_TR));
513 setButtonIcons("ok", CANCEL);
514 setCancelButton(2);
515 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);
516 this.key = key;
517 this.m = map;
518 this.initialFocusOnKey = initialFocusOnKey;
519
520 usedValuesAwareComparator = (o1, o2) -> {
521 boolean c1 = m.containsKey(o1.getValue());
522 boolean c2 = m.containsKey(o2.getValue());
523 if (c1 == c2)
524 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
525 else if (c1)
526 return -1;
527 else
528 return +1;
529 };
530
531 JPanel mainPanel = new JPanel(new BorderLayout());
532
533 String msg = HTML+trn("This will change {0} object.",
534 "This will change up to {0} objects.", sel.size(), sel.size())
535 +"<br><br>("+tr("An empty value deletes the tag.", key)+")</html>";
536
537 mainPanel.add(new JLabel(msg), BorderLayout.NORTH);
538
539 JPanel p = new JPanel(new GridBagLayout()) {
540 /**
541 * This hack allows the comboboxes to have their own orientation.
542 * <p>
543 * The problem is that
544 * {@link org.openstreetmap.josm.gui.ExtendedDialog#showDialog ExtendedDialog} calls
545 * {@code applyComponentOrientation} very late in the dialog construction process
546 * thus overwriting the orientation the components have chosen for themselves.
547 * <p>
548 * This stops the propagation of {@code applyComponentOrientation}, thus all
549 * components may (and have to) set their own orientation.
550 */
551 @Override
552 public void applyComponentOrientation(ComponentOrientation o) {
553 setComponentOrientation(o);
554 }
555 };
556 mainPanel.add(p, BorderLayout.CENTER);
557
558 autocomplete = AutoCompletionManager.of(OsmDataManager.getInstance().getActiveDataSet());
559 List<AutoCompletionItem> keyList = autocomplete.getTagKeys(DEFAULT_AC_ITEM_COMPARATOR);
560
561 keys = new AutoCompComboBox<>();
562 keys.getModel().setComparator(Comparator.naturalOrder()); // according to Comparable
563 keys.setEditable(true);
564 keys.setPrototypeDisplayValue(new AutoCompletionItem(DUMMY));
565 keys.getModel().addAllElements(keyList);
566 keys.setSelectedItemText(key);
567
568 p.add(Box.createVerticalStrut(5), GBC.eol());
569 p.add(new JLabel(tr("Key")), GBC.std());
570 p.add(Box.createHorizontalStrut(10), GBC.std());
571 p.add(keys, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
572
573 List<AutoCompletionItem> valueList = autocomplete.getTagValues(getAutocompletionKeys(key), usedValuesAwareComparator);
574
575 final String selection = m.size() != 1 ? KeyedItem.DIFFERENT_I18N : m.entrySet().iterator().next().getKey();
576
577 values = new AutoCompComboBox<>();
578 values.getModel().setComparator(Comparator.naturalOrder());
579 values.setRenderer(new TEHListCellRenderer(values, values.getRenderer(), valueCount.get(key)));
580 values.setEditable(true);
581 values.setPrototypeDisplayValue(new AutoCompletionItem(DUMMY));
582 values.getModel().addAllElements(valueList);
583 values.setSelectedItemText(selection);
584
585 p.add(Box.createVerticalStrut(5), GBC.eol());
586 p.add(new JLabel(tr("Value")), GBC.std());
587 p.add(Box.createHorizontalStrut(10), GBC.std());
588 p.add(values, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
589 p.add(Box.createVerticalStrut(2), GBC.eol());
590
591 p.applyComponentOrientation(OrientationAction.getDefaultComponentOrientation());
592 keys.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
593 values.applyComponentOrientation(OrientationAction.getNamelikeOrientation(keys.getText()));
594
595 setContent(mainPanel, false);
596
597 addEventListeners();
598 }
599
600 @Override
601 public void autoCompBefore(AutoCompEvent e) {
602 updateValueModel(autocomplete, usedValuesAwareComparator);
603 }
604
605 @Override
606 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
607 updateValueModel(autocomplete, usedValuesAwareComparator);
608 }
609
610 @Override
611 public void performTagEdit() {
612 String value = getEditItem(values);
613 value = Normalizer.normalize(value, Normalizer.Form.NFC);
614 if (value.isEmpty()) {
615 value = null; // delete the key
616 }
617 String newkey = getEditItem(keys);
618 newkey = Normalizer.normalize(newkey, Normalizer.Form.NFC);
619 if (newkey.isEmpty()) {
620 newkey = key;
621 value = null; // delete the key instead
622 }
623 if (key.equals(newkey) && KeyedItem.DIFFERENT_I18N.equals(value))
624 return;
625 if (value != null && key.equals(getEditItem(keys)) && m.size() == 1 && m.containsKey(getEditItem(values)))
626 return; // see #22814: avoid to create a command that wouldn't change anything
627 if (key.equals(newkey) || value == null) {
628 UndoRedoHandler.getInstance().add(new ChangePropertyCommand(sel, newkey, value));
629 if (value != null) {
630 AutoCompletionManager.rememberUserInput(newkey, value, true);
631 recentTags.add(new Tag(key, value));
632 }
633 } else {
634 for (OsmPrimitive osm: sel) {
635 if (osm.get(newkey) != null) {
636 if (!warnOverwriteKey(tr("You changed the key from ''{0}'' to ''{1}''.", key, newkey)
637 + "\n" + tr("The new key is already used, overwrite values?"),
638 "overwriteEditKey"))
639 return;
640 break;
641 }
642 }
643 Collection<Command> commands = new ArrayList<>();
644 commands.add(new ChangePropertyCommand(sel, key, null));
645 if (value.equals(KeyedItem.DIFFERENT_I18N)) {
646 String newKey = newkey;
647 sel.stream()
648 .filter(osm -> osm.hasKey(key))
649 .collect(Collectors.groupingBy(osm -> osm.get(key)))
650 .forEach((newValue, osmPrimitives) -> commands.add(new ChangePropertyCommand(osmPrimitives, newKey, newValue)));
651 } else {
652 commands.add(new ChangePropertyCommand(sel, newkey, value));
653 AutoCompletionManager.rememberUserInput(newkey, value, false);
654 }
655 UndoRedoHandler.getInstance().add(new SequenceCommand(
656 trn("Change properties of up to {0} object",
657 "Change properties of up to {0} objects", sel.size(), sel.size()),
658 commands));
659 }
660
661 changedKey = newkey;
662 }
663 }
664
665 protected abstract class AbstractTagsDialog extends ExtendedDialog implements AutoCompListener, FocusListener, PopupMenuListener {
666 protected AutoCompComboBox<AutoCompletionItem> keys;
667 protected AutoCompComboBox<AutoCompletionItem> values;
668 protected boolean initialFocusOnKey = true;
669 /**
670 * The 'values' model is currently holding values for this key. Used for lazy-loading of values.
671 */
672 protected String currentValuesModelKey = "";
673
674 AbstractTagsDialog(Component parent, String title, String... buttonTexts) {
675 super(parent, title, buttonTexts);
676 addMouseListener(new PopupMenuLauncher(popupMenu));
677 }
678
679 @Override
680 public void setupDialog() {
681 super.setupDialog();
682 buttons.get(0).setEnabled(!OsmDataManager.getInstance().getActiveDataSet().isLocked());
683 final Dimension size = getSize();
684 // Set resizable only in width
685 setMinimumSize(size);
686 setPreferredSize(size);
687 // setMaximumSize does not work, and never worked, but still it seems not to bother Oracle to fix this 10-year-old bug
688 // https://bugs.openjdk.java.net/browse/JDK-6200438
689 // https://bugs.openjdk.java.net/browse/JDK-6464548
690
691 setRememberWindowGeometry(getClass().getName() + ".geometry",
692 WindowGeometry.centerInWindow(MainApplication.getMainFrame(), size));
693 keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
694 }
695
696 @Override
697 public void setVisible(boolean visible) {
698 // Do not want dialog to be resizable in height, as its size may increase each time because of the recently added tags
699 // So need to modify the stored geometry (size part only) in order to use the automatic positioning mechanism
700 if (visible) {
701 WindowGeometry geometry = initWindowGeometry();
702 Dimension storedSize = geometry.getSize();
703 Dimension size = getSize();
704 if (!storedSize.equals(size)) {
705 if (storedSize.width < size.width) {
706 storedSize.width = size.width;
707 }
708 if (storedSize.height != size.height) {
709 storedSize.height = size.height;
710 }
711 rememberWindowGeometry(geometry);
712 }
713 updateOkButtonIcon();
714 }
715 super.setVisible(visible);
716 }
717
718 /**
719 * Updates the values model if the key has changed
720 *
721 * @param autocomplete the autocompletion manager
722 * @param comparator sorting order for the items in the combo dropdown
723 */
724 protected void updateValueModel(AutoCompletionManager autocomplete, Comparator<AutoCompletionItem> comparator) {
725 String key = keys.getText();
726 if (!key.equals(currentValuesModelKey)) {
727 Logging.debug("updateValueModel: lazy loading values for key ''{0}''", key);
728 // key has changed, reload model
729 String savedText = values.getText();
730 values.getModel().removeAllElements();
731 values.getModel().addAllElements(autocomplete.getTagValues(getAutocompletionKeys(key), comparator));
732 values.applyComponentOrientation(OrientationAction.getNamelikeOrientation(key));
733 values.setSelectedItemText(savedText);
734 values.getEditor().selectAll();
735 currentValuesModelKey = key;
736 }
737 }
738
739 protected void addEventListeners() {
740 // OK on Enter in values
741 values.getEditor().addActionListener(e -> buttonAction(0, null));
742 // update values orientation according to key
743 keys.getEditorComponent().addFocusListener(this);
744 // update the "values" data model before an autocomplete or list dropdown
745 values.getEditorComponent().addAutoCompListener(this);
746 values.addPopupMenuListener(this);
747 // set the initial focus to either combobox
748 addWindowListener(new WindowAdapter() {
749 @Override
750 public void windowOpened(WindowEvent e) {
751 if (initialFocusOnKey) {
752 keys.requestFocus();
753 } else {
754 values.requestFocus();
755 }
756 }
757 });
758 }
759
760 @Override
761 public void autoCompPerformed(AutoCompEvent e) {
762 }
763
764 @Override
765 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
766 }
767
768 @Override
769 public void popupMenuCanceled(PopupMenuEvent e) {
770 }
771
772 @Override
773 public void focusGained(FocusEvent e) {
774 }
775
776 @Override
777 public void focusLost(FocusEvent e) {
778 // update the values combobox orientation if the key changed
779 values.applyComponentOrientation(OrientationAction.getNamelikeOrientation(keys.getText()));
780 }
781
782 protected void updateOkButtonIcon() {
783 if (buttons.isEmpty()) {
784 return;
785 }
786 buttons.get(0).setIcon(findIcon(getSelectedOrEditItem(keys), getSelectedOrEditItem(values))
787 .orElse(ImageProvider.get("ok", ImageProvider.ImageSizes.LARGEICON)));
788 }
789
790 protected Optional<ImageIcon> findIcon(String key, String value) {
791 final Iterator<OsmPrimitive> osmPrimitiveIterator = sel.iterator();
792 final OsmPrimitiveType type = osmPrimitiveIterator.hasNext() ? osmPrimitiveIterator.next().getType() : OsmPrimitiveType.NODE;
793 return OsmPrimitiveImageProvider.getResource(key, value, type)
794 .map(resource -> resource.getPaddedIcon(ImageProvider.ImageSizes.LARGEICON.getImageDimension()));
795 }
796
797 protected JPopupMenu popupMenu = new JPopupMenu() {
798 private final JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem(
799 new AbstractAction(tr("Use English language for tag by default")) {
800 @Override
801 public void actionPerformed(ActionEvent e) {
802 boolean use = ((JCheckBoxMenuItem) e.getSource()).getState();
803 PROPERTY_FIX_TAG_LOCALE.put(use);
804 keys.setFixedLocale(use);
805 }
806 });
807 {
808 add(fixTagLanguageCb);
809 fixTagLanguageCb.setState(PROPERTY_FIX_TAG_LOCALE.get());
810 }
811 };
812 }
813
814 protected class AddTagsDialog extends AbstractTagsDialog {
815 private final List<JosmAction> recentTagsActions = new ArrayList<>();
816 private final JPanel mainPanel;
817 private JPanel recentTagsPanel;
818
819 // Counter of added commands for possible undo
820 private int commandCount;
821 private final transient AutoCompletionManager autocomplete;
822
823 protected AddTagsDialog() {
824 super(MainApplication.getMainFrame(), tr("Add tag"), tr("OK"), tr(CANCEL_TR));
825 setButtonIcons("ok", CANCEL);
826 setCancelButton(2);
827 configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */);
828
829 mainPanel = new JPanel(new GridBagLayout()) {
830 /**
831 * This hack allows the comboboxes to have their own orientation.
832 * <p>
833 * The problem is that
834 * {@link org.openstreetmap.josm.gui.ExtendedDialog#showDialog ExtendedDialog} calls
835 * {@code applyComponentOrientation} very late in the dialog construction process
836 * thus overwriting the orientation the components have chosen for themselves.
837 * <p>
838 * This stops the propagation of {@code applyComponentOrientation}, thus all
839 * components may (and have to) set their own orientation.
840 */
841 @Override
842 public void applyComponentOrientation(ComponentOrientation o) {
843 setComponentOrientation(o);
844 }
845 };
846 mainPanel.add(new JLabel(HTML+trn("This will change up to {0} object.",
847 "This will change up to {0} objects.", sel.size(), sel.size())
848 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
849
850 keys = new AutoCompComboBox<>();
851 keys.setPrototypeDisplayValue(new AutoCompletionItem(DUMMY));
852 keys.setEditable(true);
853 keys.getModel().setComparator(Comparator.naturalOrder()); // according to Comparable
854 keys.setAutocompleteEnabled(AUTOCOMPLETE_KEYS.get());
855
856 mainPanel.add(keys, GBC.eop().fill(GridBagConstraints.HORIZONTAL));
857 mainPanel.add(new JLabel(tr("Choose a value")), GBC.eol());
858
859 values = new AutoCompComboBox<>();
860 values.setPrototypeDisplayValue(new AutoCompletionItem(DUMMY));
861 values.setEditable(true);
862 values.getModel().setComparator(Comparator.naturalOrder());
863 values.setAutocompleteEnabled(AUTOCOMPLETE_VALUES.get());
864
865 mainPanel.add(values, GBC.eop().fill(GridBagConstraints.HORIZONTAL));
866
867 cacheRecentTags();
868 autocomplete = AutoCompletionManager.of(OsmDataManager.getInstance().getActiveDataSet());
869 List<AutoCompletionItem> keyList = autocomplete.getTagKeys(DEFAULT_AC_ITEM_COMPARATOR);
870
871 // remove the object's tag keys from the list
872 keyList.removeIf(item -> containsDataKey(item.getValue()));
873
874 keys.getModel().addAllElements(keyList);
875
876 updateValueModel(autocomplete, DEFAULT_AC_ITEM_COMPARATOR);
877
878 // pre-fill first recent tag for which the key is not already present
879 tags.stream()
880 .filter(tag -> !containsDataKey(tag.getKey()))
881 .findFirst()
882 .ifPresent(tag -> {
883 keys.setSelectedItemText(tag.getKey());
884 values.setSelectedItemText(tag.getValue());
885 });
886
887
888 keys.addActionListener(ignore -> updateOkButtonIcon());
889 values.addActionListener(ignore -> updateOkButtonIcon());
890
891 // Add tag on Shift-Enter
892 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
893 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK), "addAndContinue");
894 mainPanel.getActionMap().put("addAndContinue", new AbstractAction() {
895 @Override
896 public void actionPerformed(ActionEvent e) {
897 performTagAdding();
898 refreshRecentTags();
899 keys.requestFocus();
900 }
901 });
902
903 suggestRecentlyAddedTags();
904
905 mainPanel.add(Box.createVerticalGlue(), GBC.eop().fill());
906 mainPanel.applyComponentOrientation(OrientationAction.getDefaultComponentOrientation());
907
908 setContent(mainPanel, false);
909
910 addEventListeners();
911
912 popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) {
913 @Override
914 public void actionPerformed(ActionEvent e) {
915 selectNumberOfTags();
916 suggestRecentlyAddedTags();
917 }
918 });
919
920 popupMenu.add(buildMenuRecentExisting());
921 popupMenu.add(buildMenuRefreshRecent());
922
923 JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem(
924 new AbstractAction(tr("Remember last used tags after a restart")) {
925 @Override
926 public void actionPerformed(ActionEvent e) {
927 boolean state = ((JCheckBoxMenuItem) e.getSource()).getState();
928 PROPERTY_REMEMBER_TAGS.put(state);
929 if (state)
930 saveTagsIfNeeded();
931 }
932 });
933 rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get());
934 popupMenu.add(rememberLastTags);
935 }
936
937 @Override
938 public void autoCompBefore(AutoCompEvent e) {
939 updateValueModel(autocomplete, DEFAULT_AC_ITEM_COMPARATOR);
940 }
941
942 @Override
943 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
944 updateValueModel(autocomplete, DEFAULT_AC_ITEM_COMPARATOR);
945 }
946
947 private JMenu buildMenuRecentExisting() {
948 JMenu menu = new JMenu(tr("Recent tags with existing key"));
949 TreeMap<RecentExisting, String> radios = new TreeMap<>();
950 radios.put(RecentExisting.ENABLE, tr("Enable"));
951 radios.put(RecentExisting.DISABLE, tr("Disable"));
952 radios.put(RecentExisting.HIDE, tr("Hide"));
953 ButtonGroup buttonGroup = new ButtonGroup();
954 for (final Map.Entry<RecentExisting, String> entry : radios.entrySet()) {
955 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) {
956 @Override
957 public void actionPerformed(ActionEvent e) {
958 PROPERTY_RECENT_EXISTING.put(entry.getKey());
959 suggestRecentlyAddedTags();
960 }
961 });
962 buttonGroup.add(radio);
963 radio.setSelected(PROPERTY_RECENT_EXISTING.get() == entry.getKey());
964 menu.add(radio);
965 }
966 return menu;
967 }
968
969 private JMenu buildMenuRefreshRecent() {
970 JMenu menu = new JMenu(tr("Refresh recent tags list after applying tag"));
971 TreeMap<RefreshRecent, String> radios = new TreeMap<>();
972 radios.put(RefreshRecent.NO, tr("No refresh"));
973 radios.put(RefreshRecent.STATUS, tr("Refresh tag status only (enabled / disabled)"));
974 radios.put(RefreshRecent.REFRESH, tr("Refresh tag status and list of recently added tags"));
975 ButtonGroup buttonGroup = new ButtonGroup();
976 for (final Map.Entry<RefreshRecent, String> entry : radios.entrySet()) {
977 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) {
978 @Override
979 public void actionPerformed(ActionEvent e) {
980 PROPERTY_REFRESH_RECENT.put(entry.getKey());
981 }
982 });
983 buttonGroup.add(radio);
984 radio.setSelected(PROPERTY_REFRESH_RECENT.get() == entry.getKey());
985 menu.add(radio);
986 }
987 return menu;
988 }
989
990 @Override
991 public void setContentPane(Container contentPane) {
992 final int commandDownMask = PlatformManager.getPlatform().getMenuShortcutKeyMaskEx();
993 List<String> lines = new ArrayList<>();
994 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask).ifPresent(sc ->
995 lines.add(sc.getKeyText() + ' ' + tr("to apply first suggestion"))
996 );
997 lines.add(Shortcut.getKeyText(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK)) + ' '
998 +tr("to add without closing the dialog"));
999 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask | InputEvent.SHIFT_DOWN_MASK).ifPresent(sc ->
1000 lines.add(sc.getKeyText() + ' ' + tr("to add first suggestion without closing the dialog"))
1001 );
1002 final JLabel helpLabel = new JLabel(HTML + String.join("<br>", lines) + "</html>");
1003 helpLabel.setFont(helpLabel.getFont().deriveFont(Font.PLAIN));
1004 contentPane.add(helpLabel, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(5, 5, 5, 5));
1005 super.setContentPane(contentPane);
1006 }
1007
1008 protected void selectNumberOfTags() {
1009 String s = String.format("%d", PROPERTY_RECENT_TAGS_NUMBER.get());
1010 while (true) {
1011 s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"), s);
1012 if (Utils.isEmpty(s)) {
1013 return;
1014 }
1015 try {
1016 int v = Integer.parseInt(s);
1017 if (v >= 0 && v <= MAX_LRU_TAGS_NUMBER) {
1018 PROPERTY_RECENT_TAGS_NUMBER.put(v);
1019 return;
1020 }
1021 } catch (NumberFormatException ex) {
1022 Logging.warn(ex);
1023 }
1024 JOptionPane.showMessageDialog(this, tr("Please enter integer number between 0 and {0}", MAX_LRU_TAGS_NUMBER));
1025 }
1026 }
1027
1028 protected void suggestRecentlyAddedTags() {
1029 if (recentTagsPanel == null) {
1030 recentTagsPanel = new JPanel(new GridBagLayout());
1031 buildRecentTagsPanel();
1032 mainPanel.add(recentTagsPanel, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
1033 } else {
1034 Dimension panelOldSize = recentTagsPanel.getPreferredSize();
1035 recentTagsPanel.removeAll();
1036 buildRecentTagsPanel();
1037 Dimension panelNewSize = recentTagsPanel.getPreferredSize();
1038 Dimension dialogOldSize = getMinimumSize();
1039 Dimension dialogNewSize = new Dimension(dialogOldSize.width, dialogOldSize.height-panelOldSize.height+panelNewSize.height);
1040 setMinimumSize(dialogNewSize);
1041 setPreferredSize(dialogNewSize);
1042 setSize(dialogNewSize);
1043 revalidate();
1044 repaint();
1045 }
1046 }
1047
1048 protected void buildRecentTagsPanel() {
1049 final int tagsToShow = Math.min(PROPERTY_RECENT_TAGS_NUMBER.get(), MAX_LRU_TAGS_NUMBER);
1050 if (!(tagsToShow > 0 && !recentTags.isEmpty()))
1051 return;
1052 recentTagsPanel.add(new JLabel(tr("Recently added tags")), GBC.eol());
1053
1054 int count = 0;
1055 destroyActions();
1056 for (int i = 0; i < tags.size() && count < tagsToShow; i++) {
1057 final Tag t = tags.get(i);
1058 boolean keyExists = containsDataKey(t.getKey());
1059 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.HIDE)
1060 continue;
1061 count++;
1062 // Create action for reusing the tag, with keyboard shortcut
1063 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */
1064 final Shortcut sc = count > 10 ? null : Shortcut.registerShortcut("properties:recent:" + count,
1065 tr("Choose recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL);
1066 final JosmAction action = new JosmAction(
1067 tr("Choose recent tag {0}", count), null, tr("Use this tag again"), sc, false) {
1068 @Override
1069 public void actionPerformed(ActionEvent e) {
1070 keys.setSelectedItemText(t.getKey());
1071 // fix #7951, #8298 - update list of values before setting value (?)
1072 updateValueModel(autocomplete, DEFAULT_AC_ITEM_COMPARATOR);
1073 values.setSelectedItemText(t.getValue());
1074 values.requestFocus();
1075 }
1076 };
1077 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */
1078 final Shortcut scShift = count > 10 ? null : Shortcut.registerShortcut("properties:recent:apply:" + count,
1079 tr("Apply recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL_SHIFT);
1080 final JosmAction actionShift = new JosmAction(
1081 tr("Apply recent tag {0}", count), null, tr("Use this tag again"), scShift, false) {
1082 @Override
1083 public void actionPerformed(ActionEvent e) {
1084 action.actionPerformed(null);
1085 performTagAdding();
1086 refreshRecentTags();
1087 keys.requestFocus();
1088 }
1089 };
1090 recentTagsActions.add(action);
1091 recentTagsActions.add(actionShift);
1092 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.DISABLE) {
1093 action.setEnabled(false);
1094 }
1095 ImageIcon icon = findIcon(t.getKey(), t.getValue())
1096 // If still nothing display an empty icon
1097
1098 .orElseGet(() -> new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB)));
1099 GridBagConstraints gbc = new GridBagConstraints();
1100 gbc.ipadx = 5;
1101 recentTagsPanel.add(new JLabel(action.isEnabled() ? icon : GuiHelper.getDisabledIcon(icon)), gbc);
1102 // Create tag label
1103 final String color = action.isEnabled() ? "" : "; color:gray";
1104 final JLabel tagLabel = new JLabel(HTML
1105 + "<style>td{" + color + "}</style>"
1106 + "<table><tr>"
1107 + "<td>" + count + ".</td>"
1108 + "<td style='border:1px solid gray'>" + XmlWriter.encode(t.toString(), true) + '<' +
1109 "/td></tr></table></html>");
1110 tagLabel.setFont(tagLabel.getFont().deriveFont(Font.PLAIN));
1111 if (action.isEnabled() && sc != null && scShift != null) {
1112 // Register action
1113 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), "choose"+count);
1114 recentTagsPanel.getActionMap().put("choose"+count, action);
1115 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), "apply"+count);
1116 recentTagsPanel.getActionMap().put("apply"+count, actionShift);
1117 }
1118 if (action.isEnabled()) {
1119 // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut)
1120 tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
1121 tagLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
1122 tagLabel.addMouseListener(new MouseAdapter() {
1123 @Override
1124 public void mouseClicked(MouseEvent e) {
1125 action.actionPerformed(null);
1126 if (SwingUtilities.isRightMouseButton(e)) {
1127 Component component = e.getComponent();
1128 if (component.isShowing()) {
1129 new TagPopupMenu(t).show(component, e.getX(), e.getY());
1130 }
1131 } else if (e.isShiftDown()) {
1132 // add tags on Shift-Click
1133 performTagAdding();
1134 refreshRecentTags();
1135 keys.requestFocus();
1136 } else if (e.getClickCount() > 1) {
1137 // add tags and close window on double-click
1138 buttonAction(0, null); // emulate OK click and close the dialog
1139 }
1140 }
1141 });
1142 } else {
1143 // Disable tag label
1144 tagLabel.setEnabled(false);
1145 // Explain in the tooltip why
1146 tagLabel.setToolTipText(tr("The key ''{0}'' is already used", t.getKey()));
1147 }
1148 // Finally add label to the resulting panel
1149 JPanel tagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
1150 tagPanel.add(tagLabel);
1151 recentTagsPanel.add(tagPanel, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
1152 }
1153 // Clear label if no tags were added
1154 if (count == 0) {
1155 recentTagsPanel.removeAll();
1156 }
1157 }
1158
1159 class TagPopupMenu extends JPopupMenu {
1160
1161 TagPopupMenu(Tag t) {
1162 add(new IgnoreTagAction(tr("Ignore key ''{0}''", t.getKey()), new Tag(t.getKey(), "")));
1163 add(new IgnoreTagAction(tr("Ignore tag ''{0}''", t), t));
1164 add(new EditIgnoreTagsAction());
1165 }
1166 }
1167
1168 class IgnoreTagAction extends AbstractAction {
1169 final transient Tag tag;
1170
1171 IgnoreTagAction(String name, Tag tag) {
1172 super(name);
1173 this.tag = tag;
1174 }
1175
1176 @Override
1177 public void actionPerformed(ActionEvent e) {
1178 try {
1179 if (tagsToIgnore != null) {
1180 recentTags.ignoreTag(tag, tagsToIgnore);
1181 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString());
1182 }
1183 } catch (SearchParseError parseError) {
1184 throw new IllegalStateException(parseError);
1185 }
1186 }
1187 }
1188
1189 class EditIgnoreTagsAction extends AbstractAction {
1190
1191 EditIgnoreTagsAction() {
1192 super(tr("Edit ignore list"));
1193 }
1194
1195 @Override
1196 public void actionPerformed(ActionEvent e) {
1197 final SearchSetting newTagsToIngore = SearchAction.showSearchDialog(tagsToIgnore);
1198 if (newTagsToIngore == null) {
1199 return;
1200 }
1201 try {
1202 tagsToIgnore = newTagsToIngore;
1203 recentTags.setTagsToIgnore(tagsToIgnore);
1204 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString());
1205 } catch (SearchParseError parseError) {
1206 warnAboutParseError(parseError);
1207 }
1208 }
1209 }
1210
1211 /**
1212 * Destroy the recentTagsActions.
1213 */
1214 public void destroyActions() {
1215 for (JosmAction action : recentTagsActions) {
1216 action.destroy();
1217 }
1218 recentTagsActions.clear();
1219 }
1220
1221 /**
1222 * Read tags from comboboxes and add it to all selected objects
1223 */
1224 public final void performTagAdding() {
1225 Collection<OsmPrimitive> selection = sel;
1226 if (!Utils.isEmpty(selection)) {
1227 performTagAdding(selection);
1228 }
1229 }
1230
1231 /**
1232 * Read tags from comboboxes and add it to all selected objects
1233 * @param selection The selection to perform tag adding on
1234 * @since 18842
1235 */
1236 private void performTagAdding(Collection<OsmPrimitive> selection) {
1237 String key = getEditItem(keys);
1238 String value = getEditItem(values);
1239 if (key.isEmpty() || value.isEmpty())
1240 return;
1241 for (Tagged osm : selection) {
1242 String val = osm.get(key);
1243 if (val != null && !val.equals(value)) {
1244 String valueHtmlString = Utils.joinAsHtmlUnorderedList(Arrays.asList("<strike>" + val + "</strike>", value));
1245 if (!warnOverwriteKey(HTML
1246 + tr("You changed the value of ''{0}'': {1}", key, valueHtmlString)
1247 + tr("Overwrite?"), "overwriteAddKey"))
1248 return;
1249 break;
1250 }
1251 }
1252 recentTags.add(new Tag(key, value));
1253 valueCount.put(key, new TreeMap<>());
1254 AutoCompletionManager.rememberUserInput(key, value, false);
1255 commandCount++;
1256 UndoRedoHandler.getInstance().add(new ChangePropertyCommand(selection, key, value));
1257 changedKey = key;
1258 clearEntries();
1259 }
1260
1261 protected void clearEntries() {
1262 keys.getEditor().setItem("");
1263 values.getEditor().setItem("");
1264 }
1265
1266 /**
1267 * Undo all tag add commands that this dialog has created
1268 */
1269 public void undoAllTagsAdding() {
1270 UndoRedoHandler.getInstance().undo(commandCount);
1271 }
1272
1273 private void refreshRecentTags() {
1274 switch (PROPERTY_REFRESH_RECENT.get()) {
1275 case REFRESH:
1276 cacheRecentTags();
1277 suggestRecentlyAddedTags();
1278 break;
1279 case STATUS:
1280 suggestRecentlyAddedTags();
1281 break;
1282 default: // Do nothing
1283 }
1284 }
1285 }
1286}
Note: See TracBrowser for help on using the repository browser.