]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/contributions/ChangeMappingTypeHandler.java
1f94833507ad557226f249d02740347d995e6eab
[simantics/district.git] / org.simantics.district.network.ui / src / org / simantics / district / network / ui / contributions / ChangeMappingTypeHandler.java
1 package org.simantics.district.network.ui.contributions;
2
3 import java.util.Collection;
4 import java.util.HashMap;
5 import java.util.HashSet;
6 import java.util.List;
7 import java.util.Map;
8 import java.util.concurrent.CompletableFuture;
9 import java.util.concurrent.ExecutionException;
10
11 import javax.inject.Named;
12
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.district.network.ontology.DistrictNetworkResource;
51 import org.simantics.district.network.ui.function.Functions;
52 import org.simantics.district.network.ui.internal.Activator;
53 import org.simantics.utils.ui.ISelectionUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 public class ChangeMappingTypeHandler {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(ChangeMappingTypeHandler.class);
60
61     @CanExecute
62     public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) ISelection selection) {
63 //        List<Resource> elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class);
64 //        if (elements.size() < 1)
65 //            return false;
66 //        try {
67 //            return Simantics.getSession().syncRequest(new Read<Boolean>() {
68 //
69 //                @Override
70 //                public Boolean perform(ReadGraph graph) throws DatabaseException {
71 //                    Layer0 L0 = Layer0.getInstance(graph);
72 //                    Resource instanceOf = null;
73 //                    for (Resource element : elements) {
74 //                        if (instanceOf == null) {
75 //                            instanceOf = graph.getSingleObject(element, L0.InstanceOf);
76 //                        } else {
77 //                            Resource currentInstanceOf = graph.getSingleObject(element, L0.InstanceOf);
78 //                            if (!currentInstanceOf.equals(instanceOf)) {
79 //                                return false;
80 //                            }
81 //                        }
82 //                    }
83 //                    return true;
84 //                }
85 //            });
86 //        } catch (DatabaseException e) {
87 //            e.printStackTrace();
88 //            return false;
89 //        }
90         return true;
91     }
92     
93     @Execute
94     public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) Object selection) {
95         final List<Resource> elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class);
96 //        if (elements.size() < 1)
97 //            return;
98         
99         CompletableFuture<Map<NamedResource, Collection<NamedResource>>> result = new CompletableFuture<>();
100         Simantics.getSession().asyncRequest(new UniqueRead<Map<NamedResource, Collection<NamedResource>>>() {
101             
102             @Override
103             public Map<NamedResource, Collection<NamedResource>> perform(ReadGraph graph) throws DatabaseException {
104                 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
105                 
106                 Map<NamedResource, Collection<NamedResource>> currents = new HashMap<>();
107                 for (Resource element : elements) {
108                     Resource currentMapping = graph.getPossibleObject(element, DN.HasMapping);
109                     NamedResource mapping = new NamedResource(NameUtils.getSafeName(graph, currentMapping), currentMapping);
110                     currents.compute(mapping, (t, u) -> {
111                         if (u == null)
112                             u = new HashSet<>();
113                         try {
114                             u.add(new NamedResource(NameUtils.getSafeName(graph, element), element));
115                         } catch (ValidationException | ServiceException e) {
116                             LOGGER.error("Could not compute name for {}", element, e);
117                         }
118                         return u;
119                     });
120                 }
121                 return currents;
122             }
123         }, new Procedure<Map<NamedResource, Collection<NamedResource>>>() {
124
125             @Override
126             public void execute(Map<NamedResource, Collection<NamedResource>> results) {
127                 result.complete(results);
128             }
129
130             @Override
131             public void exception(Throwable t) {
132                 LOGGER.error("Could not compute mappings for selection {}", elements, t);
133                 result.completeExceptionally(t);
134             }
135         });
136         
137         UIJob uiJob = new UIJob("Change mappings..") {
138             
139             @Override
140             public IStatus runInUIThread(IProgressMonitor monitor) {
141                 SelectMappingDialog dialog = new SelectMappingDialog(getDisplay().getActiveShell(), result);
142                 if (dialog.open() != Dialog.OK)
143                     return Status.OK_STATUS;
144                 
145                 Map<Resource, Collection<NamedResource>> results = dialog.getResults();
146                 Job job = new DatabaseJob("Join selected vertices") {
147                     
148                     @Override
149                     protected IStatus run(IProgressMonitor monitor) {
150                         try {
151                             Simantics.getSession().syncRequest(new WriteRequest() {
152                                 
153                                 @Override
154                                 public void perform(WriteGraph graph) throws DatabaseException {
155                                     DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
156                                     
157                                     for (Map.Entry<Resource, Collection<NamedResource>> entry : results.entrySet()) {
158                                         Resource newMapping = entry.getKey();
159                                         Collection<NamedResource> elements = entry.getValue();
160                                         for (NamedResource element : elements) {
161                                             graph.deny(element.getResource(), DN.HasMapping);
162                                             graph.claim(element.getResource(), DN.HasMapping, newMapping);
163                                         }
164                                     }
165                                 }
166                             });
167                         } catch (DatabaseException e) {
168                             return new Status(IStatus.ERROR, Activator.PLUGIN_ID, getName() + " failed.", e);
169                         }
170                         return Status.OK_STATUS;
171                     }
172                 };
173                 job.setUser(true);
174                 job.schedule();
175                 return Status.OK_STATUS;
176             }
177         };
178         uiJob.setUser(true);
179         uiJob.schedule();
180     }
181     
182     private static class SelectMappingDialog extends SelectionStatusDialog {
183
184         private Map<NamedResource, Combo> mappingCombos = new HashMap<>();
185         
186         private Composite composite;
187         
188         private CompletableFuture<Map<NamedResource, Collection<NamedResource>>> elements;
189         
190         private Map<NamedResource, Map<String, Resource>> possibleMappings = new HashMap<>();
191         
192         private Resource defaultVertexMapping;
193
194         protected SelectMappingDialog(Shell parentShell, CompletableFuture<Map<NamedResource, Collection<NamedResource>>> elements) {
195             super(parentShell);
196             this.elements = elements;
197             setTitle("Change mappings");
198         }
199
200         public Resource getDefaultVertexMapping() {
201             return defaultVertexMapping;
202         }
203
204         @Override
205         protected Control createDialogArea(Composite parent) {
206             composite = (Composite) super.createDialogArea(parent);
207             
208             createMappingsGroup(composite);
209             
210             // compute default values
211             Simantics.getSession().asyncRequest(new ReadRequest() {
212
213                 @Override
214                 public void run(ReadGraph graph) throws DatabaseException {
215                     DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
216                     try {
217                         for (Map.Entry<NamedResource, Collection<NamedResource>> entry : elements.get().entrySet()) {
218                             NamedResource currentMapping = entry.getKey();
219                             Resource resource = entry.getValue().iterator().next().getResource();
220                             Resource indexRoot = graph.sync(new IndexRoot(resource));
221                             if (graph.isInstanceOf(currentMapping.getResource(), DN.Mapping_VertexMapping)) {
222                                 possibleMappings.put(currentMapping, Functions.getVertexMappings(graph, indexRoot));
223                             } else if (graph.isInstanceOf(currentMapping.getResource(), DN.Mapping_EdgeMapping)) {
224                                 possibleMappings.put(currentMapping, Functions.getEdgeMappings(graph, indexRoot));
225                             }
226                         }
227                     } catch (InterruptedException | ExecutionException e) {
228                         e.printStackTrace();
229                     }
230                     composite.getDisplay().asyncExec(() -> {
231                         for (Map.Entry<NamedResource, Map<String, Resource>> entry : possibleMappings.entrySet()) {
232                             NamedResource key = entry.getKey();
233                             Map<String, Resource> value = entry.getValue();
234                             Combo combo = mappingCombos.get(key);
235                             combo.setItems(value.keySet().toArray(new String[value.size()]));
236                             combo.select(0);
237                         }
238                     });
239                 }
240             });
241             return composite;
242         }
243
244         private Map<Resource, Collection<NamedResource>> results = new HashMap<>();
245         
246         @Override
247         protected void computeResult() {
248             Map<NamedResource, Collection<NamedResource>> currentElements = null;
249             try {
250                 currentElements = elements.get();
251             } catch (InterruptedException | ExecutionException e) {
252                 LOGGER.error("Could not get currentElements", e);
253                 throw new RuntimeException("Could not get currentElements", e);
254             }
255             for (Map.Entry<NamedResource, Combo> combos : mappingCombos.entrySet()) {
256                 NamedResource resource = combos.getKey();
257                 Combo c = combos.getValue();
258                 String item = c.getItem(c.getSelectionIndex());
259                 Collection<NamedResource> collection = currentElements.get(resource);
260                 Map<String, Resource> map = possibleMappings.get(resource);
261                 Resource newMapping = map.get(item);
262                 results.compute(newMapping, (t, u) -> {
263                     if (u == null) {
264                         u = new HashSet<>();
265                     }
266                     u.addAll(collection);
267                     return u;
268                 });
269             }
270         }
271
272         public Map<Resource, Collection<NamedResource>> getResults() {
273             return results;
274         }
275
276         private void createMappingsGroup(Composite parent) {
277             try {
278                 for (Map.Entry<NamedResource, Collection<NamedResource>> entry : elements.get().entrySet()) {
279                     
280                     NamedResource currentMapping = entry.getKey();
281                     
282                     Collection<NamedResource> mappedElements = entry.getValue();
283                     
284                     Group group= new Group(parent, SWT.NONE);
285                     group.setFont(parent.getFont());
286                     group.setText(currentMapping.getName() + " currently mapped to " + mappedElements.size() + " elements");
287                     GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
288                     group.setLayout(new GridLayout(1, false));
289                     
290                     Composite cmposite = new Composite(group, SWT.NONE);
291                     cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
292                     cmposite.setLayout(new GridLayout(2, false));
293                     
294                     Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
295                     vertexMappingLabel.setText("New mapping type");
296
297                     Combo c = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
298                     GridDataFactory.fillDefaults().grab(true, false).applyTo(c);
299                     mappingCombos.put(entry.getKey(), c);
300                 }
301             } catch (InterruptedException | ExecutionException e) {
302                 e.printStackTrace();
303             }
304         }
305     }
306 }