package org.simantics.district.network.ui.contributions; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.inject.Named; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.e4.core.di.annotations.CanExecute; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.dialogs.SelectionStatusDialog; import org.eclipse.ui.progress.UIJob; import org.simantics.DatabaseJob; import org.simantics.Simantics; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; import org.simantics.db.common.NamedResource; import org.simantics.db.common.request.IndexRoot; import org.simantics.db.common.request.ReadRequest; import org.simantics.db.common.request.UniqueRead; import org.simantics.db.common.request.WriteRequest; import org.simantics.db.common.utils.NameUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.db.exception.ServiceException; import org.simantics.db.exception.ValidationException; import org.simantics.db.layer0.SelectionHints; import org.simantics.db.procedure.Procedure; import org.simantics.db.request.Read; import org.simantics.district.network.DistrictNetworkUtil; import org.simantics.district.network.ontology.DistrictNetworkResource; import org.simantics.district.network.ui.function.Functions; import org.simantics.district.network.ui.internal.Activator; import org.simantics.utils.ui.ISelectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChangeMappingTypeHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ChangeMappingTypeHandler.class); @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) ISelection selection) { List elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class); if (elements.size() < 1) return false; try { return Simantics.getSession().syncRequest(new Read() { @Override public Boolean perform(ReadGraph graph) throws DatabaseException { DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph); for (Resource selection : elements) { if (!graph.isInstanceOf(selection, DN.Element)) { return false; } } return true; } }); } catch (DatabaseException e) { LOGGER.error("Could not evaluate if mapping can be changed for selection {}", elements, e); return false; } } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) Object selection) { final List elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class); // if (elements.size() < 1) // return; CompletableFuture>> result = new CompletableFuture<>(); Simantics.getSession().asyncRequest(new UniqueRead>>() { @Override public Map> perform(ReadGraph graph) throws DatabaseException { DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph); Map> currents = new HashMap<>(); for (Resource element : elements) { Resource currentMapping = graph.getPossibleObject(element, DN.HasMapping); NamedResource mapping = new NamedResource(NameUtils.getSafeName(graph, currentMapping), currentMapping); currents.compute(mapping, (t, u) -> { if (u == null) u = new HashSet<>(); try { u.add(new NamedResource(NameUtils.getSafeName(graph, element), element)); } catch (ValidationException | ServiceException e) { LOGGER.error("Could not compute name for {}", element, e); } return u; }); } return currents; } }, new Procedure>>() { @Override public void execute(Map> results) { result.complete(results); } @Override public void exception(Throwable t) { LOGGER.error("Could not compute mappings for selection {}", elements, t); result.completeExceptionally(t); } }); UIJob uiJob = new UIJob("Change mappings..") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { SelectMappingDialog dialog = new SelectMappingDialog(getDisplay().getActiveShell(), result); if (dialog.open() != Dialog.OK) return Status.OK_STATUS; Map> results = dialog.getResults(); Job job = new DatabaseJob("Join selected vertices") { @Override protected IStatus run(IProgressMonitor monitor) { try { Simantics.getSession().syncRequest(new WriteRequest() { @Override public void perform(WriteGraph graph) throws DatabaseException { for (Map.Entry> entry : results.entrySet()) { List elements = entry.getValue().stream() .map(NamedResource::getResource) .collect(Collectors.toList()); DistrictNetworkUtil.changeMappingType(graph, entry.getKey(), elements); } } }); } catch (DatabaseException e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, getName() + " failed.", e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return Status.OK_STATUS; } }; uiJob.setUser(true); uiJob.schedule(); } private static class SelectMappingDialog extends SelectionStatusDialog { private Map mappingCombos = new HashMap<>(); private Composite composite; private CompletableFuture>> elements; private Map> possibleMappings = new HashMap<>(); protected SelectMappingDialog(Shell parentShell, CompletableFuture>> elements) { super(parentShell); this.elements = elements; setTitle("Change mappings"); } @Override protected Control createDialogArea(Composite parent) { composite = (Composite) super.createDialogArea(parent); createMappingsGroup(composite); // compute default values Simantics.getSession().asyncRequest(new ReadRequest() { @Override public void run(ReadGraph graph) throws DatabaseException { DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph); try { for (Map.Entry> entry : elements.get().entrySet()) { NamedResource currentMapping = entry.getKey(); Resource resource = entry.getValue().iterator().next().getResource(); Resource indexRoot = graph.sync(new IndexRoot(resource)); if (graph.isInstanceOf(currentMapping.getResource(), DN.Mapping_VertexMapping)) { possibleMappings.put(currentMapping, Functions.getVertexMappings(graph, indexRoot)); } else if (graph.isInstanceOf(currentMapping.getResource(), DN.Mapping_EdgeMapping)) { possibleMappings.put(currentMapping, Functions.getEdgeMappings(graph, indexRoot)); } } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } composite.getDisplay().asyncExec(() -> { for (Map.Entry> entry : possibleMappings.entrySet()) { NamedResource key = entry.getKey(); Map value = entry.getValue(); Combo combo = mappingCombos.get(key); combo.setItems(value.keySet().toArray(new String[value.size()])); combo.select(0); } }); } }); return composite; } private Map> results = new HashMap<>(); @Override protected void computeResult() { Map> currentElements = null; try { currentElements = elements.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error("Could not get currentElements", e); throw new RuntimeException("Could not get currentElements", e); } for (Map.Entry combos : mappingCombos.entrySet()) { NamedResource resource = combos.getKey(); Combo c = combos.getValue(); String item = c.getItem(c.getSelectionIndex()); Collection collection = currentElements.get(resource); Map map = possibleMappings.get(resource); Resource newMapping = map.get(item); results.compute(newMapping, (t, u) -> { if (u == null) { u = new HashSet<>(); } u.addAll(collection); return u; }); } } public Map> getResults() { return results; } private void createMappingsGroup(Composite parent) { try { for (Map.Entry> entry : elements.get().entrySet()) { NamedResource currentMapping = entry.getKey(); Collection mappedElements = entry.getValue(); Group group= new Group(parent, SWT.NONE); group.setFont(parent.getFont()); group.setText(currentMapping.getName() + " currently mapped to " + mappedElements.size() + " elements"); GridDataFactory.fillDefaults().grab(true, false).applyTo(group); group.setLayout(new GridLayout(1, false)); Composite cmposite = new Composite(group, SWT.NONE); cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); cmposite.setLayout(new GridLayout(2, false)); Label vertexMappingLabel = new Label(cmposite, SWT.NONE); vertexMappingLabel.setText("New mapping type"); Combo c = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(c); mappingCombos.put(entry.getKey(), c); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } }