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