package org.simantics.district.selection.ui; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.simantics.Simantics; import org.simantics.browsing.ui.common.AdaptableHintContext; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.common.request.ResourceRead; import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.QueryIndexUtils; import org.simantics.db.layer0.SelectionHints; import org.simantics.db.layer0.request.ActiveModels; import org.simantics.db.layer0.variable.Variable; import org.simantics.db.request.Read; import org.simantics.district.selection.ElementSelectionResource; import org.simantics.district.selection.ElementSelector; import org.simantics.layer0.Layer0; import org.simantics.ui.selection.AnyResource; import org.simantics.ui.selection.AnyVariable; import org.simantics.ui.selection.WorkbenchSelectionContentType; public class ElementSelectionTools { public static final class SelectionElement extends AdaptableHintContext { public SelectionElement(Key[] keys) { super(keys); } @SuppressWarnings("unchecked") public T getContent(WorkbenchSelectionContentType contentType) { Resource element = getHint(SelectionHints.KEY_MAIN); if (contentType instanceof AnyResource) { return (T)element; } else if (contentType instanceof AnyVariable) { AnyVariable type = (AnyVariable) contentType; try { return (T) type.processor.syncRequest(new ResourceRead(element) { public Variable perform(ReadGraph graph) throws DatabaseException { return ElementSelector.getVariableForElement(graph, resource); } }); } catch (DatabaseException e) { return null; } } return null; } } public static final class SelectionsRequest implements Read> { @Override public Collection perform(ReadGraph graph) throws DatabaseException { Layer0 L0 = Layer0.getInstance(graph); ElementSelectionResource ES = ElementSelectionResource.getInstance(graph); Resource model = ActiveModels.getPossibleActiveModel(graph, Simantics.getProjectResource()); if (model == null) { return Collections.emptyList(); } List libs = QueryIndexUtils.searchByType(graph, model, ES.SelectionLibrary); if (libs.isEmpty()) return Collections.emptyList(); Resource lib = libs.get(0); List result = new ArrayList<>(); for (Resource selection : graph.getObjects(lib, L0.ConsistsOf)) { if (!graph.isInstanceOf(selection, ES.Selection)) continue; result.add(ElementSelector.getSelector(graph, selection)); } return result; } } }