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

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

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

  • 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.Logging;
91import org.openstreetmap.josm.tools.Shortcut;
92import org.openstreetmap.josm.tools.Utils;
93import org.openstreetmap.josm.tools.WindowGeometry;
94
95/**
96 * Class that helps PropertiesDialog add and edit tag values.
97 * @since 5633
98 */
99public class TagEditHelper {
100
101 private final JTable tagTable;
102 private final DefaultTableModel tagData;
103 private final Map<String, Map<String, Integer>> valueCount;
104
105 // Selection that we are editing by using both dialogs
106 protected Collection<OsmPrimitive> sel;
107
108 private String changedKey;
109 private String objKey;
110
111 static final Comparator<AutoCompletionListItem> DEFAULT_AC_ITEM_COMPARATOR =
112 (o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
113
114 /** Default number of recent tags */
115 public static final int DEFAULT_LRU_TAGS_NUMBER = 5;
116 /** Maximum number of recent tags */
117 public static final int MAX_LRU_TAGS_NUMBER = 30;
118
119 /** Use English language for tag by default */
120 public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE = new BooleanProperty("properties.fix-tag-combobox-locale", false);
121 /** Whether recent tags must be remembered */
122 public static final BooleanProperty PROPERTY_REMEMBER_TAGS = new BooleanProperty("properties.remember-recently-added-tags", true);
123 /** Number of recent tags */
124 public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER = new IntegerProperty("properties.recently-added-tags",
125 DEFAULT_LRU_TAGS_NUMBER);
126 /** The preference storage of recent tags */
127 public static final CollectionProperty PROPERTY_RECENT_TAGS = new CollectionProperty("properties.recent-tags",
128 Collections.<String>emptyList());
129 public static final StringProperty PROPERTY_TAGS_TO_IGNORE = new StringProperty("properties.recent-tags.ignore",
130 new SearchAction.SearchSetting().writeToString());
131
132 /**
133 * What to do with recent tags where keys already exist
134 */
135 private enum RecentExisting {
136 ENABLE,
137 DISABLE,
138 HIDE
139 }
140
141 /**
142 * Preference setting for popup menu item "Recent tags with existing key"
143 */
144 public static final EnumProperty<RecentExisting> PROPERTY_RECENT_EXISTING = new EnumProperty<>(
145 "properties.recently-added-tags-existing-key", RecentExisting.class, RecentExisting.DISABLE);
146
147 /**
148 * What to do after applying tag
149 */
150 private enum RefreshRecent {
151 NO,
152 STATUS,
153 REFRESH
154 }
155
156 /**
157 * Preference setting for popup menu item "Refresh recent tags list after applying tag"
158 */
159 public static final EnumProperty<RefreshRecent> PROPERTY_REFRESH_RECENT = new EnumProperty<>(
160 "properties.refresh-recently-added-tags", RefreshRecent.class, RefreshRecent.STATUS);
161
162 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER);
163 SearchAction.SearchSetting tagsToIgnore;
164
165 /**
166 * Copy of recently added tags in sorted from newest to oldest order.
167 *
168 * We store the maximum number of recent tags to allow dynamic change of number of tags shown in the preferences.
169 * Used to cache initial status.
170 */
171 private List<Tag> tags;
172
173 static {
174 // init user input based on recent tags
175 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER);
176 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS);
177 recentTags.toList().forEach(tag -> AutoCompletionManager.rememberUserInput(tag.getKey(), tag.getValue(), false));
178 }
179
180 /**
181 * Constructs a new {@code TagEditHelper}.
182 * @param tagTable tag table
183 * @param propertyData table model
184 * @param valueCount tag value count
185 */
186 public TagEditHelper(JTable tagTable, DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
187 this.tagTable = tagTable;
188 this.tagData = propertyData;
189 this.valueCount = valueCount;
190 }
191
192 /**
193 * Finds the key from given row of tag editor.
194 * @param viewRow index of row
195 * @return key of tag
196 */
197 public final String getDataKey(int viewRow) {
198 return tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 0).toString();
199 }
200
201 /**
202 * Determines if the given tag key is already used (by all selected primitives, not just some of them)
203 * @param key the key to check
204 * @return {@code true} if the key is used by all selected primitives (key not unset for at least one primitive)
205 */
206 @SuppressWarnings("unchecked")
207 boolean containsDataKey(String key) {
208 return IntStream.range(0, tagData.getRowCount())
209 .anyMatch(i -> key.equals(tagData.getValueAt(i, 0)) /* sic! do not use getDataKey*/
210 && !((Map<String, Integer>) tagData.getValueAt(i, 1)).containsKey("") /* sic! do not use getDataValues*/);
211 }
212
213 /**
214 * Finds the values from given row of tag editor.
215 * @param viewRow index of row
216 * @return map of values and number of occurrences
217 */
218 @SuppressWarnings("unchecked")
219 public final Map<String, Integer> getDataValues(int viewRow) {
220 return (Map<String, Integer>) tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 1);
221 }
222
223 /**
224 * Open the add selection dialog and add a new key/value to the table (and
225 * to the dataset, of course).
226 */
227 public void addTag() {
228 changedKey = null;
229 sel = Main.main.getInProgressSelection();
230 if (sel == null || sel.isEmpty())
231 return;
232
233 final AddTagsDialog addDialog = getAddTagsDialog();
234
235 addDialog.showDialog();
236
237 addDialog.destroyActions();
238 if (addDialog.getValue() == 1)
239 addDialog.performTagAdding();
240 else
241 addDialog.undoAllTagsAdding();
242 }
243
244 /**
245 * Returns a new {@code AddTagsDialog}.
246 * @return a new {@code AddTagsDialog}
247 */
248 protected AddTagsDialog getAddTagsDialog() {
249 return new AddTagsDialog();
250 }
251
252 /**
253 * Edit the value in the tags table row.
254 * @param row The row of the table from which the value is edited.
255 * @param focusOnKey Determines if the initial focus should be set on key instead of value
256 * @since 5653
257 */
258 public void editTag(final int row, boolean focusOnKey) {
259 changedKey = null;
260 sel = Main.main.getInProgressSelection();
261 if (sel == null || sel.isEmpty())
262 return;
263
264 String key = getDataKey(row);
265 objKey = key;
266
267 final IEditTagDialog editDialog = getEditTagDialog(row, focusOnKey, key);
268 editDialog.showDialog();
269 if (editDialog.getValue() != 1)
270 return;
271 editDialog.performTagEdit();
272 }
273
274 /**
275 * Extracted interface of {@link EditTagDialog}.
276 */
277 protected interface IEditTagDialog extends IExtendedDialog {
278 /**
279 * Edit tags of multiple selected objects according to selected ComboBox values
280 * If value == "", tag will be deleted
281 * Confirmations may be needed.
282 */
283 void performTagEdit();
284 }
285
286 protected IEditTagDialog getEditTagDialog(int row, boolean focusOnKey, String key) {
287 return new EditTagDialog(key, getDataValues(row), focusOnKey);
288 }
289
290 /**
291 * If during last editProperty call user changed the key name, this key will be returned
292 * Elsewhere, returns null.
293 * @return The modified key, or {@code null}
294 */
295 public String getChangedKey() {
296 return changedKey;
297 }
298
299 /**
300 * Reset last changed key.
301 */
302 public void resetChangedKey() {
303 changedKey = null;
304 }
305
306 /**
307 * For a given key k, return a list of keys which are used as keys for
308 * auto-completing values to increase the search space.
309 * @param key the key k
310 * @return a list of keys
311 */
312 private static List<String> getAutocompletionKeys(String key) {
313 if ("name".equals(key) || "addr:street".equals(key))
314 return Arrays.asList("addr:street", "name");
315 else
316 return Arrays.asList(key);
317 }
318
319 /**
320 * Load recently used tags from preferences if needed.
321 */
322 public void loadTagsIfNeeded() {
323 loadTagsToIgnore();
324 if (PROPERTY_REMEMBER_TAGS.get() && recentTags.isEmpty()) {
325 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS);
326 }
327 }
328
329 void loadTagsToIgnore() {
330 final SearchAction.SearchSetting searchSetting = Utils.firstNonNull(
331 SearchAction.SearchSetting.readFromString(PROPERTY_TAGS_TO_IGNORE.get()), new SearchAction.SearchSetting());
332 if (!Objects.equals(tagsToIgnore, searchSetting)) {
333 try {
334 tagsToIgnore = searchSetting;
335 recentTags.setTagsToIgnore(tagsToIgnore);
336 } catch (SearchCompiler.ParseError parseError) {
337 warnAboutParseError(parseError);
338 tagsToIgnore = new SearchAction.SearchSetting();
339 recentTags.setTagsToIgnore(SearchCompiler.Never.INSTANCE);
340 }
341 }
342 }
343
344 private static void warnAboutParseError(SearchCompiler.ParseError parseError) {
345 Logging.warn(parseError);
346 JOptionPane.showMessageDialog(
347 Main.parent,
348 parseError.getMessage(),
349 tr("Error"),
350 JOptionPane.ERROR_MESSAGE
351 );
352 }
353
354 /**
355 * Store recently used tags in preferences if needed.
356 */
357 public void saveTagsIfNeeded() {
358 if (PROPERTY_REMEMBER_TAGS.get() && !recentTags.isEmpty()) {
359 recentTags.saveToPreference(PROPERTY_RECENT_TAGS);
360 }
361 }
362
363 /**
364 * Update cache of recent tags used for displaying tags.
365 */
366 private void cacheRecentTags() {
367 tags = recentTags.toList();
368 Collections.reverse(tags);
369 }
370
371 /**
372 * Warns user about a key being overwritten.
373 * @param action The action done by the user. Must state what key is changed
374 * @param togglePref The preference to save the checkbox state to
375 * @return {@code true} if the user accepts to overwrite key, {@code false} otherwise
376 */
377 private static boolean warnOverwriteKey(String action, String togglePref) {
378 return new ExtendedDialog(
379 Main.parent,
380 tr("Overwrite key"),
381 tr("Replace"), tr("Cancel"))
382 .setButtonIcons("purge", "cancel")
383 .setContent(action+'\n'+ tr("The new key is already used, overwrite values?"))
384 .setCancelButton(2)
385 .toggleEnable(togglePref)
386 .showDialog().getValue() == 1;
387 }
388
389 protected class EditTagDialog extends AbstractTagsDialog implements IEditTagDialog {
390 private final String key;
391 private final transient Map<String, Integer> m;
392 private final transient Comparator<AutoCompletionListItem> usedValuesAwareComparator;
393
394 private final transient ListCellRenderer<AutoCompletionListItem> cellRenderer = new ListCellRenderer<AutoCompletionListItem>() {
395 private final DefaultListCellRenderer def = new DefaultListCellRenderer();
396 @Override
397 public Component getListCellRendererComponent(JList<? extends AutoCompletionListItem> list,
398 AutoCompletionListItem value, int index, boolean isSelected, boolean cellHasFocus) {
399 Component c = def.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
400 if (c instanceof JLabel) {
401 String str = value.getValue();
402 if (valueCount.containsKey(objKey)) {
403 Map<String, Integer> map = valueCount.get(objKey);
404 if (map.containsKey(str)) {
405 str = tr("{0} ({1})", str, map.get(str));
406 c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD));
407 }
408 }
409 ((JLabel) c).setText(str);
410 }
411 return c;
412 }
413 };
414
415 protected EditTagDialog(String key, Map<String, Integer> map, final boolean initialFocusOnKey) {
416 super(Main.parent, trn("Change value?", "Change values?", map.size()), tr("OK"), tr("Cancel"));
417 setButtonIcons("ok", "cancel");
418 setCancelButton(2);
419 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);
420 this.key = key;
421 this.m = map;
422
423 usedValuesAwareComparator = (o1, o2) -> {
424 boolean c1 = m.containsKey(o1.getValue());
425 boolean c2 = m.containsKey(o2.getValue());
426 if (c1 == c2)
427 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
428 else if (c1)
429 return -1;
430 else
431 return +1;
432 };
433
434 JPanel mainPanel = new JPanel(new BorderLayout());
435
436 String msg = "<html>"+trn("This will change {0} object.",
437 "This will change up to {0} objects.", sel.size(), sel.size())
438 +"<br><br>("+tr("An empty value deletes the tag.", key)+")</html>";
439
440 mainPanel.add(new JLabel(msg), BorderLayout.NORTH);
441
442 JPanel p = new JPanel(new GridBagLayout());
443 mainPanel.add(p, BorderLayout.CENTER);
444
445 AutoCompletionManager autocomplete = Main.getLayerManager().getEditLayer().data.getAutoCompletionManager();
446 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
447 keyList.sort(DEFAULT_AC_ITEM_COMPARATOR);
448
449 keys = new AutoCompletingComboBox(key);
450 keys.setPossibleACItems(keyList);
451 keys.setEditable(true);
452 keys.setSelectedItem(key);
453
454 p.add(Box.createVerticalStrut(5), GBC.eol());
455 p.add(new JLabel(tr("Key")), GBC.std());
456 p.add(Box.createHorizontalStrut(10), GBC.std());
457 p.add(keys, GBC.eol().fill(GBC.HORIZONTAL));
458
459 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
460 valueList.sort(usedValuesAwareComparator);
461
462 final String selection = m.size() != 1 ? tr("<different>") : m.entrySet().iterator().next().getKey();
463
464 values = new AutoCompletingComboBox(selection);
465 values.setRenderer(cellRenderer);
466
467 values.setEditable(true);
468 values.setPossibleACItems(valueList);
469 values.setSelectedItem(selection);
470 values.getEditor().setItem(selection);
471 p.add(Box.createVerticalStrut(5), GBC.eol());
472 p.add(new JLabel(tr("Value")), GBC.std());
473 p.add(Box.createHorizontalStrut(10), GBC.std());
474 p.add(values, GBC.eol().fill(GBC.HORIZONTAL));
475 values.getEditor().addActionListener(e -> buttonAction(0, null));
476 addFocusAdapter(autocomplete, usedValuesAwareComparator);
477
478 setContent(mainPanel, false);
479
480 addWindowListener(new WindowAdapter() {
481 @Override
482 public void windowOpened(WindowEvent e) {
483 if (initialFocusOnKey) {
484 selectKeysComboBox();
485 } else {
486 selectValuesCombobox();
487 }
488 }
489 });
490 }
491
492 @Override
493 public void performTagEdit() {
494 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
495 value = Normalizer.normalize(value, Normalizer.Form.NFC);
496 if (value.isEmpty()) {
497 value = null; // delete the key
498 }
499 String newkey = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
500 newkey = Normalizer.normalize(newkey, Normalizer.Form.NFC);
501 if (newkey.isEmpty()) {
502 newkey = key;
503 value = null; // delete the key instead
504 }
505 if (key.equals(newkey) && tr("<different>").equals(value))
506 return;
507 if (key.equals(newkey) || value == null) {
508 Main.main.undoRedo.add(new ChangePropertyCommand(sel, newkey, value));
509 AutoCompletionManager.rememberUserInput(newkey, value, true);
510 } else {
511 for (OsmPrimitive osm: sel) {
512 if (osm.get(newkey) != null) {
513 if (!warnOverwriteKey(tr("You changed the key from ''{0}'' to ''{1}''.", key, newkey),
514 "overwriteEditKey"))
515 return;
516 break;
517 }
518 }
519 Collection<Command> commands = new ArrayList<>();
520 commands.add(new ChangePropertyCommand(sel, key, null));
521 if (value.equals(tr("<different>"))) {
522 Map<String, List<OsmPrimitive>> map = new HashMap<>();
523 for (OsmPrimitive osm: sel) {
524 String val = osm.get(key);
525 if (val != null) {
526 if (map.containsKey(val)) {
527 map.get(val).add(osm);
528 } else {
529 List<OsmPrimitive> v = new ArrayList<>();
530 v.add(osm);
531 map.put(val, v);
532 }
533 }
534 }
535 for (Map.Entry<String, List<OsmPrimitive>> e: map.entrySet()) {
536 commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey()));
537 }
538 } else {
539 commands.add(new ChangePropertyCommand(sel, newkey, value));
540 AutoCompletionManager.rememberUserInput(newkey, value, false);
541 }
542 Main.main.undoRedo.add(new SequenceCommand(
543 trn("Change properties of up to {0} object",
544 "Change properties of up to {0} objects", sel.size(), sel.size()),
545 commands));
546 }
547
548 changedKey = newkey;
549 }
550 }
551
552 protected abstract class AbstractTagsDialog extends ExtendedDialog {
553 protected AutoCompletingComboBox keys;
554 protected AutoCompletingComboBox values;
555
556 AbstractTagsDialog(Component parent, String title, String... buttonTexts) {
557 super(parent, title, buttonTexts);
558 addMouseListener(new PopupMenuLauncher(popupMenu));
559 }
560
561 @Override
562 public void setupDialog() {
563 super.setupDialog();
564 final Dimension size = getSize();
565 // Set resizable only in width
566 setMinimumSize(size);
567 setPreferredSize(size);
568 // setMaximumSize does not work, and never worked, but still it seems not to bother Oracle to fix this 10-year-old bug
569 // https://bugs.openjdk.java.net/browse/JDK-6200438
570 // https://bugs.openjdk.java.net/browse/JDK-6464548
571
572 setRememberWindowGeometry(getClass().getName() + ".geometry",
573 WindowGeometry.centerInWindow(Main.parent, size));
574 }
575
576 @Override
577 public void setVisible(boolean visible) {
578 // Do not want dialog to be resizable in height, as its size may increase each time because of the recently added tags
579 // So need to modify the stored geometry (size part only) in order to use the automatic positioning mechanism
580 if (visible) {
581 WindowGeometry geometry = initWindowGeometry();
582 Dimension storedSize = geometry.getSize();
583 Dimension size = getSize();
584 if (!storedSize.equals(size)) {
585 if (storedSize.width < size.width) {
586 storedSize.width = size.width;
587 }
588 if (storedSize.height != size.height) {
589 storedSize.height = size.height;
590 }
591 rememberWindowGeometry(geometry);
592 }
593 keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
594 }
595 super.setVisible(visible);
596 }
597
598 private void selectACComboBoxSavingUnixBuffer(AutoCompletingComboBox cb) {
599 // select combobox with saving unix system selection (middle mouse paste)
600 Clipboard sysSel = ClipboardUtils.getSystemSelection();
601 if (sysSel != null) {
602 Transferable old = ClipboardUtils.getClipboardContent(sysSel);
603 cb.requestFocusInWindow();
604 cb.getEditor().selectAll();
605 if (old != null) {
606 sysSel.setContents(old, null);
607 }
608 } else {
609 cb.requestFocusInWindow();
610 cb.getEditor().selectAll();
611 }
612 }
613
614 public void selectKeysComboBox() {
615 selectACComboBoxSavingUnixBuffer(keys);
616 }
617
618 public void selectValuesCombobox() {
619 selectACComboBoxSavingUnixBuffer(values);
620 }
621
622 /**
623 * Create a focus handling adapter and apply in to the editor component of value
624 * autocompletion box.
625 * @param autocomplete Manager handling the autocompletion
626 * @param comparator Class to decide what values are offered on autocompletion
627 * @return The created adapter
628 */
629 protected FocusAdapter addFocusAdapter(final AutoCompletionManager autocomplete, final Comparator<AutoCompletionListItem> comparator) {
630 // get the combo box' editor component
631 final JTextComponent editor = values.getEditorComponent();
632 // Refresh the values model when focus is gained
633 FocusAdapter focus = new FocusAdapter() {
634 @Override
635 public void focusGained(FocusEvent e) {
636 String key = keys.getEditor().getItem().toString();
637
638 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
639 valueList.sort(comparator);
640 Logging.trace("Focus gained by {0}, e={1}", values, e);
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?"), tr("OK"), tr("Cancel"));
678 setButtonIcons("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(DEFAULT_AC_ITEM_COMPARATOR);
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, DEFAULT_AC_ITEM_COMPARATOR);
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_DOWN_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(Shortcut.getKeyText(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK)) + ' '
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 Logging.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.