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

Last change on this file since 12846 was 12846, checked in by bastiK, 7 years ago

see #15229 - use Config.getPref() wherever possible

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