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

Last change on this file since 16838 was 16838, checked in by simon04, 4 years ago

see #19622 - Extract OsmPrimitiveImageProvider

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