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

Last change on this file since 6939 was 6890, checked in by Don-vip, 10 years ago

fix some Sonar issues (Constructor Calls Overridable Method)

File size: 34.4 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.Cursor;
10import java.awt.Dimension;
11import java.awt.FlowLayout;
12import java.awt.Font;
13import java.awt.GridBagConstraints;
14import java.awt.GridBagLayout;
15import java.awt.Toolkit;
16import java.awt.datatransfer.Clipboard;
17import java.awt.datatransfer.Transferable;
18import java.awt.event.ActionEvent;
19import java.awt.event.ActionListener;
20import java.awt.event.FocusAdapter;
21import java.awt.event.FocusEvent;
22import java.awt.event.InputEvent;
23import java.awt.event.KeyEvent;
24import java.awt.event.MouseAdapter;
25import java.awt.event.MouseEvent;
26import java.awt.event.WindowAdapter;
27import java.awt.event.WindowEvent;
28import java.awt.image.BufferedImage;
29import java.text.Normalizer;
30import java.util.ArrayList;
31import java.util.Arrays;
32import java.util.Collection;
33import java.util.Collections;
34import java.util.Comparator;
35import java.util.HashMap;
36import java.util.Iterator;
37import java.util.LinkedHashMap;
38import java.util.LinkedList;
39import java.util.List;
40import java.util.Map;
41
42import javax.swing.AbstractAction;
43import javax.swing.Action;
44import javax.swing.Box;
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.JOptionPane;
52import javax.swing.JPanel;
53import javax.swing.JPopupMenu;
54import javax.swing.KeyStroke;
55import javax.swing.table.DefaultTableModel;
56import javax.swing.text.JTextComponent;
57
58import org.openstreetmap.josm.Main;
59import org.openstreetmap.josm.actions.JosmAction;
60import org.openstreetmap.josm.command.ChangePropertyCommand;
61import org.openstreetmap.josm.command.Command;
62import org.openstreetmap.josm.command.SequenceCommand;
63import org.openstreetmap.josm.data.osm.OsmPrimitive;
64import org.openstreetmap.josm.data.osm.Tag;
65import org.openstreetmap.josm.data.preferences.BooleanProperty;
66import org.openstreetmap.josm.data.preferences.IntegerProperty;
67import org.openstreetmap.josm.gui.ExtendedDialog;
68import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
69import org.openstreetmap.josm.gui.tagging.TaggingPreset;
70import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingComboBox;
71import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionListItem;
72import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
73import org.openstreetmap.josm.gui.util.GuiHelper;
74import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
75import org.openstreetmap.josm.io.XmlWriter;
76import org.openstreetmap.josm.tools.GBC;
77import org.openstreetmap.josm.tools.Shortcut;
78import org.openstreetmap.josm.tools.WindowGeometry;
79
80/**
81 * Class that helps PropertiesDialog add and edit tag values
82 */
83 class TagEditHelper {
84 private final DefaultTableModel tagData;
85 private final Map<String, Map<String, Integer>> valueCount;
86
87 // Selection that we are editing by using both dialogs
88 Collection<OsmPrimitive> sel;
89
90 private String changedKey;
91 private String objKey;
92
93 Comparator<AutoCompletionListItem> defaultACItemComparator = new Comparator<AutoCompletionListItem>() {
94 @Override
95 public int compare(AutoCompletionListItem o1, AutoCompletionListItem o2) {
96 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
97 }
98 };
99
100 private String lastAddKey = null;
101 private String lastAddValue = null;
102
103 public static final int DEFAULT_LRU_TAGS_NUMBER = 5;
104 public static final int MAX_LRU_TAGS_NUMBER = 30;
105
106 // LRU cache for recently added tags (http://java-planet.blogspot.com/2005/08/how-to-set-up-simple-lru-cache-using.html)
107 private final Map<Tag, Void> recentTags = new LinkedHashMap<Tag, Void>(MAX_LRU_TAGS_NUMBER+1, 1.1f, true) {
108 @Override
109 protected boolean removeEldestEntry(Map.Entry<Tag, Void> eldest) {
110 return size() > MAX_LRU_TAGS_NUMBER;
111 }
112 };
113
114 TagEditHelper(DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
115 this.tagData = propertyData;
116 this.valueCount = valueCount;
117 }
118
119 /**
120 * Open the add selection dialog and add a new key/value to the table (and
121 * to the dataset, of course).
122 */
123 public void addTag() {
124 changedKey = null;
125 sel = Main.main.getInProgressSelection();
126 if (sel == null || sel.isEmpty()) return;
127
128 final AddTagsDialog addDialog = new AddTagsDialog();
129
130 addDialog.showDialog();
131
132 addDialog.destroyActions();
133 if (addDialog.getValue() == 1)
134 addDialog.performTagAdding();
135 else
136 addDialog.undoAllTagsAdding();
137 }
138
139 /**
140 * Edit the value in the tags table row
141 * @param row The row of the table from which the value is edited.
142 * @param focusOnKey Determines if the initial focus should be set on key instead of value
143 * @since 5653
144 */
145 public void editTag(final int row, boolean focusOnKey) {
146 changedKey = null;
147 sel = Main.main.getInProgressSelection();
148 if (sel == null || sel.isEmpty()) return;
149
150 String key = tagData.getValueAt(row, 0).toString();
151 objKey=key;
152
153 @SuppressWarnings("unchecked")
154 final EditTagDialog editDialog = new EditTagDialog(key, row,
155 (Map<String, Integer>) tagData.getValueAt(row, 1), focusOnKey);
156 editDialog.showDialog();
157 if (editDialog.getValue() !=1 ) return;
158 editDialog.performTagEdit();
159 }
160
161 /**
162 * If during last editProperty call user changed the key name, this key will be returned
163 * Elsewhere, returns null.
164 */
165 public String getChangedKey() {
166 return changedKey;
167 }
168
169 public void resetChangedKey() {
170 changedKey = null;
171 }
172
173 /**
174 * For a given key k, return a list of keys which are used as keys for
175 * auto-completing values to increase the search space.
176 * @param key the key k
177 * @return a list of keys
178 */
179 private static List<String> getAutocompletionKeys(String key) {
180 if ("name".equals(key) || "addr:street".equals(key))
181 return Arrays.asList("addr:street", "name");
182 else
183 return Arrays.asList(key);
184 }
185
186 /**
187 * Load recently used tags from preferences if needed
188 */
189 public void loadTagsIfNeeded() {
190 if (PROPERTY_REMEMBER_TAGS.get() && recentTags.isEmpty()) {
191 recentTags.clear();
192 Collection<String> c = Main.pref.getCollection("properties.recent-tags");
193 Iterator<String> it = c.iterator();
194 String key, value;
195 while (it.hasNext()) {
196 key = it.next();
197 value = it.next();
198 recentTags.put(new Tag(key, value), null);
199 }
200 }
201 }
202
203 /**
204 * Store recently used tags in preferences if needed
205 */
206 public void saveTagsIfNeeded() {
207 if (PROPERTY_REMEMBER_TAGS.get() && !recentTags.isEmpty()) {
208 List<String> c = new ArrayList<String>( recentTags.size()*2 );
209 for (Tag t: recentTags.keySet()) {
210 c.add(t.getKey());
211 c.add(t.getValue());
212 }
213 Main.pref.putCollection("properties.recent-tags", c);
214 }
215 }
216
217 public final class EditTagDialog extends AbstractTagsDialog {
218 final String key;
219 final Map<String, Integer> m;
220 final int row;
221
222 Comparator<AutoCompletionListItem> usedValuesAwareComparator = new Comparator<AutoCompletionListItem>() {
223 @Override
224 public int compare(AutoCompletionListItem o1, AutoCompletionListItem o2) {
225 boolean c1 = m.containsKey(o1.getValue());
226 boolean c2 = m.containsKey(o2.getValue());
227 if (c1 == c2)
228 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
229 else if (c1)
230 return -1;
231 else
232 return +1;
233 }
234 };
235
236 DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() {
237 @Override public Component getListCellRendererComponent(JList list,
238 Object value, int index, boolean isSelected, boolean cellHasFocus){
239 Component c = super.getListCellRendererComponent(list, value,
240 index, isSelected, cellHasFocus);
241 if (c instanceof JLabel) {
242 String str = ((AutoCompletionListItem) value).getValue();
243 if (valueCount.containsKey(objKey)) {
244 Map<String, Integer> m = valueCount.get(objKey);
245 if (m.containsKey(str)) {
246 str = tr("{0} ({1})", str, m.get(str));
247 c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD));
248 }
249 }
250 ((JLabel) c).setText(str);
251 }
252 return c;
253 }
254 };
255
256 private EditTagDialog(String key, int row, Map<String, Integer> map, final boolean initialFocusOnKey) {
257 super(Main.parent, trn("Change value?", "Change values?", map.size()), new String[] {tr("OK"),tr("Cancel")});
258 setButtonIcons(new String[] {"ok","cancel"});
259 setCancelButton(2);
260 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);
261 this.key = key;
262 this.row = row;
263 this.m = map;
264
265 JPanel mainPanel = new JPanel(new BorderLayout());
266
267 String msg = "<html>"+trn("This will change {0} object.",
268 "This will change up to {0} objects.", sel.size(), sel.size())
269 +"<br><br>("+tr("An empty value deletes the tag.", key)+")</html>";
270
271 mainPanel.add(new JLabel(msg), BorderLayout.NORTH);
272
273 JPanel p = new JPanel(new GridBagLayout());
274 mainPanel.add(p, BorderLayout.CENTER);
275
276 AutoCompletionManager autocomplete = Main.main.getEditLayer().data.getAutoCompletionManager();
277 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
278 Collections.sort(keyList, defaultACItemComparator);
279
280 keys = new AutoCompletingComboBox(key);
281 keys.setPossibleACItems(keyList);
282 keys.setEditable(true);
283 keys.setSelectedItem(key);
284
285 p.add(Box.createVerticalStrut(5),GBC.eol());
286 p.add(new JLabel(tr("Key")), GBC.std());
287 p.add(Box.createHorizontalStrut(10), GBC.std());
288 p.add(keys, GBC.eol().fill(GBC.HORIZONTAL));
289
290 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
291 Collections.sort(valueList, usedValuesAwareComparator);
292
293 final String selection= m.size()!=1?tr("<different>"):m.entrySet().iterator().next().getKey();
294
295 values = new AutoCompletingComboBox(selection);
296 values.setRenderer(cellRenderer);
297
298 values.setEditable(true);
299 values.setPossibleACItems(valueList);
300 values.setSelectedItem(selection);
301 values.getEditor().setItem(selection);
302 p.add(Box.createVerticalStrut(5),GBC.eol());
303 p.add(new JLabel(tr("Value")), GBC.std());
304 p.add(Box.createHorizontalStrut(10), GBC.std());
305 p.add(values, GBC.eol().fill(GBC.HORIZONTAL));
306 values.getEditor().addActionListener(new ActionListener() {
307 @Override
308 public void actionPerformed(ActionEvent e) {
309 buttonAction(0, null); // emulate OK button click
310 }
311 });
312 addFocusAdapter(autocomplete, usedValuesAwareComparator);
313
314 setContent(mainPanel, false);
315
316 addWindowListener(new WindowAdapter() {
317 @Override
318 public void windowOpened(WindowEvent e) {
319 if (initialFocusOnKey) {
320 selectKeysComboBox();
321 } else {
322 selectValuesCombobox();
323 }
324 }
325 });
326 }
327
328 /**
329 * Edit tags of multiple selected objects according to selected ComboBox values
330 * If value == "", tag will be deleted
331 * Confirmations may be needed.
332 */
333 private void performTagEdit() {
334 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
335 value = Normalizer.normalize(value, java.text.Normalizer.Form.NFC);
336 if (value.isEmpty()) {
337 value = null; // delete the key
338 }
339 String newkey = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
340 newkey = Normalizer.normalize(newkey, java.text.Normalizer.Form.NFC);
341 if (newkey.isEmpty()) {
342 newkey = key;
343 value = null; // delete the key instead
344 }
345 if (key.equals(newkey) && tr("<different>").equals(value))
346 return;
347 if (key.equals(newkey) || value == null) {
348 Main.main.undoRedo.add(new ChangePropertyCommand(sel, newkey, value));
349 } else {
350 for (OsmPrimitive osm: sel) {
351 if(osm.get(newkey) != null) {
352 ExtendedDialog ed = new ExtendedDialog(
353 Main.parent,
354 tr("Overwrite key"),
355 new String[]{tr("Replace"), tr("Cancel")});
356 ed.setButtonIcons(new String[]{"purge", "cancel"});
357 ed.setContent(tr("You changed the key from ''{0}'' to ''{1}''.\n"
358 + "The new key is already used, overwrite values?", key, newkey));
359 ed.setCancelButton(2);
360 ed.toggleEnable("overwriteEditKey");
361 ed.showDialog();
362
363 if (ed.getValue() != 1)
364 return;
365 break;
366 }
367 }
368 Collection<Command> commands = new ArrayList<Command>();
369 commands.add(new ChangePropertyCommand(sel, key, null));
370 if (value.equals(tr("<different>"))) {
371 Map<String, List<OsmPrimitive>> map = new HashMap<String, List<OsmPrimitive>>();
372 for (OsmPrimitive osm: sel) {
373 String val = osm.get(key);
374 if (val != null) {
375 if (map.containsKey(val)) {
376 map.get(val).add(osm);
377 } else {
378 List<OsmPrimitive> v = new ArrayList<OsmPrimitive>();
379 v.add(osm);
380 map.put(val, v);
381 }
382 }
383 }
384 for (Map.Entry<String, List<OsmPrimitive>> e: map.entrySet()) {
385 commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey()));
386 }
387 } else {
388 commands.add(new ChangePropertyCommand(sel, newkey, value));
389 }
390 Main.main.undoRedo.add(new SequenceCommand(
391 trn("Change properties of up to {0} object",
392 "Change properties of up to {0} objects", sel.size(), sel.size()),
393 commands));
394 }
395
396 changedKey = newkey;
397 }
398 }
399
400 public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE = new BooleanProperty("properties.fix-tag-combobox-locale", false);
401 public static final BooleanProperty PROPERTY_REMEMBER_TAGS = new BooleanProperty("properties.remember-recently-added-tags", false);
402 public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER = new IntegerProperty("properties.recently-added-tags", DEFAULT_LRU_TAGS_NUMBER);
403
404 abstract class AbstractTagsDialog extends ExtendedDialog {
405 AutoCompletingComboBox keys;
406 AutoCompletingComboBox values;
407 Component componentUnderMouse;
408
409 public AbstractTagsDialog(Component parent, String title, String[] buttonTexts) {
410 super(parent, title, buttonTexts);
411 addMouseListener(new PopupMenuLauncher(popupMenu));
412 }
413
414 @Override
415 public void setupDialog() {
416 super.setupDialog();
417 final Dimension size = getSize();
418 // Set resizable only in width
419 setMinimumSize(size);
420 setPreferredSize(size);
421 // setMaximumSize does not work, and never worked, but still it seems not to bother Oracle to fix this 10-year-old bug
422 // https://bugs.openjdk.java.net/browse/JDK-6200438
423 // https://bugs.openjdk.java.net/browse/JDK-6464548
424
425 setRememberWindowGeometry(getClass().getName() + ".geometry",
426 WindowGeometry.centerInWindow(Main.parent, size));
427 }
428
429 @Override
430 public void setVisible(boolean visible) {
431 // Do not want dialog to be resizable in height, as its size may increase each time because of the recently added tags
432 // So need to modify the stored geometry (size part only) in order to use the automatic positioning mechanism
433 if (visible) {
434 WindowGeometry geometry = initWindowGeometry();
435 Dimension storedSize = geometry.getSize();
436 Dimension size = getSize();
437 if (!storedSize.equals(size)) {
438 if (storedSize.width < size.width) {
439 storedSize.width = size.width;
440 }
441 if (storedSize.height != size.height) {
442 storedSize.height = size.height;
443 }
444 rememberWindowGeometry(geometry);
445 }
446 keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
447 }
448 super.setVisible(visible);
449 }
450
451 private void selectACComboBoxSavingUnixBuffer(AutoCompletingComboBox cb) {
452 // select compbobox with saving unix system selection (middle mouse paste)
453 Clipboard sysSel = Toolkit.getDefaultToolkit().getSystemSelection();
454 if(sysSel != null) {
455 Transferable old = sysSel.getContents(null);
456 cb.requestFocusInWindow();
457 cb.getEditor().selectAll();
458 sysSel.setContents(old, null);
459 } else {
460 cb.requestFocusInWindow();
461 cb.getEditor().selectAll();
462 }
463 }
464
465 public void selectKeysComboBox() {
466 selectACComboBoxSavingUnixBuffer(keys);
467 }
468
469 public void selectValuesCombobox() {
470 selectACComboBoxSavingUnixBuffer(values);
471 }
472
473 /**
474 * Create a focus handling adapter and apply in to the editor component of value
475 * autocompletion box.
476 * @param autocomplete Manager handling the autocompletion
477 * @param comparator Class to decide what values are offered on autocompletion
478 * @return The created adapter
479 */
480 protected FocusAdapter addFocusAdapter(final AutoCompletionManager autocomplete, final Comparator<AutoCompletionListItem> comparator) {
481 // get the combo box' editor component
482 JTextComponent editor = (JTextComponent)values.getEditor()
483 .getEditorComponent();
484 // Refresh the values model when focus is gained
485 FocusAdapter focus = new FocusAdapter() {
486 @Override public void focusGained(FocusEvent e) {
487 String key = keys.getEditor().getItem().toString();
488
489 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
490 Collections.sort(valueList, comparator);
491
492 values.setPossibleACItems(valueList);
493 objKey=key;
494 }
495 };
496 editor.addFocusListener(focus);
497 return focus;
498 }
499
500 protected JPopupMenu popupMenu = new JPopupMenu() {
501 JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem(
502 new AbstractAction(tr("Use English language for tag by default")){
503 @Override
504 public void actionPerformed(ActionEvent e) {
505 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
506 PROPERTY_FIX_TAG_LOCALE.put(sel);
507 }
508 });
509 {
510 add(fixTagLanguageCb);
511 fixTagLanguageCb.setState(PROPERTY_FIX_TAG_LOCALE.get());
512 }
513 };
514 }
515
516 class AddTagsDialog extends AbstractTagsDialog {
517 List<JosmAction> recentTagsActions = new ArrayList<JosmAction>();
518
519 // Counter of added commands for possible undo
520 private int commandCount;
521
522 public AddTagsDialog() {
523 super(Main.parent, tr("Add value?"), new String[] {tr("OK"),tr("Cancel")});
524 setButtonIcons(new String[] {"ok","cancel"});
525 setCancelButton(2);
526 configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */);
527
528 JPanel mainPanel = new JPanel(new GridBagLayout());
529 keys = new AutoCompletingComboBox();
530 values = new AutoCompletingComboBox();
531
532 mainPanel.add(new JLabel("<html>"+trn("This will change up to {0} object.",
533 "This will change up to {0} objects.", sel.size(),sel.size())
534 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL));
535
536 AutoCompletionManager autocomplete = Main.main.getEditLayer().data.getAutoCompletionManager();
537 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
538
539 AutoCompletionListItem itemToSelect = null;
540 // remove the object's tag keys from the list
541 Iterator<AutoCompletionListItem> iter = keyList.iterator();
542 while (iter.hasNext()) {
543 AutoCompletionListItem item = iter.next();
544 if (item.getValue().equals(lastAddKey)) {
545 itemToSelect = item;
546 }
547 for (int i = 0; i < tagData.getRowCount(); ++i) {
548 if (item.getValue().equals(tagData.getValueAt(i, 0))) {
549 if (itemToSelect == item) {
550 itemToSelect = null;
551 }
552 iter.remove();
553 break;
554 }
555 }
556 }
557
558 Collections.sort(keyList, defaultACItemComparator);
559 keys.setPossibleACItems(keyList);
560 keys.setEditable(true);
561
562 mainPanel.add(keys, GBC.eop().fill());
563
564 mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol());
565 values.setEditable(true);
566 mainPanel.add(values, GBC.eop().fill());
567 if (itemToSelect != null) {
568 keys.setSelectedItem(itemToSelect);
569 if (lastAddValue != null) {
570 values.setSelectedItem(lastAddValue);
571 }
572 }
573
574 FocusAdapter focus = addFocusAdapter(autocomplete, defaultACItemComparator);
575 // fire focus event in advance or otherwise the popup list will be too small at first
576 focus.focusGained(null);
577
578 int recentTagsToShow = PROPERTY_RECENT_TAGS_NUMBER.get();
579 if (recentTagsToShow > MAX_LRU_TAGS_NUMBER) {
580 recentTagsToShow = MAX_LRU_TAGS_NUMBER;
581 }
582
583 // Add tag on Shift-Enter
584 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
585 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK), "addAndContinue");
586 mainPanel.getActionMap().put("addAndContinue", new AbstractAction() {
587 @Override
588 public void actionPerformed(ActionEvent e) {
589 performTagAdding();
590 selectKeysComboBox();
591 }
592 });
593
594 suggestRecentlyAddedTags(mainPanel, recentTagsToShow, focus);
595
596 setContent(mainPanel, false);
597
598 selectKeysComboBox();
599
600 popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) {
601 @Override
602 public void actionPerformed(ActionEvent e) {
603 selectNumberOfTags();
604 }
605 });
606 JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem(
607 new AbstractAction(tr("Remember last used tags")){
608 @Override
609 public void actionPerformed(ActionEvent e) {
610 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
611 PROPERTY_REMEMBER_TAGS.put(sel);
612 if (sel) saveTagsIfNeeded();
613 }
614 });
615 rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get());
616 popupMenu.add(rememberLastTags);
617 }
618
619 private void selectNumberOfTags() {
620 String s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"));
621 if (s!=null) try {
622 int v = Integer.parseInt(s);
623 if (v>=0 && v<=MAX_LRU_TAGS_NUMBER) {
624 PROPERTY_RECENT_TAGS_NUMBER.put(v);
625 return;
626 }
627 } catch (NumberFormatException ex) {
628 Main.warn(ex);
629 }
630 JOptionPane.showMessageDialog(this, tr("Please enter integer number between 0 and {0}", MAX_LRU_TAGS_NUMBER));
631 }
632
633 private void suggestRecentlyAddedTags(JPanel mainPanel, int tagsToShow, final FocusAdapter focus) {
634 if (!(tagsToShow > 0 && !recentTags.isEmpty()))
635 return;
636
637 mainPanel.add(new JLabel(tr("Recently added tags")), GBC.eol());
638
639 int count = 1;
640 // We store the maximum number (9) of recent tags to allow dynamic change of number of tags shown in the preferences.
641 // This implies to iterate in descending order, as the oldest elements will only be removed after we reach the maximum numbern and not the number of tags to show.
642 // However, as Set does not allow to iterate in descending order, we need to copy its elements into a List we can access in reverse order.
643 List<Tag> tags = new LinkedList<Tag>(recentTags.keySet());
644 for (int i = tags.size()-1; i >= 0 && count <= tagsToShow; i--, count++) {
645 final Tag t = tags.get(i);
646 // Create action for reusing the tag, with keyboard shortcut Ctrl+(1-5)
647 String actionShortcutKey = "properties:recent:"+count;
648 String actionShortcutShiftKey = "properties:recent:shift:"+count;
649 Shortcut sc = Shortcut.registerShortcut(actionShortcutKey, tr("Choose recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL);
650 final JosmAction action = new JosmAction(actionShortcutKey, null, tr("Use this tag again"), sc, false) {
651 @Override
652 public void actionPerformed(ActionEvent e) {
653 keys.setSelectedItem(t.getKey());
654 // Update list of values (fix #7951)
655 // fix #8298 - update list of values before setting value (?)
656 focus.focusGained(null);
657 values.setSelectedItem(t.getValue());
658 selectValuesCombobox();
659 }
660 };
661 Shortcut scShift = Shortcut.registerShortcut(actionShortcutShiftKey, tr("Apply recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL_SHIFT);
662 final JosmAction actionShift = new JosmAction(actionShortcutShiftKey, null, tr("Use this tag again"), scShift, false) {
663 @Override
664 public void actionPerformed(ActionEvent e) {
665 action.actionPerformed(null);
666 performTagAdding();
667 selectKeysComboBox();
668 }
669 };
670 recentTagsActions.add(action);
671 recentTagsActions.add(actionShift);
672 disableTagIfNeeded(t, action);
673 // Find and display icon
674 ImageIcon icon = MapPaintStyles.getNodeIcon(t, false); // Filters deprecated icon
675 if (icon == null) {
676 // If no icon found in map style look at presets
677 Map<String, String> map = new HashMap<String, String>();
678 map.put(t.getKey(), t.getValue());
679 for (TaggingPreset tp : TaggingPreset.getMatchingPresets(null, map, false)) {
680 icon = tp.getIcon();
681 if (icon != null) {
682 break;
683 }
684 }
685 // If still nothing display an empty icon
686 if (icon == null) {
687 icon = new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB));
688 }
689 }
690 GridBagConstraints gbc = new GridBagConstraints();
691 gbc.ipadx = 5;
692 mainPanel.add(new JLabel(action.isEnabled() ? icon : GuiHelper.getDisabledIcon(icon)), gbc);
693 // Create tag label
694 final String color = action.isEnabled() ? "" : "; color:gray";
695 final JLabel tagLabel = new JLabel("<html>"
696 + "<style>td{border:1px solid gray; font-weight:normal"+color+"}</style>"
697 + "<table><tr><td>" + XmlWriter.encode(t.toString(), true) + "</td></tr></table></html>");
698 if (action.isEnabled()) {
699 // Register action
700 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), actionShortcutKey);
701 mainPanel.getActionMap().put(actionShortcutKey, action);
702 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), actionShortcutShiftKey);
703 mainPanel.getActionMap().put(actionShortcutShiftKey, actionShift);
704 // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut)
705 tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
706 tagLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
707 tagLabel.addMouseListener(new MouseAdapter() {
708 @Override
709 public void mouseClicked(MouseEvent e) {
710 action.actionPerformed(null);
711 // add tags and close window on double-click
712 if (e.getClickCount()>1) {
713 buttonAction(0, null); // emulate OK click and close the dialog
714 }
715 // add tags on Shift-Click
716 if (e.isShiftDown()) {
717 performTagAdding();
718 selectKeysComboBox();
719 }
720 }
721 });
722 } else {
723 // Disable tag label
724 tagLabel.setEnabled(false);
725 // Explain in the tooltip why
726 tagLabel.setToolTipText(tr("The key ''{0}'' is already used", t.getKey()));
727 }
728 // Finally add label to the resulting panel
729 JPanel tagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
730 tagPanel.add(tagLabel);
731 mainPanel.add(tagPanel, GBC.eol().fill(GBC.HORIZONTAL));
732 }
733 }
734
735 public void destroyActions() {
736 for (JosmAction action : recentTagsActions) {
737 action.destroy();
738 }
739 }
740
741 /**
742 * Read tags from comboboxes and add it to all selected objects
743 */
744 public final void performTagAdding() {
745 String key = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
746 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
747 if (key.isEmpty() || value.isEmpty()) return;
748 lastAddKey = key;
749 lastAddValue = value;
750 recentTags.put(new Tag(key, value), null);
751 commandCount++;
752 Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, value));
753 changedKey = key;
754 }
755
756 public void undoAllTagsAdding() {
757 Main.main.undoRedo.undo(commandCount);
758 }
759
760 private void disableTagIfNeeded(final Tag t, final JosmAction action) {
761 // Disable action if its key is already set on the object (the key being absent from the keys list for this reason
762 // performing this action leads to autocomplete to the next key (see #7671 comments)
763 for (int j = 0; j < tagData.getRowCount(); ++j) {
764 if (t.getKey().equals(tagData.getValueAt(j, 0))) {
765 action.setEnabled(false);
766 break;
767 }
768 }
769 }
770 }
771 }
Note: See TracBrowser for help on using the repository browser.