]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network.ui/src/org/simantics/district/network/ui/contributions/PasteDistrictVertexHandler.java
7fadac3fd32743aac2800e79017027463c22fd2a
[simantics/district.git] / org.simantics.district.network.ui / src / org / simantics / district / network / ui / contributions / PasteDistrictVertexHandler.java
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, sourceElement, sourceMappedElement));
141                     Resource targetMappedElement = graph.getPossibleObject(targetElement, DN.MappedComponent);
142                     targetCopyAttributes.putAll(copyAttributes(graph, targetElement, targetMappedElement));
143                     if (sourceMappedElement != null && cut)
144                         RemoverUtil.remove(graph, sourceMappedElement);
145                     if (targetMappedElement != null)
146                         RemoverUtil.remove(graph, targetMappedElement);
147                 }
148             });
149             ThreadUtils.getNonBlockingWorkExecutor().schedule(() -> {
150                 try {
151                                         Simantics.getSession().syncRequest(new WriteRequest() {
152
153                                                 @Override
154                                                 public void perform(WriteGraph graph) throws DatabaseException {
155                                                         Layer0 L0 = Layer0.getInstance(graph);
156
157                                                         Resource diagram = graph.getSingleObject(sourceElement, L0.PartOf);
158                                                         Resource newTarget = doCopy(graph, diagram, targetElement, sourceElement);
159                                                         if (cut) {
160                                                                 Resource newSource = doCopy(graph, diagram, sourceElement, targetElement);
161                                                                 for (Map.Entry<Resource, Object> attrValue : targetCopyAttributes.entrySet()) {
162                                                                         graph.claimLiteral(newSource, attrValue.getKey(), attrValue.getValue());
163                                                                 }
164                                                                 copyVertexInverses(graph, sourceElement, newSource);
165                                                                 deleteExistingTarget(graph, sourceElement);
166                                                         }
167                                                         for (Map.Entry<Resource, Object> attrValue : sourceCopyAttributes.entrySet()) {
168                                                                 graph.claimLiteral(newTarget, attrValue.getKey(), attrValue.getValue());
169                                                         }
170                                                         copyVertexInverses(graph, targetElement, newTarget);
171                                                         deleteExistingTarget(graph, targetElement);
172                                                 }
173                                         });
174                                 } catch (DatabaseException e) {
175                                         e.printStackTrace();
176                                 }
177             }, 500, TimeUnit.MILLISECONDS);
178
179 //              ThreadUtils.getNonBlockingWorkExecutor().schedule(() -> {
180 //                Simantics.getSession().asyncRequest(new WriteRequest() {
181 //                    
182 //                    @Override
183 //                    public void perform(WriteGraph graph) throws DatabaseException {
184 //                        DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
185 //                        //copyMapping(graph, DN, sourceElement, targetElement);
186 //                        copyLocation(graph, DN, sourceElement, targetElement, cut);
187 //                        copyVertexInverses(graph, DN, sourceElement, targetElement, cut);
188 //                        copyElevation(graph, DN, sourceElement, targetElement, cut);
189 //                    }
190 //                    
191 //                    private void copyMapping(WriteGraph graph, DistrictNetworkResource DN, Resource sourceElement, Resource targetElement) throws DatabaseException {
192 //                        Resource sourceMapping = graph.getSingleObject(sourceElement, DN.Mapping);
193 //                        Resource targetMapping = graph.getSingleObject(targetElement, DN.Mapping);
194 //                        if (cut) {
195 //                            graph.deny(sourceElement, DN.Mapping);
196 //                            graph.claim(sourceElement, DN.Mapping, targetMapping);
197 //                        }
198 //                        graph.deny(targetElement, DN.Mapping);
199 //                        graph.claim(targetElement, DN.Mapping, sourceMapping);
200 //                    }
201 //
202 //                    private void copyElevation(WriteGraph graph, DistrictNetworkResource DN, Resource sourceElement, Resource targetElement, boolean cut) throws DatabaseException {
203 //                        double sourceElevation = graph.getRelatedValue(sourceElement, DN.Vertex_HasElevation, Bindings.DOUBLE);
204 //                        double targetElevation = graph.getRelatedValue(targetElement, DN.Vertex_HasElevation, Bindings.DOUBLE);
205 //                        if (cut) {
206 //                            graph.deny(sourceElement, DN.Vertex_HasElevation);
207 //                            graph.claimLiteral(sourceElement, DN.Vertex_HasElevation, targetElevation, Bindings.DOUBLE);
208 //                        }
209 //                        graph.deny(targetElement, DN.Vertex_HasElevation);
210 //                        graph.claimLiteral(targetElement, DN.Vertex_HasElevation, sourceElevation, Bindings.DOUBLE);
211 //                    }
212 //
213 //                    private void copyLocation(WriteGraph graph, DistrictNetworkResource DN, Resource sourceElement, Resource targetElement, boolean cut) throws DatabaseException {
214 //                        DiagramResource DIA = DiagramResource.getInstance(graph);
215 //                        double[] sourceLocation = graph.getRelatedValue(sourceElement, DIA.HasLocation, Bindings.DOUBLE_ARRAY);
216 //                        double[] targetLocation = graph.getRelatedValue(targetElement, DIA.HasLocation, Bindings.DOUBLE_ARRAY);
217 //                        if (cut) {
218 //                            graph.deny(sourceElement, DIA.HasLocation);
219 //                            graph.claimLiteral(sourceElement, DIA.HasLocation, targetLocation, Bindings.DOUBLE_ARRAY);
220 //                        }
221 //                        graph.deny(targetElement, DIA.HasLocation);
222 //                        graph.claimLiteral(targetElement, DIA.HasLocation, sourceLocation, Bindings.DOUBLE_ARRAY);
223 //                    }
224 //                    
225
226 //                    
227 //                    
228 //                });
229 //            }, 500, TimeUnit.MILLISECONDS);
230
231         } catch (DatabaseException e) {
232             e.printStackTrace();
233         }
234         
235     }
236     
237     private static Map<Resource, Object> copyAttributes(WriteGraph graph, Resource sourceElement, Resource mappedElement) throws DatabaseException {
238         Layer0 L0 = Layer0.getInstance(graph);
239         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
240
241         Resource mapping = graph.getSingleObject(sourceElement, DN.HasMapping);
242         Collection<Statement> statements = graph.getStatements(mapping, L0.HasProperty);
243         Collection<Statement> mappingAttributeStatements = statements.stream().filter(stm -> {
244             try {
245                 Resource predicate = stm.getPredicate();
246                 Resource hasDomain = graph.getPossibleObject(predicate, L0.HasDomain);
247                 if (hasDomain != null && hasDomain.equals(DN.Mapping_VertexMapping)) {
248                     // filter out x and y and z
249                     Resource vertexAttribute = attributeMappingToVertexAttribute(graph, DN, predicate);
250                     return vertexAttribute != null;
251                 }
252             } catch (Exception e) {
253                 e.printStackTrace();
254             }
255             return false;
256         }).collect(Collectors.toList());
257         Resource component = graph.getPossibleObject(mappedElement, ModelingResources.getInstance(graph).ElementToComponent);
258         Variable variable = Variables.getVariable(graph, component);
259         Map<Resource, Object> predValues = new HashMap<>();
260         for (Statement stm : mappingAttributeStatements) {
261             String propertyName = graph.getPossibleValue(stm.getObject());
262             if (propertyName != null) {
263                 Object propertyValue = variable.getPossiblePropertyValue(graph, propertyName);
264                 if (propertyValue != null) {
265                     predValues.put(attributeMappingToVertexAttribute(graph, DN, stm.getPredicate()), propertyValue);
266                 } else {
267                     System.err.println("no property value for " + variable.getURI(graph) + " and property " + propertyName);
268                 }
269             } else {
270                 System.err.println("stm.getObject() is not string " + stm.getObject());
271             }
272         }
273         return predValues;
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 = null; // ignore elevation as well
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_PumpInReturnLineAttribute))
325             attr = DN.Vertex_HasPumpInReturnLine;
326         else if (attribute.equals(DN.Mapping_VertexMapping_HeadPumpMaximumAttribute))
327             attr = DN.Vertex_HasHeadPumpMaximum;
328         else if (attribute.equals(DN.Mapping_VertexMapping_HeadPumpNominalAttribute))
329             attr = DN.Vertex_HasHeadPumpNominal;
330         else if (attribute.equals(DN.Mapping_VertexMapping_FrequencyConverterControlledAttribute))
331             attr = DN.Vertex_HasFrequencyConverterControlled;
332         else if (attribute.equals(DN.Mapping_VertexMapping_InternalValveMeasurementAttribute))
333             attr = DN.Vertex_HasInternalValveMeasurement;
334         else if (attribute.equals(DN.Mapping_VertexMapping_PumpMassFlowNominalAttribute))
335             attr = DN.Vertex_HasPumpMassFlowNominal;
336         else if (attribute.equals(DN.Mapping_VertexMapping_PumpMeMaxAttribute))
337             attr = DN.Vertex_HasPumpMeMax;
338         else if (attribute.equals(DN.Mapping_VertexMapping_PumpMeMinAttribute))
339             attr = DN.Vertex_HasPumpMeMin;
340         else if (attribute.equals(DN.Mapping_VertexMapping_PumpSpeedMaxAttribute))
341             attr = DN.Vertex_HasPumpSpeedMax;
342         else if (attribute.equals(DN.Mapping_VertexMapping_PumpSpeedMinAttribute))
343             attr = DN.Vertex_HasPumpSpeedMin;
344         else if (attribute.equals(DN.Mapping_VertexMapping_ValveReturnLineAttribute))
345             attr = DN.Vertex_HasValveReturnLine;
346         else if (attribute.equals(DN.Mapping_VertexMapping_ValveMeMaxAttribute))
347             attr = DN.Vertex_HasValveMeMax;
348         else if (attribute.equals(DN.Mapping_VertexMapping_ValveMeMinAttribute))
349             attr = DN.Vertex_HasValveMeMin;
350         else if (attribute.equals(DN.Mapping_VertexMapping_ValveMinPositionAttribute))
351             attr = DN.Vertex_HasValveMinPosition;
352         else if (attribute.equals(DN.Mapping_VertexMapping_ValveOutletModeAttribute))
353             attr = DN.Vertex_HasValveOutletMode;
354         else if (attribute.equals(DN.Mapping_VertexMapping_ValvePressLossNominalAttribute))
355             attr = DN.Vertex_HasValvePressLossNominal;
356         else if (attribute.equals(DN.Mapping_VertexMapping_OpeningTimeAttribute))
357             attr = DN.Vertex_HasOpeningTime;
358         else if (attribute.equals(DN.Mapping_VertexMapping_XAttribute))
359                 attr = null; // ignore this!
360         else if (attribute.equals(DN.Mapping_VertexMapping_YAttribute))
361                 attr = null; // ignore this!
362         return attr;
363     }
364 }