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

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

sonar - pmd:UseVarargs - Use Varargs

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