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

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

fix #14527 - Add Tag - last entry disabled for partial dataset

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