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

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

initialize unit tests for TagEditHelper

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