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

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

see #15229 - deprecate Main.parent and Main itself

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