001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.actions; 003 004import static org.openstreetmap.josm.gui.help.HelpUtil.ht; 005import static org.openstreetmap.josm.tools.I18n.tr; 006 007import java.awt.event.ActionEvent; 008import java.awt.event.KeyEvent; 009import java.util.Collection; 010import java.util.Collections; 011import java.util.HashSet; 012import java.util.Set; 013 014import org.openstreetmap.josm.data.osm.IPrimitive; 015import org.openstreetmap.josm.data.osm.OsmPrimitive; 016import org.openstreetmap.josm.tools.Shortcut; 017import org.openstreetmap.josm.tools.Utils; 018 019/** 020 * Select child objects (way nodes and relation members) that are shared by all objects in the current selection. 021 * @since 18814 022 */ 023public class SelectSharedChildObjectsAction extends JosmAction { 024 025 /** 026 * Create a new SelectSharedChildObjectsAction 027 */ 028 public SelectSharedChildObjectsAction() { 029 super(tr("Select shared child objects"), 030 "select_shared_children", 031 tr("Select child objects (way nodes and relation members) that are shared by all objects in the current selection"), 032 Shortcut.registerShortcut("selection:sharedchildobjects", 033 tr("Selection: {0}", tr("Shared Child Objects")), 034 KeyEvent.CHAR_UNDEFINED, Shortcut.NONE), 035 true); 036 setHelpId(ht("/Action/SelectSharedChildObjectsAction")); 037 } 038 039 @Override 040 public void actionPerformed(ActionEvent e) { 041 Collection<? extends IPrimitive> selection = getLayerManager().getActiveData().getSelected(); 042 Set<? extends IPrimitive> shared = getSharedChildren(selection); 043 getLayerManager().getActiveData().setSelected(shared); 044 } 045 046 @Override 047 protected void updateEnabledState() { 048 updateEnabledStateOnCurrentSelection(true); 049 } 050 051 @Override 052 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) { 053 setEnabled(!Utils.isEmpty(selection)); 054 } 055 056 /** 057 * Get the shared children for a selection 058 * @param selection The selection to get shared children for 059 * @return The shared children 060 */ 061 private static Set<? extends IPrimitive> getSharedChildren(Collection<? extends IPrimitive> selection) { 062 Set<IPrimitive> sharedChildObjects = new HashSet<>(selection.stream() 063 .findAny().map(IPrimitive::getChildren).orElse(Collections.emptyList())); 064 065 for (IPrimitive p : selection) { 066 if (sharedChildObjects.isEmpty()) 067 break; 068 069 sharedChildObjects.retainAll(p.getChildren()); 070 } 071 072 return sharedChildObjects; 073 } 074}