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

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

sonar - fb-contrib:SCII_SPOILED_CHILD_INTERFACE_IMPLEMENTOR - Style - Class implements interface by relying on unknowing superclass methods

  • Property svn:eol-style set to native
File size: 46.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.dialogs.properties;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.BorderLayout;
8import java.awt.Component;
9import java.awt.Container;
10import java.awt.Cursor;
11import java.awt.Dimension;
12import java.awt.FlowLayout;
13import java.awt.Font;
14import java.awt.GridBagConstraints;
15import java.awt.GridBagLayout;
16import java.awt.datatransfer.Clipboard;
17import java.awt.datatransfer.Transferable;
18import java.awt.event.ActionEvent;
19import java.awt.event.FocusAdapter;
20import java.awt.event.FocusEvent;
21import java.awt.event.InputEvent;
22import java.awt.event.KeyEvent;
23import java.awt.event.MouseAdapter;
24import java.awt.event.MouseEvent;
25import java.awt.event.WindowAdapter;
26import java.awt.event.WindowEvent;
27import java.awt.image.BufferedImage;
28import java.text.Normalizer;
29import java.util.ArrayList;
30import java.util.Arrays;
31import java.util.Collection;
32import java.util.Collections;
33import java.util.Comparator;
34import java.util.HashMap;
35import java.util.List;
36import java.util.Map;
37import java.util.Objects;
38import java.util.TreeMap;
39import java.util.stream.IntStream;
40
41import javax.swing.AbstractAction;
42import javax.swing.Action;
43import javax.swing.Box;
44import javax.swing.ButtonGroup;
45import javax.swing.DefaultListCellRenderer;
46import javax.swing.ImageIcon;
47import javax.swing.JCheckBoxMenuItem;
48import javax.swing.JComponent;
49import javax.swing.JLabel;
50import javax.swing.JList;
51import javax.swing.JMenu;
52import javax.swing.JOptionPane;
53import javax.swing.JPanel;
54import javax.swing.JPopupMenu;
55import javax.swing.JRadioButtonMenuItem;
56import javax.swing.JTable;
57import javax.swing.KeyStroke;
58import javax.swing.ListCellRenderer;
59import javax.swing.SwingUtilities;
60import javax.swing.table.DefaultTableModel;
61import javax.swing.text.JTextComponent;
62
63import org.openstreetmap.josm.Main;
64import org.openstreetmap.josm.actions.JosmAction;
65import org.openstreetmap.josm.actions.search.SearchAction;
66import org.openstreetmap.josm.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 private final Comparator<AutoCompletionListItem> defaultACItemComparator =
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 private boolean containsDataKey(String key) {
207 return IntStream.range(0, tagData.getRowCount())
208 .filter(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 .findAny().isPresent();
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 Main.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 ExtendedDialog ed = new ExtendedDialog(
379 Main.parent,
380 tr("Overwrite key"),
381 new String[]{tr("Replace"), tr("Cancel")});
382 ed.setButtonIcons(new String[]{"purge", "cancel"});
383 ed.setContent(action+'\n'+ tr("The new key is already used, overwrite values?"));
384 ed.setCancelButton(2);
385 ed.toggleEnable(togglePref);
386 ed.showDialog();
387
388 return ed.getValue() == 1;
389 }
390
391 protected class EditTagDialog extends AbstractTagsDialog implements IEditTagDialog {
392 private final String key;
393 private final transient Map<String, Integer> m;
394 private final transient Comparator<AutoCompletionListItem> usedValuesAwareComparator;
395
396 private final transient ListCellRenderer<AutoCompletionListItem> cellRenderer = new ListCellRenderer<AutoCompletionListItem>() {
397 private final DefaultListCellRenderer def = new DefaultListCellRenderer();
398 @Override
399 public Component getListCellRendererComponent(JList<? extends AutoCompletionListItem> list,
400 AutoCompletionListItem value, int index, boolean isSelected, boolean cellHasFocus) {
401 Component c = def.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
402 if (c instanceof JLabel) {
403 String str = value.getValue();
404 if (valueCount.containsKey(objKey)) {
405 Map<String, Integer> map = valueCount.get(objKey);
406 if (map.containsKey(str)) {
407 str = tr("{0} ({1})", str, map.get(str));
408 c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD));
409 }
410 }
411 ((JLabel) c).setText(str);
412 }
413 return c;
414 }
415 };
416
417 protected EditTagDialog(String key, Map<String, Integer> map, final boolean initialFocusOnKey) {
418 super(Main.parent, trn("Change value?", "Change values?", map.size()), new String[] {tr("OK"), tr("Cancel")});
419 setButtonIcons(new String[] {"ok", "cancel"});
420 setCancelButton(2);
421 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);
422 this.key = key;
423 this.m = map;
424
425 usedValuesAwareComparator = (o1, o2) -> {
426 boolean c1 = m.containsKey(o1.getValue());
427 boolean c2 = m.containsKey(o2.getValue());
428 if (c1 == c2)
429 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
430 else if (c1)
431 return -1;
432 else
433 return +1;
434 };
435
436 JPanel mainPanel = new JPanel(new BorderLayout());
437
438 String msg = "<html>"+trn("This will change {0} object.",
439 "This will change up to {0} objects.", sel.size(), sel.size())
440 +"<br><br>("+tr("An empty value deletes the tag.", key)+")</html>";
441
442 mainPanel.add(new JLabel(msg), BorderLayout.NORTH);
443
444 JPanel p = new JPanel(new GridBagLayout());
445 mainPanel.add(p, BorderLayout.CENTER);
446
447 AutoCompletionManager autocomplete = Main.getLayerManager().getEditLayer().data.getAutoCompletionManager();
448 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
449 keyList.sort(defaultACItemComparator);
450
451 keys = new AutoCompletingComboBox(key);
452 keys.setPossibleACItems(keyList);
453 keys.setEditable(true);
454 keys.setSelectedItem(key);
455
456 p.add(Box.createVerticalStrut(5), GBC.eol());
457 p.add(new JLabel(tr("Key")), GBC.std());
458 p.add(Box.createHorizontalStrut(10), GBC.std());
459 p.add(keys, GBC.eol().fill(GBC.HORIZONTAL));
460
461 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
462 valueList.sort(usedValuesAwareComparator);
463
464 final String selection = m.size() != 1 ? tr("<different>") : m.entrySet().iterator().next().getKey();
465
466 values = new AutoCompletingComboBox(selection);
467 values.setRenderer(cellRenderer);
468
469 values.setEditable(true);
470 values.setPossibleACItems(valueList);
471 values.setSelectedItem(selection);
472 values.getEditor().setItem(selection);
473 p.add(Box.createVerticalStrut(5), GBC.eol());
474 p.add(new JLabel(tr("Value")), GBC.std());
475 p.add(Box.createHorizontalStrut(10), GBC.std());
476 p.add(values, GBC.eol().fill(GBC.HORIZONTAL));
477 values.getEditor().addActionListener(e -> buttonAction(0, null));
478 addFocusAdapter(autocomplete, usedValuesAwareComparator);
479
480 setContent(mainPanel, false);
481
482 addWindowListener(new WindowAdapter() {
483 @Override
484 public void windowOpened(WindowEvent e) {
485 if (initialFocusOnKey) {
486 selectKeysComboBox();
487 } else {
488 selectValuesCombobox();
489 }
490 }
491 });
492 }
493
494 @Override
495 public void performTagEdit() {
496 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
497 value = Normalizer.normalize(value, Normalizer.Form.NFC);
498 if (value.isEmpty()) {
499 value = null; // delete the key
500 }
501 String newkey = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
502 newkey = Normalizer.normalize(newkey, Normalizer.Form.NFC);
503 if (newkey.isEmpty()) {
504 newkey = key;
505 value = null; // delete the key instead
506 }
507 if (key.equals(newkey) && tr("<different>").equals(value))
508 return;
509 if (key.equals(newkey) || value == null) {
510 Main.main.undoRedo.add(new ChangePropertyCommand(sel, newkey, value));
511 AutoCompletionManager.rememberUserInput(newkey, value, true);
512 } else {
513 for (OsmPrimitive osm: sel) {
514 if (osm.get(newkey) != null) {
515 if (!warnOverwriteKey(tr("You changed the key from ''{0}'' to ''{1}''.", key, newkey),
516 "overwriteEditKey"))
517 return;
518 break;
519 }
520 }
521 Collection<Command> commands = new ArrayList<>();
522 commands.add(new ChangePropertyCommand(sel, key, null));
523 if (value.equals(tr("<different>"))) {
524 Map<String, List<OsmPrimitive>> map = new HashMap<>();
525 for (OsmPrimitive osm: sel) {
526 String val = osm.get(key);
527 if (val != null) {
528 if (map.containsKey(val)) {
529 map.get(val).add(osm);
530 } else {
531 List<OsmPrimitive> v = new ArrayList<>();
532 v.add(osm);
533 map.put(val, v);
534 }
535 }
536 }
537 for (Map.Entry<String, List<OsmPrimitive>> e: map.entrySet()) {
538 commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey()));
539 }
540 } else {
541 commands.add(new ChangePropertyCommand(sel, newkey, value));
542 AutoCompletionManager.rememberUserInput(newkey, value, false);
543 }
544 Main.main.undoRedo.add(new SequenceCommand(
545 trn("Change properties of up to {0} object",
546 "Change properties of up to {0} objects", sel.size(), sel.size()),
547 commands));
548 }
549
550 changedKey = newkey;
551 }
552 }
553
554 protected abstract class AbstractTagsDialog extends ExtendedDialog {
555 protected AutoCompletingComboBox keys;
556 protected AutoCompletingComboBox values;
557
558 AbstractTagsDialog(Component parent, String title, String... buttonTexts) {
559 super(parent, title, buttonTexts);
560 addMouseListener(new PopupMenuLauncher(popupMenu));
561 }
562
563 @Override
564 public void setupDialog() {
565 super.setupDialog();
566 final Dimension size = getSize();
567 // Set resizable only in width
568 setMinimumSize(size);
569 setPreferredSize(size);
570 // setMaximumSize does not work, and never worked, but still it seems not to bother Oracle to fix this 10-year-old bug
571 // https://bugs.openjdk.java.net/browse/JDK-6200438
572 // https://bugs.openjdk.java.net/browse/JDK-6464548
573
574 setRememberWindowGeometry(getClass().getName() + ".geometry",
575 WindowGeometry.centerInWindow(Main.parent, size));
576 }
577
578 @Override
579 public void setVisible(boolean visible) {
580 // Do not want dialog to be resizable in height, as its size may increase each time because of the recently added tags
581 // So need to modify the stored geometry (size part only) in order to use the automatic positioning mechanism
582 if (visible) {
583 WindowGeometry geometry = initWindowGeometry();
584 Dimension storedSize = geometry.getSize();
585 Dimension size = getSize();
586 if (!storedSize.equals(size)) {
587 if (storedSize.width < size.width) {
588 storedSize.width = size.width;
589 }
590 if (storedSize.height != size.height) {
591 storedSize.height = size.height;
592 }
593 rememberWindowGeometry(geometry);
594 }
595 keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
596 }
597 super.setVisible(visible);
598 }
599
600 private void selectACComboBoxSavingUnixBuffer(AutoCompletingComboBox cb) {
601 // select combobox with saving unix system selection (middle mouse paste)
602 Clipboard sysSel = ClipboardUtils.getSystemSelection();
603 if (sysSel != null) {
604 Transferable old = ClipboardUtils.getClipboardContent(sysSel);
605 cb.requestFocusInWindow();
606 cb.getEditor().selectAll();
607 if (old != null) {
608 sysSel.setContents(old, null);
609 }
610 } else {
611 cb.requestFocusInWindow();
612 cb.getEditor().selectAll();
613 }
614 }
615
616 public void selectKeysComboBox() {
617 selectACComboBoxSavingUnixBuffer(keys);
618 }
619
620 public void selectValuesCombobox() {
621 selectACComboBoxSavingUnixBuffer(values);
622 }
623
624 /**
625 * Create a focus handling adapter and apply in to the editor component of value
626 * autocompletion box.
627 * @param autocomplete Manager handling the autocompletion
628 * @param comparator Class to decide what values are offered on autocompletion
629 * @return The created adapter
630 */
631 protected FocusAdapter addFocusAdapter(final AutoCompletionManager autocomplete, final Comparator<AutoCompletionListItem> comparator) {
632 // get the combo box' editor component
633 final JTextComponent editor = values.getEditorComponent();
634 // Refresh the values model when focus is gained
635 FocusAdapter focus = new FocusAdapter() {
636 @Override
637 public void focusGained(FocusEvent e) {
638 String key = keys.getEditor().getItem().toString();
639
640 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
641 valueList.sort(comparator);
642 if (Main.isTraceEnabled()) {
643 Main.trace("Focus gained by {0}, e={1}", values, e);
644 }
645 values.setPossibleACItems(valueList);
646 values.getEditor().selectAll();
647 objKey = key;
648 }
649 };
650 editor.addFocusListener(focus);
651 return focus;
652 }
653
654 protected JPopupMenu popupMenu = new JPopupMenu() {
655 private final JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem(
656 new AbstractAction(tr("Use English language for tag by default")) {
657 @Override
658 public void actionPerformed(ActionEvent e) {
659 boolean use = ((JCheckBoxMenuItem) e.getSource()).getState();
660 PROPERTY_FIX_TAG_LOCALE.put(use);
661 keys.setFixedLocale(use);
662 }
663 });
664 {
665 add(fixTagLanguageCb);
666 fixTagLanguageCb.setState(PROPERTY_FIX_TAG_LOCALE.get());
667 }
668 };
669 }
670
671 protected class AddTagsDialog extends AbstractTagsDialog {
672 private final List<JosmAction> recentTagsActions = new ArrayList<>();
673 protected final transient FocusAdapter focus;
674 private final JPanel mainPanel;
675 private JPanel recentTagsPanel;
676
677 // Counter of added commands for possible undo
678 private int commandCount;
679
680 protected AddTagsDialog() {
681 super(Main.parent, tr("Add value?"), new String[] {tr("OK"), tr("Cancel")});
682 setButtonIcons(new String[] {"ok", "cancel"});
683 setCancelButton(2);
684 configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */);
685
686 mainPanel = new JPanel(new GridBagLayout());
687 keys = new AutoCompletingComboBox();
688 values = new AutoCompletingComboBox();
689
690 mainPanel.add(new JLabel("<html>"+trn("This will change up to {0} object.",
691 "This will change up to {0} objects.", sel.size(), sel.size())
692 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL));
693
694 cacheRecentTags();
695 AutoCompletionManager autocomplete = Main.getLayerManager().getEditLayer().data.getAutoCompletionManager();
696 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
697
698 // remove the object's tag keys from the list
699 keyList.removeIf(item -> containsDataKey(item.getValue()));
700
701 keyList.sort(defaultACItemComparator);
702 keys.setPossibleACItems(keyList);
703 keys.setEditable(true);
704
705 mainPanel.add(keys, GBC.eop().fill(GBC.HORIZONTAL));
706
707 mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol());
708 values.setEditable(true);
709 mainPanel.add(values, GBC.eop().fill(GBC.HORIZONTAL));
710
711 // pre-fill first recent tag for which the key is not already present
712 tags.stream()
713 .filter(tag -> !containsDataKey(tag.getKey()))
714 .findFirst()
715 .ifPresent(tag -> {
716 keys.setSelectedItem(tag.getKey());
717 values.setSelectedItem(tag.getValue());
718 });
719
720 focus = addFocusAdapter(autocomplete, defaultACItemComparator);
721 // fire focus event in advance or otherwise the popup list will be too small at first
722 focus.focusGained(null);
723
724 // Add tag on Shift-Enter
725 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
726 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK), "addAndContinue");
727 mainPanel.getActionMap().put("addAndContinue", new AbstractAction() {
728 @Override
729 public void actionPerformed(ActionEvent e) {
730 performTagAdding();
731 refreshRecentTags();
732 selectKeysComboBox();
733 }
734 });
735
736 suggestRecentlyAddedTags();
737
738 mainPanel.add(Box.createVerticalGlue(), GBC.eop().fill());
739 setContent(mainPanel, false);
740
741 selectKeysComboBox();
742
743 popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) {
744 @Override
745 public void actionPerformed(ActionEvent e) {
746 selectNumberOfTags();
747 suggestRecentlyAddedTags();
748 }
749 });
750
751 popupMenu.add(buildMenuRecentExisting());
752 popupMenu.add(buildMenuRefreshRecent());
753
754 JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem(
755 new AbstractAction(tr("Remember last used tags after a restart")) {
756 @Override
757 public void actionPerformed(ActionEvent e) {
758 boolean state = ((JCheckBoxMenuItem) e.getSource()).getState();
759 PROPERTY_REMEMBER_TAGS.put(state);
760 if (state)
761 saveTagsIfNeeded();
762 }
763 });
764 rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get());
765 popupMenu.add(rememberLastTags);
766 }
767
768 private JMenu buildMenuRecentExisting() {
769 JMenu menu = new JMenu(tr("Recent tags with existing key"));
770 TreeMap<RecentExisting, String> radios = new TreeMap<>();
771 radios.put(RecentExisting.ENABLE, tr("Enable"));
772 radios.put(RecentExisting.DISABLE, tr("Disable"));
773 radios.put(RecentExisting.HIDE, tr("Hide"));
774 ButtonGroup buttonGroup = new ButtonGroup();
775 for (final Map.Entry<RecentExisting, String> entry : radios.entrySet()) {
776 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) {
777 @Override
778 public void actionPerformed(ActionEvent e) {
779 PROPERTY_RECENT_EXISTING.put(entry.getKey());
780 suggestRecentlyAddedTags();
781 }
782 });
783 buttonGroup.add(radio);
784 radio.setSelected(PROPERTY_RECENT_EXISTING.get() == entry.getKey());
785 menu.add(radio);
786 }
787 return menu;
788 }
789
790 private JMenu buildMenuRefreshRecent() {
791 JMenu menu = new JMenu(tr("Refresh recent tags list after applying tag"));
792 TreeMap<RefreshRecent, String> radios = new TreeMap<>();
793 radios.put(RefreshRecent.NO, tr("No refresh"));
794 radios.put(RefreshRecent.STATUS, tr("Refresh tag status only (enabled / disabled)"));
795 radios.put(RefreshRecent.REFRESH, tr("Refresh tag status and list of recently added tags"));
796 ButtonGroup buttonGroup = new ButtonGroup();
797 for (final Map.Entry<RefreshRecent, String> entry : radios.entrySet()) {
798 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) {
799 @Override
800 public void actionPerformed(ActionEvent e) {
801 PROPERTY_REFRESH_RECENT.put(entry.getKey());
802 }
803 });
804 buttonGroup.add(radio);
805 radio.setSelected(PROPERTY_REFRESH_RECENT.get() == entry.getKey());
806 menu.add(radio);
807 }
808 return menu;
809 }
810
811 @Override
812 public void setContentPane(Container contentPane) {
813 final int commandDownMask = GuiHelper.getMenuShortcutKeyMaskEx();
814 List<String> lines = new ArrayList<>();
815 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask).ifPresent(sc ->
816 lines.add(sc.getKeyText() + ' ' + tr("to apply first suggestion"))
817 );
818 lines.add(KeyEvent.getKeyModifiersText(KeyEvent.SHIFT_MASK)+'+'+KeyEvent.getKeyText(KeyEvent.VK_ENTER) + ' '
819 +tr("to add without closing the dialog"));
820 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask | KeyEvent.SHIFT_DOWN_MASK).ifPresent(sc ->
821 lines.add(sc.getKeyText() + ' ' + tr("to add first suggestion without closing the dialog"))
822 );
823 final JLabel helpLabel = new JLabel("<html>" + Utils.join("<br>", lines) + "</html>");
824 helpLabel.setFont(helpLabel.getFont().deriveFont(Font.PLAIN));
825 contentPane.add(helpLabel, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(5, 5, 5, 5));
826 super.setContentPane(contentPane);
827 }
828
829 protected void selectNumberOfTags() {
830 String s = String.format("%d", PROPERTY_RECENT_TAGS_NUMBER.get());
831 while (true) {
832 s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"), s);
833 if (s == null || s.isEmpty()) {
834 return;
835 }
836 try {
837 int v = Integer.parseInt(s);
838 if (v >= 0 && v <= MAX_LRU_TAGS_NUMBER) {
839 PROPERTY_RECENT_TAGS_NUMBER.put(v);
840 return;
841 }
842 } catch (NumberFormatException ex) {
843 Main.warn(ex);
844 }
845 JOptionPane.showMessageDialog(this, tr("Please enter integer number between 0 and {0}", MAX_LRU_TAGS_NUMBER));
846 }
847 }
848
849 protected void suggestRecentlyAddedTags() {
850 if (recentTagsPanel == null) {
851 recentTagsPanel = new JPanel(new GridBagLayout());
852 buildRecentTagsPanel();
853 mainPanel.add(recentTagsPanel, GBC.eol().fill(GBC.HORIZONTAL));
854 } else {
855 Dimension panelOldSize = recentTagsPanel.getPreferredSize();
856 recentTagsPanel.removeAll();
857 buildRecentTagsPanel();
858 Dimension panelNewSize = recentTagsPanel.getPreferredSize();
859 Dimension dialogOldSize = getMinimumSize();
860 Dimension dialogNewSize = new Dimension(dialogOldSize.width, dialogOldSize.height-panelOldSize.height+panelNewSize.height);
861 setMinimumSize(dialogNewSize);
862 setPreferredSize(dialogNewSize);
863 setSize(dialogNewSize);
864 revalidate();
865 repaint();
866 }
867 }
868
869 protected void buildRecentTagsPanel() {
870 final int tagsToShow = Math.min(PROPERTY_RECENT_TAGS_NUMBER.get(), MAX_LRU_TAGS_NUMBER);
871 if (!(tagsToShow > 0 && !recentTags.isEmpty()))
872 return;
873 recentTagsPanel.add(new JLabel(tr("Recently added tags")), GBC.eol());
874
875 int count = 0;
876 destroyActions();
877 for (int i = 0; i < tags.size() && count < tagsToShow; i++) {
878 final Tag t = tags.get(i);
879 boolean keyExists = containsDataKey(t.getKey());
880 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.HIDE)
881 continue;
882 count++;
883 // Create action for reusing the tag, with keyboard shortcut
884 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */
885 final Shortcut sc = count > 10 ? null : Shortcut.registerShortcut("properties:recent:" + count,
886 tr("Choose recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL);
887 final JosmAction action = new JosmAction(
888 tr("Choose recent tag {0}", count), null, tr("Use this tag again"), sc, false) {
889 @Override
890 public void actionPerformed(ActionEvent e) {
891 keys.setSelectedItem(t.getKey());
892 // fix #7951, #8298 - update list of values before setting value (?)
893 focus.focusGained(null);
894 values.setSelectedItem(t.getValue());
895 selectValuesCombobox();
896 }
897 };
898 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */
899 final Shortcut scShift = count > 10 ? null : Shortcut.registerShortcut("properties:recent:apply:" + count,
900 tr("Apply recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL_SHIFT);
901 final JosmAction actionShift = new JosmAction(
902 tr("Apply recent tag {0}", count), null, tr("Use this tag again"), scShift, false) {
903 @Override
904 public void actionPerformed(ActionEvent e) {
905 action.actionPerformed(null);
906 performTagAdding();
907 refreshRecentTags();
908 selectKeysComboBox();
909 }
910 };
911 recentTagsActions.add(action);
912 recentTagsActions.add(actionShift);
913 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.DISABLE) {
914 action.setEnabled(false);
915 }
916 // Find and display icon
917 ImageIcon icon = MapPaintStyles.getNodeIcon(t, false); // Filters deprecated icon
918 if (icon == null) {
919 // If no icon found in map style look at presets
920 Map<String, String> map = new HashMap<>();
921 map.put(t.getKey(), t.getValue());
922 for (TaggingPreset tp : TaggingPresets.getMatchingPresets(null, map, false)) {
923 icon = tp.getIcon();
924 if (icon != null) {
925 break;
926 }
927 }
928 // If still nothing display an empty icon
929 if (icon == null) {
930 icon = new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB));
931 }
932 }
933 GridBagConstraints gbc = new GridBagConstraints();
934 gbc.ipadx = 5;
935 recentTagsPanel.add(new JLabel(action.isEnabled() ? icon : GuiHelper.getDisabledIcon(icon)), gbc);
936 // Create tag label
937 final String color = action.isEnabled() ? "" : "; color:gray";
938 final JLabel tagLabel = new JLabel("<html>"
939 + "<style>td{" + color + "}</style>"
940 + "<table><tr>"
941 + "<td>" + count + ".</td>"
942 + "<td style='border:1px solid gray'>" + XmlWriter.encode(t.toString(), true) + '<' +
943 "/td></tr></table></html>");
944 tagLabel.setFont(tagLabel.getFont().deriveFont(Font.PLAIN));
945 if (action.isEnabled() && sc != null && scShift != null) {
946 // Register action
947 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), "choose"+count);
948 recentTagsPanel.getActionMap().put("choose"+count, action);
949 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), "apply"+count);
950 recentTagsPanel.getActionMap().put("apply"+count, actionShift);
951 }
952 if (action.isEnabled()) {
953 // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut)
954 tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
955 tagLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
956 tagLabel.addMouseListener(new MouseAdapter() {
957 @Override
958 public void mouseClicked(MouseEvent e) {
959 action.actionPerformed(null);
960 if (SwingUtilities.isRightMouseButton(e)) {
961 new TagPopupMenu(t).show(e.getComponent(), e.getX(), e.getY());
962 } else if (e.isShiftDown()) {
963 // add tags on Shift-Click
964 performTagAdding();
965 refreshRecentTags();
966 selectKeysComboBox();
967 } else if (e.getClickCount() > 1) {
968 // add tags and close window on double-click
969 buttonAction(0, null); // emulate OK click and close the dialog
970 }
971 }
972 });
973 } else {
974 // Disable tag label
975 tagLabel.setEnabled(false);
976 // Explain in the tooltip why
977 tagLabel.setToolTipText(tr("The key ''{0}'' is already used", t.getKey()));
978 }
979 // Finally add label to the resulting panel
980 JPanel tagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
981 tagPanel.add(tagLabel);
982 recentTagsPanel.add(tagPanel, GBC.eol().fill(GBC.HORIZONTAL));
983 }
984 // Clear label if no tags were added
985 if (count == 0) {
986 recentTagsPanel.removeAll();
987 }
988 }
989
990 class TagPopupMenu extends JPopupMenu {
991
992 TagPopupMenu(Tag t) {
993 add(new IgnoreTagAction(tr("Ignore key ''{0}''", t.getKey()), new Tag(t.getKey(), "")));
994 add(new IgnoreTagAction(tr("Ignore tag ''{0}''", t), t));
995 add(new EditIgnoreTagsAction());
996 }
997 }
998
999 class IgnoreTagAction extends AbstractAction {
1000 final transient Tag tag;
1001
1002 IgnoreTagAction(String name, Tag tag) {
1003 super(name);
1004 this.tag = tag;
1005 }
1006
1007 @Override
1008 public void actionPerformed(ActionEvent e) {
1009 try {
1010 if (tagsToIgnore != null) {
1011 recentTags.ignoreTag(tag, tagsToIgnore);
1012 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString());
1013 }
1014 } catch (SearchCompiler.ParseError parseError) {
1015 throw new IllegalStateException(parseError);
1016 }
1017 }
1018 }
1019
1020 class EditIgnoreTagsAction extends AbstractAction {
1021
1022 EditIgnoreTagsAction() {
1023 super(tr("Edit ignore list"));
1024 }
1025
1026 @Override
1027 public void actionPerformed(ActionEvent e) {
1028 final SearchAction.SearchSetting newTagsToIngore = SearchAction.showSearchDialog(tagsToIgnore);
1029 if (newTagsToIngore == null) {
1030 return;
1031 }
1032 try {
1033 tagsToIgnore = newTagsToIngore;
1034 recentTags.setTagsToIgnore(tagsToIgnore);
1035 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString());
1036 } catch (SearchCompiler.ParseError parseError) {
1037 warnAboutParseError(parseError);
1038 }
1039 }
1040 }
1041
1042 /**
1043 * Destroy the recentTagsActions.
1044 */
1045 public void destroyActions() {
1046 for (JosmAction action : recentTagsActions) {
1047 action.destroy();
1048 }
1049 recentTagsActions.clear();
1050 }
1051
1052 /**
1053 * Read tags from comboboxes and add it to all selected objects
1054 */
1055 public final void performTagAdding() {
1056 String key = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
1057 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
1058 if (key.isEmpty() || value.isEmpty())
1059 return;
1060 for (OsmPrimitive osm : sel) {
1061 String val = osm.get(key);
1062 if (val != null && !val.equals(value)) {
1063 if (!warnOverwriteKey(tr("You changed the value of ''{0}'' from ''{1}'' to ''{2}''.", key, val, value),
1064 "overwriteAddKey"))
1065 return;
1066 break;
1067 }
1068 }
1069 recentTags.add(new Tag(key, value));
1070 valueCount.put(key, new TreeMap<String, Integer>());
1071 AutoCompletionManager.rememberUserInput(key, value, false);
1072 commandCount++;
1073 Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, value));
1074 changedKey = key;
1075 clearEntries();
1076 }
1077
1078 protected void clearEntries() {
1079 keys.getEditor().setItem("");
1080 values.getEditor().setItem("");
1081 }
1082
1083 public void undoAllTagsAdding() {
1084 Main.main.undoRedo.undo(commandCount);
1085 }
1086
1087 private void refreshRecentTags() {
1088 switch (PROPERTY_REFRESH_RECENT.get()) {
1089 case REFRESH:
1090 cacheRecentTags();
1091 suggestRecentlyAddedTags();
1092 break;
1093 case STATUS:
1094 suggestRecentlyAddedTags();
1095 break;
1096 default: // Do nothing
1097 }
1098 }
1099 }
1100}
Note: See TracBrowser for help on using the repository browser.