001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.dialogs.properties; 003 004import java.awt.event.ActionEvent; 005import java.util.Collection; 006import java.util.Objects; 007import java.util.Set; 008import java.util.TreeSet; 009import java.util.function.IntFunction; 010import java.util.function.Supplier; 011 012import javax.swing.AbstractAction; 013import javax.swing.JTable; 014 015import org.openstreetmap.josm.data.osm.Tagged; 016import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils; 017import org.openstreetmap.josm.tools.Utils; 018 019/** 020 * Super class of all copy actions from tag table. 021 * @since 13521 022 */ 023public abstract class AbstractCopyAction extends AbstractAction { 024 025 private final JTable tagTable; 026 private final IntFunction<String> keySupplier; 027 private final Supplier<Collection<? extends Tagged>> objectSupplier; 028 029 /** 030 * Constructs a new {@code AbstractCopyAction}. 031 * @param tagTable the tag table 032 * @param keySupplier a supplier which returns the selected key for a given row index 033 * @param objectSupplier a supplier which returns the selected tagged object(s) 034 */ 035 public AbstractCopyAction(JTable tagTable, IntFunction<String> keySupplier, Supplier<Collection<? extends Tagged>> objectSupplier) { 036 this.tagTable = Objects.requireNonNull(tagTable); 037 this.keySupplier = Objects.requireNonNull(keySupplier); 038 this.objectSupplier = Objects.requireNonNull(objectSupplier); 039 } 040 041 protected abstract Collection<String> getString(Tagged p, String key); 042 043 @Override 044 public void actionPerformed(ActionEvent ae) { 045 int[] rows = tagTable.getSelectedRows(); 046 Set<String> values = new TreeSet<>(); 047 Collection<? extends Tagged> sel = objectSupplier.get(); 048 if (rows.length == 0 || sel == null || sel.isEmpty()) return; 049 050 for (int row: rows) { 051 String key = keySupplier.apply(row); 052 for (Tagged p : sel) { 053 Collection<String> s = getString(p, key); 054 if (s != null) { 055 values.addAll(s); 056 } 057 } 058 } 059 if (!values.isEmpty()) { 060 ClipboardUtils.copyString(Utils.join("\n", values)); 061 } 062 } 063}