1 package org.simantics.district.network.ui.contributions;
3 import java.util.Collection;
4 import java.util.HashMap;
5 import java.util.HashSet;
8 import java.util.concurrent.CompletableFuture;
9 import java.util.concurrent.ExecutionException;
11 import javax.inject.Named;
13 import org.eclipse.core.runtime.IProgressMonitor;
14 import org.eclipse.core.runtime.IStatus;
15 import org.eclipse.core.runtime.Status;
16 import org.eclipse.core.runtime.jobs.Job;
17 import org.eclipse.e4.core.di.annotations.CanExecute;
18 import org.eclipse.e4.core.di.annotations.Execute;
19 import org.eclipse.e4.ui.services.IServiceConstants;
20 import org.eclipse.jface.dialogs.Dialog;
21 import org.eclipse.jface.layout.GridDataFactory;
22 import org.eclipse.jface.viewers.ISelection;
23 import org.eclipse.swt.SWT;
24 import org.eclipse.swt.layout.GridData;
25 import org.eclipse.swt.layout.GridLayout;
26 import org.eclipse.swt.widgets.Combo;
27 import org.eclipse.swt.widgets.Composite;
28 import org.eclipse.swt.widgets.Control;
29 import org.eclipse.swt.widgets.Group;
30 import org.eclipse.swt.widgets.Label;
31 import org.eclipse.swt.widgets.Shell;
32 import org.eclipse.ui.dialogs.SelectionStatusDialog;
33 import org.eclipse.ui.progress.UIJob;
34 import org.simantics.DatabaseJob;
35 import org.simantics.Simantics;
36 import org.simantics.db.ReadGraph;
37 import org.simantics.db.Resource;
38 import org.simantics.db.WriteGraph;
39 import org.simantics.db.common.NamedResource;
40 import org.simantics.db.common.request.IndexRoot;
41 import org.simantics.db.common.request.ReadRequest;
42 import org.simantics.db.common.request.UniqueRead;
43 import org.simantics.db.common.request.WriteRequest;
44 import org.simantics.db.common.utils.NameUtils;
45 import org.simantics.db.exception.DatabaseException;
46 import org.simantics.db.exception.ServiceException;
47 import org.simantics.db.exception.ValidationException;
48 import org.simantics.db.layer0.SelectionHints;
49 import org.simantics.db.procedure.Procedure;
50 import org.simantics.db.request.Read;
51 import org.simantics.district.network.ontology.DistrictNetworkResource;
52 import org.simantics.district.network.ui.function.Functions;
53 import org.simantics.district.network.ui.internal.Activator;
54 import org.simantics.utils.ui.ISelectionUtils;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public class ChangeMappingTypeHandler {
60 private static final Logger LOGGER = LoggerFactory.getLogger(ChangeMappingTypeHandler.class);
63 public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) ISelection selection) {
64 List<Resource> elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class);
65 if (elements.size() < 1)
68 return Simantics.getSession().syncRequest(new Read<Boolean>() {
71 public Boolean perform(ReadGraph graph) throws DatabaseException {
72 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
73 for (Resource selection : elements) {
74 if (!graph.isInstanceOf(selection, DN.Element)) {
81 } catch (DatabaseException e) {
82 LOGGER.error("Could not evaluate if mapping can be changed for selection {}", elements, e);
88 public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) Object selection) {
89 final List<Resource> elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class);
90 // if (elements.size() < 1)
93 CompletableFuture<Map<NamedResource, Collection<NamedResource>>> result = new CompletableFuture<>();
94 Simantics.getSession().asyncRequest(new UniqueRead<Map<NamedResource, Collection<NamedResource>>>() {
97 public Map<NamedResource, Collection<NamedResource>> perform(ReadGraph graph) throws DatabaseException {
98 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
100 Map<NamedResource, Collection<NamedResource>> currents = new HashMap<>();
101 for (Resource element : elements) {
102 Resource currentMapping = graph.getPossibleObject(element, DN.HasMapping);
103 NamedResource mapping = new NamedResource(NameUtils.getSafeName(graph, currentMapping), currentMapping);
104 currents.compute(mapping, (t, u) -> {
108 u.add(new NamedResource(NameUtils.getSafeName(graph, element), element));
109 } catch (ValidationException | ServiceException e) {
110 LOGGER.error("Could not compute name for {}", element, e);
117 }, new Procedure<Map<NamedResource, Collection<NamedResource>>>() {
120 public void execute(Map<NamedResource, Collection<NamedResource>> results) {
121 result.complete(results);
125 public void exception(Throwable t) {
126 LOGGER.error("Could not compute mappings for selection {}", elements, t);
127 result.completeExceptionally(t);
131 UIJob uiJob = new UIJob("Change mappings..") {
134 public IStatus runInUIThread(IProgressMonitor monitor) {
135 SelectMappingDialog dialog = new SelectMappingDialog(getDisplay().getActiveShell(), result);
136 if (dialog.open() != Dialog.OK)
137 return Status.OK_STATUS;
139 Map<Resource, Collection<NamedResource>> results = dialog.getResults();
140 Job job = new DatabaseJob("Join selected vertices") {
143 protected IStatus run(IProgressMonitor monitor) {
145 Simantics.getSession().syncRequest(new WriteRequest() {
148 public void perform(WriteGraph graph) throws DatabaseException {
149 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
151 for (Map.Entry<Resource, Collection<NamedResource>> entry : results.entrySet()) {
152 Resource newMapping = entry.getKey();
153 Collection<NamedResource> elements = entry.getValue();
154 for (NamedResource element : elements) {
155 graph.deny(element.getResource(), DN.HasMapping);
156 graph.claim(element.getResource(), DN.HasMapping, newMapping);
161 } catch (DatabaseException e) {
162 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, getName() + " failed.", e);
164 return Status.OK_STATUS;
169 return Status.OK_STATUS;
176 private static class SelectMappingDialog extends SelectionStatusDialog {
178 private Map<NamedResource, Combo> mappingCombos = new HashMap<>();
180 private Composite composite;
182 private CompletableFuture<Map<NamedResource, Collection<NamedResource>>> elements;
184 private Map<NamedResource, Map<String, Resource>> possibleMappings = new HashMap<>();
186 private Resource defaultVertexMapping;
188 protected SelectMappingDialog(Shell parentShell, CompletableFuture<Map<NamedResource, Collection<NamedResource>>> elements) {
190 this.elements = elements;
191 setTitle("Change mappings");
194 public Resource getDefaultVertexMapping() {
195 return defaultVertexMapping;
199 protected Control createDialogArea(Composite parent) {
200 composite = (Composite) super.createDialogArea(parent);
202 createMappingsGroup(composite);
204 // compute default values
205 Simantics.getSession().asyncRequest(new ReadRequest() {
208 public void run(ReadGraph graph) throws DatabaseException {
209 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
211 for (Map.Entry<NamedResource, Collection<NamedResource>> entry : elements.get().entrySet()) {
212 NamedResource currentMapping = entry.getKey();
213 Resource resource = entry.getValue().iterator().next().getResource();
214 Resource indexRoot = graph.sync(new IndexRoot(resource));
215 if (graph.isInstanceOf(currentMapping.getResource(), DN.Mapping_VertexMapping)) {
216 possibleMappings.put(currentMapping, Functions.getVertexMappings(graph, indexRoot));
217 } else if (graph.isInstanceOf(currentMapping.getResource(), DN.Mapping_EdgeMapping)) {
218 possibleMappings.put(currentMapping, Functions.getEdgeMappings(graph, indexRoot));
221 } catch (InterruptedException | ExecutionException e) {
224 composite.getDisplay().asyncExec(() -> {
225 for (Map.Entry<NamedResource, Map<String, Resource>> entry : possibleMappings.entrySet()) {
226 NamedResource key = entry.getKey();
227 Map<String, Resource> value = entry.getValue();
228 Combo combo = mappingCombos.get(key);
229 combo.setItems(value.keySet().toArray(new String[value.size()]));
238 private Map<Resource, Collection<NamedResource>> results = new HashMap<>();
241 protected void computeResult() {
242 Map<NamedResource, Collection<NamedResource>> currentElements = null;
244 currentElements = elements.get();
245 } catch (InterruptedException | ExecutionException e) {
246 LOGGER.error("Could not get currentElements", e);
247 throw new RuntimeException("Could not get currentElements", e);
249 for (Map.Entry<NamedResource, Combo> combos : mappingCombos.entrySet()) {
250 NamedResource resource = combos.getKey();
251 Combo c = combos.getValue();
252 String item = c.getItem(c.getSelectionIndex());
253 Collection<NamedResource> collection = currentElements.get(resource);
254 Map<String, Resource> map = possibleMappings.get(resource);
255 Resource newMapping = map.get(item);
256 results.compute(newMapping, (t, u) -> {
260 u.addAll(collection);
266 public Map<Resource, Collection<NamedResource>> getResults() {
270 private void createMappingsGroup(Composite parent) {
272 for (Map.Entry<NamedResource, Collection<NamedResource>> entry : elements.get().entrySet()) {
274 NamedResource currentMapping = entry.getKey();
276 Collection<NamedResource> mappedElements = entry.getValue();
278 Group group= new Group(parent, SWT.NONE);
279 group.setFont(parent.getFont());
280 group.setText(currentMapping.getName() + " currently mapped to " + mappedElements.size() + " elements");
281 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
282 group.setLayout(new GridLayout(1, false));
284 Composite cmposite = new Composite(group, SWT.NONE);
285 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
286 cmposite.setLayout(new GridLayout(2, false));
288 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
289 vertexMappingLabel.setText("New mapping type");
291 Combo c = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
292 GridDataFactory.fillDefaults().grab(true, false).applyTo(c);
293 mappingCombos.put(entry.getKey(), c);
295 } catch (InterruptedException | ExecutionException e) {