001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.actions; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.event.ActionEvent; 007import java.awt.event.KeyEvent; 008import java.util.Collection; 009import java.util.Collections; 010import java.util.stream.Collectors; 011 012import org.openstreetmap.josm.data.notes.Note; 013import org.openstreetmap.josm.data.osm.DataSet; 014import org.openstreetmap.josm.data.osm.OsmPrimitive; 015import org.openstreetmap.josm.data.osm.OsmPrimitiveType; 016import org.openstreetmap.josm.gui.MainApplication; 017import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils; 018import org.openstreetmap.josm.spi.preferences.Config; 019import org.openstreetmap.josm.tools.Shortcut; 020 021/** 022 * User action to copy the URL of one or several object(s) to the clipboard. 023 * @since 17767 024 */ 025public class CopyUrlAction extends JosmAction { 026 027 /** 028 * Constructs a new {@code CopyCoordinatesAction}. 029 */ 030 public CopyUrlAction() { 031 super(tr("Copy server URLs"), "copy", 032 tr("Copy server URLs of selected objects to clipboard."), 033 Shortcut.registerShortcut("copy:urls", tr("Edit: {0}", tr("Copy server URLs")), 034 KeyEvent.CHAR_UNDEFINED, Shortcut.NONE), 035 false, "copy/urls", true); 036 } 037 038 @Override 039 public void actionPerformed(ActionEvent ae) { 040 final String base = Config.getUrls().getBaseBrowseUrl() + '/'; 041 String string = getSelected().stream() 042 .filter(p -> !p.isNew()) 043 .map(p -> base + OsmPrimitiveType.from(p).getAPIName() + '/' + p.getOsmId()) 044 .collect(Collectors.joining("\n")); 045 Note note = getNote(); 046 if (note != null && note.getId() > 0) { 047 string = string + "\n" + base + "/note/" + note.getId(); 048 } 049 ClipboardUtils.copyString(string); 050 } 051 052 @Override 053 protected void updateEnabledState() { 054 Note note = getNote(); 055 setEnabled((note != null && note.getId() > 0) || !getSelected().stream().allMatch(OsmPrimitive::isNew)); 056 } 057 058 @Override 059 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) { 060 updateEnabledState(); 061 } 062 063 private static Note getNote() { 064 return MainApplication.isDisplayingMapView() ? MainApplication.getMap().noteDialog.getSelectedNote() : null; 065 } 066 067 private Collection<OsmPrimitive> getSelected() { 068 DataSet ds = getLayerManager().getActiveDataSet(); 069 if (ds == null) { 070 return Collections.emptyList(); 071 } else { 072 return ds.getAllSelected(); 073 } 074 } 075}