]> gerrit.simantics Code Review - simantics/district.git/blob
0ad64469460ae4682ed7ad0e81de9c379377e4ff
[simantics/district.git] /
1 package org.simantics.district.network.ui.contributions;
2
3 import java.util.Collection;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.concurrent.TimeUnit;
8 import java.util.stream.Collectors;
9
10 import javax.inject.Named;
11
12 import org.eclipse.e4.core.di.annotations.CanExecute;
13 import org.eclipse.e4.core.di.annotations.Execute;
14 import org.eclipse.e4.ui.services.IServiceConstants;
15 import org.eclipse.jface.viewers.ISelection;
16 import org.simantics.Simantics;
17 import org.simantics.databoard.Bindings;
18 import org.simantics.db.ReadGraph;
19 import org.simantics.db.Resource;
20 import org.simantics.db.Statement;
21 import org.simantics.db.WriteGraph;
22 import org.simantics.db.common.request.WriteRequest;
23 import org.simantics.db.exception.DatabaseException;
24 import org.simantics.db.layer0.SelectionHints;
25 import org.simantics.db.layer0.util.RemoverUtil;
26 import org.simantics.db.layer0.variable.Variable;
27 import org.simantics.db.layer0.variable.Variables;
28 import org.simantics.db.request.Read;
29 import org.simantics.diagram.stubs.DiagramResource;
30 import org.simantics.district.network.DistrictNetworkUtil;
31 import org.simantics.district.network.ontology.DistrictNetworkResource;
32 import org.simantics.layer0.Layer0;
33 import org.simantics.modeling.ModelingResources;
34 import org.simantics.utils.threads.ThreadUtils;
35 import org.simantics.utils.ui.ISelectionUtils;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 public class PasteDistrictVertexHandler {
40
41     private static final Logger LOGGER = LoggerFactory.getLogger(PasteDistrictVertexHandler.class);
42
43     @CanExecute
44     public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) ISelection selection) {
45         List<Resource> elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class);
46         if (elements.size() < 1)
47             return false;
48         try {
49             return Simantics.getSession().syncRequest(new Read<Boolean>() {
50
51                 @Override
52                 public Boolean perform(ReadGraph graph) throws DatabaseException {
53                     DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
54                     for (Resource selection : elements) {
55                         if (!graph.isInstanceOf(selection, DN.Element)) {
56                             return false;
57                         }
58                     }
59                     return true;
60                 }
61             });
62         } catch (DatabaseException e) {
63             LOGGER.error("Could not evaluate if mapping can be changed for selection {}", elements, e);
64             return false;
65         }
66     }
67     
68     private static Resource doCopy(WriteGraph graph, Resource diagram, Resource target, Resource source) throws DatabaseException {
69                 DiagramResource DIA = DiagramResource.getInstance(graph);
70                 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
71                 double[] location = graph.getRelatedValue(target, DIA.HasLocation, Bindings.DOUBLE_ARRAY);
72                 double elevation = graph.getRelatedValue(target, DN.Vertex_HasElevation, Bindings.DOUBLE);
73                 Resource vertex = DistrictNetworkUtil.createVertex(graph, diagram, location, elevation);
74                 copySourceToTarget(graph, source, vertex);
75                 return vertex;
76     }
77
78     private static void copySourceToTarget(WriteGraph graph, Resource source, Resource target) throws DatabaseException {
79         Layer0 L0 = Layer0.getInstance(graph);
80         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
81         graph.deny(target, DN.HasMapping);
82         
83                 Collection<Statement> statements = graph.getStatements(source, L0.HasProperty);
84                 Collection<Statement> assertedStatements = graph.getAssertedStatements(source, L0.HasProperty);
85                 statements.removeAll(assertedStatements);
86                 for (Statement stm : statements) {
87                         if (!graph.hasStatement(target, stm.getPredicate())) {
88                                 graph.claim(target, stm.getPredicate(), stm.getObject());
89                         }
90                 }
91     }
92
93         private static void copyVertexInverses(WriteGraph graph, Resource sourceElement, Resource targetElement) throws DatabaseException {
94                 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
95                 Collection<Resource> sourceStartVertex_inverse = graph.getObjects(sourceElement, DN.HasStartVertex_Inverse);
96                 Collection<Resource> sourceEndVertex_inverse = graph.getObjects(sourceElement, DN.HasEndVertex_Inverse);
97                 Collection<Resource> targetStartVertex_inverse = graph.getObjects(targetElement, DN.HasStartVertex_Inverse);
98                 Collection<Resource> targetEndVertex_inverse = graph.getObjects(targetElement, DN.HasEndVertex_Inverse);
99                 graph.deny(sourceElement, DN.HasStartVertex_Inverse);
100                 graph.deny(sourceElement, DN.HasEndVertex_Inverse);
101                 graph.deny(targetElement, DN.HasStartVertex_Inverse);
102                 graph.deny(targetElement, DN.HasEndVertex_Inverse);
103                 for (Resource startVertexInverse : sourceStartVertex_inverse) {
104                         graph.claim(targetElement, DN.HasStartVertex_Inverse, startVertexInverse);
105                 }
106                 for (Resource targetVertexInverse : targetStartVertex_inverse) {
107                         graph.claim(sourceElement, DN.HasStartVertex_Inverse, targetVertexInverse);
108                 }
109                 for (Resource endVertexInverse : sourceEndVertex_inverse) {
110                         graph.claim(targetElement, DN.HasEndVertex_Inverse, endVertexInverse);
111                 }
112                 for (Resource targetVertexInverse : targetEndVertex_inverse) {
113                         graph.claim(sourceElement, DN.HasEndVertex_Inverse, targetVertexInverse);
114                 }
115         }
116     
117     private static void deleteExistingTarget(WriteGraph graph, Resource target) throws DatabaseException {
118         RemoverUtil.remove(graph, target);
119     }
120     
121     @Execute
122     public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) Object selection) {
123         final List<Resource> elements = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_MAIN, Resource.class);
124         final List<Resource> copiedElements = CopyDistrictVertexHandler.elements; // TODO: this could be implemented more nicely with clipboard ?
125         boolean cut = CopyDistrictVertexHandler.cut;
126         
127         Resource targetElement = elements.get(0);
128         Resource sourceElement = copiedElements.get(0);
129         
130         try {
131             Map<Resource, Object> sourceCopyAttributes = new HashMap<>();
132             Map<Resource, Object> targetCopyAttributes = new HashMap<>();
133             Simantics.getSession().syncRequest(new WriteRequest() {
134                 
135                 @Override
136                 public void perform(WriteGraph graph) throws DatabaseException {
137                     DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
138                     
139                     Resource sourceMappedElement = graph.getPossibleObject(sourceElement, DN.MappedComponent);
140                     sourceCopyAttributes.putAll(copyAttributes(graph, sourceMappedElement));
141                     Resource targetMappedElement = graph.getPossibleObject(targetElement, DN.MappedComponent);
142                     targetCopyAttributes.putAll(copyAttributes(graph, targetMappedElement));
143                     if (sourceMappedElement != null && cut)
144                         RemoverUtil.remove(graph, sourceMappedElement);
145                     if (targetMappedElement != null)
146                         RemoverUtil.remove(graph, targetMappedElement);
147                 }
148                 
149                 private Map<Resource, Object> copyAttributes(WriteGraph graph, Resource mappedElement) throws DatabaseException {
150                     Layer0 L0 = Layer0.getInstance(graph);
151                     DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
152
153                     Resource mapping = graph.getSingleObject(sourceElement, DN.HasMapping);
154                     Collection<Statement> statements = graph.getStatements(mapping, L0.HasProperty);
155                     Collection<Statement> mappingAttributeStatements = statements.stream().filter(stm -> {
156                         try {
157                                 Resource predicate = stm.getPredicate();
158                                 Resource hasDomain = graph.getPossibleObject(predicate, L0.HasDomain);
159                                 if (hasDomain != null && hasDomain.equals(DN.Mapping_VertexMapping)) {
160                                         // filter out x and y and z
161                                         Resource vertexAttribute = attributeMappingToVertexAttribute(graph, DN, predicate);
162                                     return vertexAttribute != null;
163                                 }
164                         } catch (Exception e) {
165                             e.printStackTrace();
166                         }
167                         return false;
168                     }).collect(Collectors.toList());
169                     Resource component = graph.getPossibleObject(mappedElement, ModelingResources.getInstance(graph).ElementToComponent);
170                     Variable variable = Variables.getVariable(graph, component);
171                     Map<Resource, Object> predValues = new HashMap<>();
172                     for (Statement stm : mappingAttributeStatements) {
173                         String propertyName = graph.getPossibleValue(stm.getObject());
174                         if (propertyName != null) {
175                             Object propertyValue = variable.getPossiblePropertyValue(graph, propertyName);
176                             if (propertyValue != null) {
177                                 predValues.put(attributeMappingToVertexAttribute(graph, DN, stm.getPredicate()), propertyValue);
178                             } else {
179                                 System.err.println("no property value for " + variable.getURI(graph) + " and property " + propertyName);
180                             }
181                         } else {
182                             System.err.println("stm.getObject() is not string " + stm.getObject());
183                         }
184                     }
185                     return predValues;
186                 }
187             });
188             ThreadUtils.getNonBlockingWorkExecutor().schedule(() -> {
189                 try {
190                                         Simantics.getSession().syncRequest(new WriteRequest() {
191
192                                                 @Override
193                                                 public void perform(WriteGraph graph) throws DatabaseException {
194                                                         Layer0 L0 = Layer0.getInstance(graph);
195
196                                                         Resource diagram = graph.getSingleObject(sourceElement, L0.PartOf);
197                                                         Resource newTarget = doCopy(graph, diagram, targetElement, sourceElement);
198                                                         if (cut) {
199                                                                 Resource newSource = doCopy(graph, diagram, sourceElement, targetElement);
200                                                                 for (Map.Entry<Resource, Object> attrValue : targetCopyAttributes.entrySet()) {
201                                                                         graph.claimLiteral(newSource, attrValue.getKey(), attrValue.getValue());
202                                                                 }
203                                                                 copyVertexInverses(graph, sourceElement, newSource);
204                                                                 deleteExistingTarget(graph, sourceElement);
205                                                         }
206                                                         for (Map.Entry<Resource, Object> attrValue : sourceCopyAttributes.entrySet()) {
207                                                                 graph.claimLiteral(newTarget, attrValue.getKey(), attrValue.getValue());
208                                                         }
209                                                         copyVertexInverses(graph, targetElement, newTarget);
210                                                         deleteExistingTarget(graph, targetElement);
211                                                 }
212                                         });
213                                 } catch (DatabaseException e) {
214                                         e.printStackTrace();
215                                 }
216             }, 500, TimeUnit.MILLISECONDS);
217
218 //              ThreadUtils.getNonBlockingWorkExecutor().schedule(() -> {
219 //                Simantics.getSession().asyncRequest(new WriteRequest() {
220 //                    
221 //                    @Override
222 //                    public void perform(WriteGraph graph) throws DatabaseException {
223 //                        DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
224 //                        //copyMapping(graph, DN, sourceElement, targetElement);
225 //                        copyLocation(graph, DN, sourceElement, targetElement, cut);
226 //                        copyVertexInverses(graph, DN, sourceElement, targetElement, cut);
227 //                        copyElevation(graph, DN, sourceElement, targetElement, cut);
228 //                    }
229 //                    
230 //                    private void copyMapping(WriteGraph graph, DistrictNetworkResource DN, Resource sourceElement, Resource targetElement) throws DatabaseException {
231 //                        Resource sourceMapping = graph.getSingleObject(sourceElement, DN.Mapping);
232 //                        Resource targetMapping = graph.getSingleObject(targetElement, DN.Mapping);
233 //                        if (cut) {
234 //                            graph.deny(sourceElement, DN.Mapping);
235 //                            graph.claim(sourceElement, DN.Mapping, targetMapping);
236 //                        }
237 //                        graph.deny(targetElement, DN.Mapping);
238 //                        graph.claim(targetElement, DN.Mapping, sourceMapping);
239 //                    }
240 //
241 //                    private void copyElevation(WriteGraph graph, DistrictNetworkResource DN, Resource sourceElement, Resource targetElement, boolean cut) throws DatabaseException {
242 //                        double sourceElevation = graph.getRelatedValue(sourceElement, DN.Vertex_HasElevation, Bindings.DOUBLE);
243 //                        double targetElevation = graph.getRelatedValue(targetElement, DN.Vertex_HasElevation, Bindings.DOUBLE);
244 //                        if (cut) {
245 //                            graph.deny(sourceElement, DN.Vertex_HasElevation);
246 //                            graph.claimLiteral(sourceElement, DN.Vertex_HasElevation, targetElevation, Bindings.DOUBLE);
247 //                        }
248 //                        graph.deny(targetElement, DN.Vertex_HasElevation);
249 //                        graph.claimLiteral(targetElement, DN.Vertex_HasElevation, sourceElevation, Bindings.DOUBLE);
250 //                    }
251 //
252 //                    private void copyLocation(WriteGraph graph, DistrictNetworkResource DN, Resource sourceElement, Resource targetElement, boolean cut) throws DatabaseException {
253 //                        DiagramResource DIA = DiagramResource.getInstance(graph);
254 //                        double[] sourceLocation = graph.getRelatedValue(sourceElement, DIA.HasLocation, Bindings.DOUBLE_ARRAY);
255 //                        double[] targetLocation = graph.getRelatedValue(targetElement, DIA.HasLocation, Bindings.DOUBLE_ARRAY);
256 //                        if (cut) {
257 //                            graph.deny(sourceElement, DIA.HasLocation);
258 //                            graph.claimLiteral(sourceElement, DIA.HasLocation, targetLocation, Bindings.DOUBLE_ARRAY);
259 //                        }
260 //                        graph.deny(targetElement, DIA.HasLocation);
261 //                        graph.claimLiteral(targetElement, DIA.HasLocation, sourceLocation, Bindings.DOUBLE_ARRAY);
262 //                    }
263 //                    
264
265 //                    
266 //                    
267 //                });
268 //            }, 500, TimeUnit.MILLISECONDS);
269
270         } catch (DatabaseException e) {
271             e.printStackTrace();
272         }
273         
274     }
275     
276     private static Resource attributeMappingToVertexAttribute(ReadGraph graph, DistrictNetworkResource DN, Resource attribute) throws DatabaseException {
277         Resource attr = null;
278         if (attribute.equals(DN.Mapping_VertexMapping_ElevationAttribute))
279             attr = DN.Vertex_HasElevation;
280         else if (attribute.equals(DN.Mapping_VertexMapping_AddressAttribute))
281                 attr = DN.Vertex_HasAddress;
282         else if (attribute.equals(DN.Mapping_VertexMapping_DeltaPressureAttribute))
283                 attr = DN.Vertex_HasDeltaPressure;
284         else if (attribute.equals(DN.Mapping_VertexMapping_DeltaTemperatureAttribute))
285                 attr = DN.Vertex_HasDeltaTemperature;
286         else if (attribute.equals(DN.Mapping_VertexMapping_dpAttribute))
287                 attr = DN.Vertex_HasDeltaPressure;
288         else if (attribute.equals(DN.Mapping_VertexMapping_dtAttribute))
289                 attr = DN.Vertex_HasDeltaTemperature;
290         else if (attribute.equals(DN.Mapping_VertexMapping_FlowAreaAttribute))
291                 attr = DN.Vertex_HasFlowArea;
292         else if (attribute.equals(DN.Mapping_VertexMapping_HeatLoadDsAttribute))
293                 attr = DN.Vertex_HasHeatLoadDs;
294         else if (attribute.equals(DN.Mapping_VertexMapping_HeatPowerAttribute))
295                 attr = DN.Vertex_HasHeatPower;
296         else if (attribute.equals(DN.Mapping_VertexMapping_MassFlowAttribute))
297                 attr = DN.Vertex_HasMassFlow;
298         else if (attribute.equals(DN.Mapping_VertexMapping_MaximumHeadMAttribute))
299                 attr = DN.Vertex_HasMaximumHeadM;
300         else if (attribute.equals(DN.Mapping_VertexMapping_NominalFlowAttribute))
301                 attr = DN.Vertex_HasNominalFlow;
302         else if (attribute.equals(DN.Mapping_VertexMapping_NominalHeadBAttribute))
303                 attr = DN.Vertex_HasNominalHeadB_Inverse;
304         else if (attribute.equals(DN.Mapping_VertexMapping_NominalHeadMAttribute))
305                 attr = DN.Vertex_HasNominalHeadM;
306         else if (attribute.equals(DN.Mapping_VertexMapping_NominalMassFlowAttribute))
307                 attr = DN.Vertex_HasNominalFlow;
308         else if (attribute.equals(DN.Mapping_VertexMapping_NominalPressureLossAttribute))
309                 attr = DN.Vertex_HasNominalPressureLoss;
310         else if (attribute.equals(DN.Mapping_VertexMapping_ReturnPressureAttribute))
311                 attr = DN.Vertex_HasReturnPressure;
312         else if (attribute.equals(DN.Mapping_VertexMapping_ReturnTemperatureAttribute))
313                 attr = DN.Vertex_HasReturnTemperature;
314         else if (attribute.equals(DN.Mapping_VertexMapping_SupplyPressureAttribute))
315                 attr = DN.Vertex_HasSupplyPressure;
316         else if (attribute.equals(DN.Mapping_VertexMapping_SupplyTemperatureAttribute))
317                 attr = DN.Vertex_HasSupplyTemperature;
318         else if (attribute.equals(DN.Mapping_VertexMapping_ValvePositionAttribute))
319                 attr = DN.Vertex_HasValvePosition;
320         else if (attribute.equals(DN.Mapping_VertexMapping_VelocityAttribute))
321                 attr = DN.Vertex_HasVelocity;
322         else if (attribute.equals(DN.Mapping_VertexMapping_VolFlowAttribute))
323                 attr = DN.Vertex_HasVolFlow;
324         else if (attribute.equals(DN.Mapping_VertexMapping_XAttribute))
325                 attr = null; // ignore this!
326         else if (attribute.equals(DN.Mapping_VertexMapping_YAttribute))
327                 attr = null; // ignore this!
328         return attr;
329     }
330 }