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