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