]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.structural2/src/org/simantics/structural2/Functions.java
Do not compute replaceable type for non ReplaceableDefinedComponentTypes
[simantics/platform.git] / bundles / org.simantics.structural2 / src / org / simantics / structural2 / Functions.java
1 package org.simantics.structural2;
2
3
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Collections;
7 import java.util.HashSet;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.Set;
11
12 import org.simantics.databoard.Bindings;
13 import org.simantics.databoard.Datatypes;
14 import org.simantics.databoard.adapter.AdaptException;
15 import org.simantics.databoard.binding.Binding;
16 import org.simantics.databoard.binding.error.BindingException;
17 import org.simantics.databoard.binding.error.DatatypeConstructionException;
18 import org.simantics.databoard.type.Datatype;
19 import org.simantics.databoard.util.URIStringUtils;
20 import org.simantics.db.Issue;
21 import org.simantics.db.ReadGraph;
22 import org.simantics.db.Resource;
23 import org.simantics.db.Statement;
24 import org.simantics.db.WriteGraph;
25 import org.simantics.db.common.issue.StandardIssue;
26 import org.simantics.db.common.primitiverequest.IsInstanceOf;
27 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
28 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
29 import org.simantics.db.common.request.ObjectsWithType;
30 import org.simantics.db.common.request.PossibleIndexRoot;
31 import org.simantics.db.common.request.PossibleObjectWithType;
32 import org.simantics.db.common.request.ResourceRead;
33 import org.simantics.db.common.request.TernaryRead;
34 import org.simantics.db.common.uri.UnescapedChildMapOfResource;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.db.layer0.function.All;
37 import org.simantics.db.layer0.function.StandardChildDomainChildren;
38 import org.simantics.db.layer0.request.PropertyInfo;
39 import org.simantics.db.layer0.request.PropertyInfoRequest;
40 import org.simantics.db.layer0.request.VariableRead;
41 import org.simantics.db.layer0.variable.AbstractChildVariable;
42 import org.simantics.db.layer0.variable.AbstractPropertyVariable;
43 import org.simantics.db.layer0.variable.LazyPropertyVariable;
44 import org.simantics.db.layer0.variable.NodeSupport;
45 import org.simantics.db.layer0.variable.StandardGraphChildVariable;
46 import org.simantics.db.layer0.variable.StandardGraphPropertyVariable;
47 import org.simantics.db.layer0.variable.ValueAccessor;
48 import org.simantics.db.layer0.variable.ValueAccessorWithBinding;
49 import org.simantics.db.layer0.variable.Variable;
50 import org.simantics.db.layer0.variable.VariableMap;
51 import org.simantics.db.layer0.variable.VariableMapImpl;
52 import org.simantics.db.layer0.variable.VariableNode;
53 import org.simantics.db.service.CollectionSupport;
54 import org.simantics.issues.common.IssueUtils;
55 import org.simantics.layer0.Layer0;
56 import org.simantics.scl.reflection.annotations.SCLValue;
57 import org.simantics.scl.runtime.SCLContext;
58 import org.simantics.scl.runtime.function.Function1;
59 import org.simantics.scl.runtime.tuple.Tuple2;
60 import org.simantics.simulation.ontology.SimulationResource;
61 import org.simantics.simulator.variable.NodeManager;
62 import org.simantics.structural.stubs.StructuralResource2;
63 import org.simantics.structural2.procedural.Component;
64 import org.simantics.structural2.procedural.ConnectionPoint;
65 import org.simantics.structural2.procedural.Interface;
66 import org.simantics.structural2.procedural.SubstructureElement;
67 import org.simantics.structural2.procedural.Terminal;
68 import org.simantics.structural2.queries.ConnectionComponents;
69 import org.simantics.structural2.queries.ConnectionJoinComponents;
70 import org.simantics.structural2.queries.ConnectionPointMapOfResource;
71 import org.simantics.structural2.queries.PossibleConnectionPointInfo;
72 import org.simantics.structural2.scl.CompileStructuralValueRequest;
73 import org.simantics.structural2.scl.procedural.CompileProceduralComponentTypeRequest;
74 import org.simantics.structural2.utils.StructuralUtils.StructuralComponentClass;
75 import org.simantics.structural2.variables.Connection;
76 import org.simantics.structural2.variables.StandardProceduralChildVariable;
77 import org.simantics.utils.datastructures.MapList;
78
79 import gnu.trove.map.hash.THashMap;
80
81 public class Functions {
82         
83         @SCLValue(type="ValueAccessor")
84         public static final ValueAccessor expressionValueAccessor = new ValueAccessorWithBinding() {
85
86                 public Binding getBinding() {
87                         return Bindings.STRING;
88                 }
89                 
90                 @Override
91                 public void setValue(WriteGraph graph, Variable context, Object value)
92                                 throws DatabaseException {
93                         if(value == null) {
94                                 if(getValue(graph, context) != null)
95                                         clearExpression(graph, context);
96                                 return;
97                         }
98                         
99                         // Get all necessary data
100                         String expression = (String)value;
101                         Variable parent = context.getParent(graph);
102                         if(!(parent instanceof AbstractPropertyVariable)) return;
103                         AbstractPropertyVariable property = (AbstractPropertyVariable)parent;                   
104                         Resource propertyResource = property.getRepresents(graph);
105                         if(propertyResource == null) return;
106                         Resource container = property.getContainerResource(graph);
107                         if(container == null) return;
108                         Resource predicate = property.getPossiblePredicateResource(graph);
109                         if(predicate == null) return;                   
110                         Statement stat = graph.getPossibleStatement(container, predicate);                      
111                         StructuralResource2 STR = StructuralResource2.getInstance(graph);
112                         
113                         // Write                        
114                         boolean createNew = false;
115                         if(stat.isAsserted(container))
116                                 createNew = true;
117                         else if(!graph.isInstanceOf(propertyResource, STR.SCLValue)) {
118                                 graph.deny(propertyResource);
119                                 createNew = true;
120                         }
121             Layer0 L0 = Layer0.getInstance(graph);
122                         if(createNew) {
123                                 propertyResource = graph.newResource();
124                                 graph.claim(container, predicate, propertyResource);
125                                 graph.claim(propertyResource, L0.InstanceOf, STR.SCLValue);                             
126                         }
127                         graph.claimLiteral(propertyResource, L0.SCLValue_expression, expression, Bindings.STRING);
128                 }
129
130                 private void clearExpression(WriteGraph graph, Variable context) throws DatabaseException {
131                         Variable parent = context.getParent(graph);
132                         if(!(parent instanceof AbstractPropertyVariable)) return;
133                         AbstractPropertyVariable property = (AbstractPropertyVariable)parent;
134                         Resource container = property.getContainerResource(graph);
135                         if(container == null) return;
136                         Resource predicate = property.getPossiblePredicateResource(graph);
137                         if(predicate == null) return;                   
138                         graph.deny(container, predicate);               
139                 }
140
141                 @Override
142                 public Object getValue(ReadGraph graph, Variable context)
143                                 throws DatabaseException {
144                         Variable parent = context.getParent(graph);
145                         if(!(parent instanceof AbstractPropertyVariable))
146                                 return null;
147                         AbstractPropertyVariable property = (AbstractPropertyVariable)parent;
148                         Resource propertyResource = property.getPossibleRepresents(graph);
149                         if(propertyResource == null) return null;
150                         StructuralResource2 STR = StructuralResource2.getInstance(graph);
151                         if(!graph.isInstanceOf(propertyResource, STR.SCLValue))
152                                 return null;
153             Layer0 L0 = Layer0.getInstance(graph);
154                         return graph.getPossibleRelatedValue(propertyResource, L0.SCLValue_expression);
155                 }
156                 
157         };
158         
159         @SCLValue(type="ValueAccessor")
160         public static final ValueAccessor connectionValueAccessor = new ValueAccessor() {
161
162                 @Override
163                 public void setValue(WriteGraph graph, Variable context, Object value) throws DatabaseException {
164                         throw new UnsupportedOperationException();
165                 }
166                 
167                 public void setValue(WriteGraph graph, Variable context, Object value, Binding binding) throws DatabaseException {
168                         throw new UnsupportedOperationException();
169                 }
170
171                 public Object getValue(ReadGraph graph, Variable context, Binding binding) throws DatabaseException {
172             try {
173                 Object value = getValue(graph, context);
174                 Binding srcBinding = Bindings.OBJECT.getContentBinding(value);
175                                 return Bindings.adapt(value, srcBinding, binding);
176                         } catch (AdaptException e) {
177                                 throw new DatabaseException(e);
178                         } catch (BindingException e) {
179                                 throw new DatabaseException(e);
180                         }
181                 }
182
183                 @Override
184                 public Object getValue(ReadGraph graph, Variable context) throws DatabaseException {
185                         StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context; 
186                         return new ConnectionImpl(context.getParent(graph), variable.property.predicate);
187                 }
188
189                 @Override
190                 public Datatype getDatatype(ReadGraph graph, Variable context) throws DatabaseException {
191                         try {
192                                 return Datatypes.getDatatype(Connection.class);
193                         } catch (DatatypeConstructionException e) {
194                                 throw new DatabaseException(e);
195                         }
196                 }
197                 
198         };      
199
200
201         @SCLValue(type = "VariableMap")
202         public static VariableMap structuralChildDomainProperties = new VariableMapImpl() {
203         
204                 public Variable getPossibleConnectionPointFromContext(ReadGraph graph, Variable variable, Resource context, String name) throws DatabaseException {
205
206                         Map<String, PropertyInfo> connectionPoints = graph.syncRequest(new ConnectionPointMapOfResource(graph, context), TransientCacheAsyncListener.<Map<String,PropertyInfo>>instance());
207                         PropertyInfo cp = connectionPoints.get(name);
208                         if(cp == null) return null;
209                         else return new StandardGraphPropertyVariable(graph, variable, cp.predicate);
210                         
211                 }
212                 
213                 public Map<String, Variable> collectConnectionPointsFromContext(ReadGraph graph, StructuralResource2 STR, Variable variable, Resource context, Map<String, Variable> map, boolean needSynchronized) throws DatabaseException {
214                         
215                         if(graph.isImmutable(context)) {
216
217                                 Map<String, PropertyInfo> cps = graph.syncRequest(new ConnectionPointMapOfResource(graph, context), TransientCacheAsyncListener.<Map<String,PropertyInfo>>instance());
218                                 if(cps.size() == 0) return map;
219                                 
220                                 if(map == null) map = new THashMap<String,Variable>(cps.size());
221                                 
222                                 for(Map.Entry<String, PropertyInfo> entry : cps.entrySet()) {
223                                         String name = entry.getKey();
224                                         PropertyInfo cp = entry.getValue();
225                                         if(needSynchronized && !graph.isInstanceOf(cp.predicate, STR.SynchronizedConnectionRelation)) continue;
226                                         map.put(name, new StandardGraphPropertyVariable(graph, variable, cp.predicate));
227                                 }
228                                 
229                                 return map;
230
231                         } else {
232                                 
233                                 Collection<Resource> predicates = graph.getPredicates(context);
234                                 
235                                 for(Resource predicate : predicates) {
236                                         
237                                         PropertyInfo info = graph.isImmutable(predicate) ?
238                                                         graph.syncRequest(new PossibleConnectionPointInfo(predicate), TransientCacheAsyncListener.<PropertyInfo>instance()) :
239                                                                 graph.syncRequest(new PossibleConnectionPointInfo(predicate));
240                                                         
241                                         if(info != null) {
242                                                 if(map == null) map = new THashMap<String,Variable>(4);
243                                                 if(needSynchronized && !graph.isInstanceOf(predicate, STR.SynchronizedConnectionRelation)) continue;
244                                                 map.put(info.name, new StandardGraphPropertyVariable(graph, variable, predicate));
245                                         }
246                                         
247                                 }
248
249                                 return map;
250
251                         }
252                         
253                 }
254
255                 @Override
256                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
257                 final StandardGraphChildVariable variable = (StandardGraphChildVariable)context;
258                 Variable cp = getPossibleConnectionPointFromContext(graph, variable, variable.resource, name);
259                 if(cp != null) return cp;
260             return All.getStandardChildDomainPropertyVariable(graph, context, name);
261                 }
262
263                 @Override
264                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
265                 StandardGraphChildVariable variable = (StandardGraphChildVariable)context;
266                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
267                 map = collectConnectionPointsFromContext(graph, STR, variable, variable.resource, map, false);
268             return All.getStandardChildDomainPropertyVariables(graph, context, map);
269                 }
270                 
271                 public Map<String,Variable> getVariables(ReadGraph graph, Variable context, String classification, Map<String,Variable> map) throws DatabaseException {
272                         if (StructuralResource2.URIs.SynchronizedRelation.equals(classification)) {
273                                 return All.getStandardChildDomainPropertyVariables(graph, context, classification, map);
274                         } else if (StructuralResource2.URIs.SynchronizedConnectionRelation.equals(classification)) {
275                         StandardGraphChildVariable variable = (StandardGraphChildVariable)context;
276                         return collectConnectionPointsFromContext(graph, StructuralResource2.getInstance(graph), variable, variable.resource, map, true);
277                         } else if(StructuralResource2.URIs.ConnectionRelation.equals(classification)) {
278                         StandardGraphChildVariable variable = (StandardGraphChildVariable)context;
279                         return collectConnectionPointsFromContext(graph, StructuralResource2.getInstance(graph), variable, variable.resource, map, false);
280                         }
281                         return super.getVariables(graph, context, classification, map);
282                 }
283                 
284         };
285
286         static class StructuralRunContext extends ResourceRead<Resource> {
287
288                 public StructuralRunContext(Resource resource) {
289                         super(resource);
290                 }
291
292                 @Override
293                 public Resource perform(ReadGraph graph) throws DatabaseException {
294
295                         Layer0 L0 = Layer0.getInstance(graph);
296                         SimulationResource SIMU = SimulationResource.getInstance(graph);
297                         Resource model = graph.sync(new PossibleIndexRoot(resource));
298                         if(graph.isInstanceOf(model, L0.RVIContext)) {
299                                 return model;
300                         }
301                         Resource configuration = graph.getPossibleObject(model, SIMU.HasConfiguration);
302                         if(configuration != null) {
303                                 if(graph.isInstanceOf(configuration, L0.RVIContext)) {
304                                         return configuration;
305                                 }
306                         }
307
308                         return null;
309
310                 }
311                 
312         }
313         
314         private static class SubstructureRequest extends VariableRead<List<SubstructureElement>> {
315             public SubstructureRequest(Variable context) {
316             super(context);
317         }
318
319         @Override
320         public List<SubstructureElement> perform(ReadGraph graph) {
321             try {
322                 Resource type = variable.getPossibleType(graph);
323                 if(type == null)
324                     return null;
325                 return CompileProceduralComponentTypeRequest.compileAndEvaluate(graph, type, variable);
326             } catch (Throwable t) {
327                 t.printStackTrace();
328                 return null;
329             }
330         }
331         }
332
333     public static List<SubstructureElement> getProceduralDesc(ReadGraph graph, final Variable context) throws DatabaseException {
334         StructuralResource2 STR = StructuralResource2.getInstance(graph);
335         final Resource type = context.getPossibleType(graph);
336         if(type != null) {
337             if(graph.isInstanceOf(type, STR.ProceduralComponentType)) {
338                 return graph.syncRequest(new SubstructureRequest(context));
339             }
340         }
341         return null;
342     }  
343         
344          public static Map<String,Variable> getProcedural(ReadGraph graph, Variable context, List<SubstructureElement> elements, Map<String,Variable> map) throws DatabaseException {
345              
346          if(map == null) map = new THashMap<String,Variable>();
347          
348          MapList<String,org.simantics.structural2.procedural.Connection> conns = new MapList<String,org.simantics.structural2.procedural.Connection>();
349          for(SubstructureElement sub : elements) {
350              if(sub instanceof org.simantics.structural2.procedural.Connection) {
351                  org.simantics.structural2.procedural.Connection conn = (org.simantics.structural2.procedural.Connection)sub;
352                  for(ConnectionPoint cp : conn.connectionPoints) {
353                      if(cp instanceof Terminal) {
354                          Terminal t = (Terminal)cp;
355                          conns.add(t.component, conn);
356                      }
357                  }
358              }
359          }
360          
361          Map<String,Component> proceduralChildren = new THashMap<String, Component>();
362          for(SubstructureElement sub : elements) {
363              if(sub instanceof Component) {
364                  Component comp = (Component)sub;
365                  proceduralChildren.put(comp.name, comp);
366              }
367          }
368          
369          Collection<Object> nodeChildren = All.getPossibleNodeChildren(graph, (AbstractChildVariable)context);
370          Set<String> used = new HashSet<String>(nodeChildren.size());
371          for(Object nodeChild : nodeChildren) {
372              @SuppressWarnings("rawtypes")
373              NodeSupport support = ((AbstractChildVariable)context).node.support;
374              @SuppressWarnings("rawtypes")
375              NodeManager manager = support.manager;
376              @SuppressWarnings("unchecked")
377              String name = manager.getName(nodeChild);
378              used.add(name);
379              Component proceduralChild = proceduralChildren.get(name); 
380              if(proceduralChild != null) {
381                  map.put(proceduralChild.name, new StandardProceduralChildVariable(graph, context, new VariableNode(support, nodeChild), proceduralChild.name, proceduralChild.type, proceduralChild.properties, conns.getValues(proceduralChild.name)));
382              }
383          }
384          
385          for(Map.Entry<String, Component> entry : proceduralChildren.entrySet()) {
386              String name = entry.getKey();
387              if(used.contains(name)) continue;
388              Component proceduralChild = entry.getValue();
389              map.put(proceduralChild.name, new StandardProceduralChildVariable(graph, context, null, proceduralChild.name, proceduralChild.type, proceduralChild.properties, conns.getValues(proceduralChild.name)));
390          }
391          
392          return map;
393              
394      }  
395          
396          private static class ProceduralSubstructureRequest extends VariableRead<Map<String,Variable>> {
397
398              public ProceduralSubstructureRequest(Variable variable) {
399                  super(variable);
400              }
401
402              @Override
403              public Map<String, Variable> perform(ReadGraph graph)
404                      throws DatabaseException {
405                  List<SubstructureElement> elements = getProceduralDesc(graph, variable);
406                  if(elements != null)
407                      return getProcedural(graph, variable, elements, null);
408                  else
409                      return null;
410              }
411          }
412          
413         public static class StructuralTypeOverrideMap extends ResourceRead<Map<Resource,Resource>> {
414
415                 protected StructuralTypeOverrideMap(Resource composite) {
416                         super(composite);
417                 }
418
419                 @Override
420                 public Map<Resource, Resource> perform(ReadGraph graph) throws DatabaseException {
421                         
422                         Layer0 L0 = Layer0.getInstance(graph);
423                         
424                         StructuralResource2 STR = StructuralResource2.getInstance(graph);
425                         
426                         CollectionSupport cs = graph.getService(CollectionSupport.class);
427                         
428                         Map<Resource,Resource> result = null;
429                         
430                         for(Resource override : graph.getObjects(resource, STR.HasTypeOverride)) {
431                                 Resource original = graph.getSingleObject(override, STR.TypeOverride_HasOriginalType);
432                                 Resource replacement = graph.getSingleObject(override, STR.TypeOverride_HasReplacementType);
433                                 if(result == null) result = cs.createMap(Resource.class);
434                                 result.put(original, replacement);
435                         }
436                         
437                         if(result == null) return Collections.emptyMap();
438                         
439                         return result;
440                         
441                 }
442                 
443         }
444         
445         public static class StructuralOverrideData {
446                 @Override
447                 public int hashCode() {
448                         final int prime = 31;
449                         int result = 1;
450                         result = prime * result + ((actualRepresents == null) ? 0 : actualRepresents.hashCode());
451                         result = prime * result + ((actualType == null) ? 0 : actualType.hashCode());
452                         result = prime * result + ((overrideType == null) ? 0 : overrideType.hashCode());
453                         return result;
454                 }
455                 @Override
456                 public boolean equals(Object obj) {
457                         if (this == obj)
458                                 return true;
459                         if (obj == null)
460                                 return false;
461                         if (getClass() != obj.getClass())
462                                 return false;
463                         StructuralOverrideData other = (StructuralOverrideData) obj;
464                         if (actualRepresents == null) {
465                                 if (other.actualRepresents != null)
466                                         return false;
467                         } else if (!actualRepresents.equals(other.actualRepresents))
468                                 return false;
469                         if (actualType == null) {
470                                 if (other.actualType != null)
471                                         return false;
472                         } else if (!actualType.equals(other.actualType))
473                                 return false;
474                         if (overrideType == null) {
475                                 if (other.overrideType != null)
476                                         return false;
477                         } else if (!overrideType.equals(other.overrideType))
478                                 return false;
479                         return true;
480                 }
481                 Resource actualRepresents;
482                 Resource actualType;
483                 Resource overrideType;
484                 public StructuralOverrideData(Resource actualRepresents, Resource actualType, Resource overrideType) {
485                         this.actualRepresents = actualRepresents;
486                         this.actualType = actualType;
487                         this.overrideType = overrideType;
488                 }
489
490                 public static StructuralOverrideData compute(ReadGraph graph, Variable context) throws DatabaseException {
491                         return graph.syncRequest(new StructuralOverrideDataRequest(context));
492                 }
493                 
494                 public Resource type() {
495                         if(overrideType != null)
496                                 return overrideType;
497                         return actualType;
498                 }
499
500                 public Resource represents() {
501                         return actualRepresents;
502                 }
503
504         }
505
506     private static class StructuralOverrideDataWalkRequest
507             extends TernaryRead<Variable, Resource, Resource, StructuralOverrideData> {
508
509         public StructuralOverrideDataWalkRequest(Variable component, Resource actualRepresents, Resource actualType) {
510             super(component, actualRepresents, actualType);
511         }
512
513         @Override
514         public StructuralOverrideData perform(ReadGraph graph) throws DatabaseException {
515             Variable component = parameter;
516             Resource actualRepresents = parameter2;
517             Resource actualType = parameter3;
518 //            System.err.println(component.getURI(graph));
519             Resource represents = component.getPossibleRepresents(graph);
520             if (represents != null) {
521                 Layer0 L0 = Layer0.getInstance(graph);
522                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
523                 Resource container = graph
524                         .syncRequest(new PossibleObjectWithType(represents, L0.PartOf, STR.Composite));
525                 if (container != null) {
526                     Map<Resource, Resource> overrides = graph.syncRequest(new StructuralTypeOverrideMap(container), TransientCacheListener.instance());
527                     Resource override = overrides.get(actualType);
528                     if (override != null) {
529                         return new StructuralOverrideData(actualRepresents, actualType, override);
530                     }
531                 }
532             }
533             Variable parent = component.getParent(graph);
534             if (parent == null)
535                 return new StructuralOverrideData(actualRepresents, actualType, null);
536             else
537                 return graph.syncRequest(new StructuralOverrideDataWalkRequest(parent, represents, actualType), TransientCacheListener.instance());
538         }
539
540     }
541
542         public static class StructuralOverrideDataRequest extends VariableRead<StructuralOverrideData> {
543
544                 public StructuralOverrideDataRequest(Variable component) {
545                         super(component);
546                 }
547                 
548                 @Override
549                 public StructuralOverrideData perform(ReadGraph graph) throws DatabaseException {
550
551                 Resource represents = variable.getPossibleRepresents(graph);
552                 if(represents == null) {
553                         String uri = variable.getPossiblePropertyValue(graph, "typeURI");
554                         if(uri != null) {
555                                 Resource actualType = graph.syncRequest(new org.simantics.db.common.primitiverequest.Resource(uri), TransientCacheAsyncListener.<Resource>instance());
556                                 if (graph.syncRequest(new IsInstanceOf(actualType, StructuralResource2.getInstance(graph).ReplaceableDefinedComponentType), TransientCacheListener.instance()) ) {
557                                     return graph.syncRequest(new StructuralOverrideDataWalkRequest(variable, null, actualType), TransientCacheListener.instance());
558                                 } else {
559                                     // can not have replaceable type 
560                                     return null;
561                                 }
562                         }
563                         throw new DatabaseException("No type for " + variable.getURI(graph));
564                 } else {
565                     Resource possibleType = graph.getPossibleType(represents, Layer0.getInstance(graph).Entity);
566                     if (graph.syncRequest(new IsInstanceOf(possibleType, StructuralResource2.getInstance(graph).ReplaceableDefinedComponentType), TransientCacheListener.instance()) ) {
567                         return graph.syncRequest(new StructuralOverrideDataWalkRequest(variable, represents, possibleType), TransientCacheListener.instance());
568                     } else {
569                         return null;
570                     }
571                 }
572                         
573                 }
574                 
575         }
576
577
578     private static class StructureTypeAndChildMapRequest extends ResourceRead<Tuple2> {
579
580         protected StructureTypeAndChildMapRequest(Resource resource) {
581             super(resource);
582         }
583
584         @Override
585         public Tuple2 perform(ReadGraph graph) throws DatabaseException {
586             StructuralComponentClass clazz = StructuralComponentClass.get(graph, resource);
587             if (StructuralComponentClass.DEFINED.equals(clazz)) {
588                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
589                 Resource def = graph.getSingleObject(resource, STR.IsDefinedBy);
590                 Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(def), TransientCacheListener.instance());
591                 return new Tuple2(clazz, children);
592             }
593             return new Tuple2(clazz, null);
594         }
595         
596     }
597
598         @SCLValue(type = "VariableMap")
599         public static VariableMap structuralChildDomainChildren = new VariableMapImpl() {
600
601                 @Override
602                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
603                         
604                         Resource type = context.getPossibleType(graph);
605                         if(type == null) return null;
606                     
607                         Tuple2 result = graph.syncRequest(new StructureTypeAndChildMapRequest(type), TransientCacheListener.instance());
608                         StructuralComponentClass clazz = (StructuralComponentClass) result.c0;
609                         
610                         if(StructuralComponentClass.PROCEDURAL.equals(clazz)) {
611                     Map<String,Variable> map = graph.syncRequest(new ProceduralSubstructureRequest(context),
612                         TransientCacheListener.<Map<String,Variable>>instance());
613                     if(map != null) return map.get(name);
614                     return null;
615                         } else if (StructuralComponentClass.DEFINED.equals(clazz)) {
616                             Map<String, Resource> children = (Map<String, Resource>) result.c1;
617                 Resource child = children.get(name);
618                 if(child == null) return null;
619                 return StandardChildDomainChildren.getStandardChildDomainChildVariable(graph, context, child, name);
620                         } else {
621                                 Resource represents = context.getPossibleRepresents(graph);
622                                 if(represents == null) return null;
623                 Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(represents), TransientCacheListener.instance());
624                 Resource child = children.get(name);
625                 return StandardChildDomainChildren.getStandardChildDomainChildVariable(graph, context, child, name);
626                         }
627
628                 }
629
630                 @Override
631                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
632                         
633                         Resource type = context.getPossibleType(graph);
634                         if(type == null) return null;
635                         
636                         StructuralComponentClass clazz = StructuralComponentClass.get(graph, type);
637                         if(StructuralComponentClass.PROCEDURAL.equals(clazz)) {
638                 Map<String,Variable> mapPrime = graph.syncRequest(new ProceduralSubstructureRequest(context),
639                                 TransientCacheListener.<Map<String,Variable>>instance());
640                 if(mapPrime != null) {
641                         if(map != null) {
642                                 map.putAll(mapPrime);
643                                 return map;
644                         }
645                         else
646                                 return mapPrime;
647                 }
648                 return map;
649                         } else if (StructuralComponentClass.DEFINED.equals(clazz)) {
650                                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
651                                 Resource def = graph.getSingleObject(type, STR.IsDefinedBy);
652                 Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(def), TransientCacheListener.instance());
653                 return StandardChildDomainChildren.getStandardChildDomainChildVariables(graph, context, children, map);
654                         } else {
655                                 Resource represents = context.getPossibleRepresents(graph);
656                                 if(represents == null) return null;
657                 Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(represents));
658                 return StandardChildDomainChildren.getStandardChildDomainChildVariables(graph, context, children, map);
659                         }
660             
661                 }
662                 
663         };
664         
665         @SCLValue(type = "VariableMap")
666         public static VariableMap structuralRunDomainChildren = new VariableMapImpl() {
667         
668                 @Override
669                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
670                         Resource ctx = graph.syncRequest(new StructuralRunContext(context.getRepresents(graph)));
671                         if(ctx == null) return null;
672                     Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(ctx));
673                         Resource child = children.get(name);
674             return StandardChildDomainChildren.getStandardChildDomainChildVariable(graph, context, child, name);
675                 }
676
677                 @Override
678                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
679                         Resource ctx = graph.syncRequest(new StructuralRunContext(context.getRepresents(graph)));
680                         if(ctx == null) return map;
681                     Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(ctx));
682                     return StandardChildDomainChildren.getStandardChildDomainChildVariables(graph, context, children, map);
683                 }
684                 
685         };
686
687         @SCLValue(type = "ReadGraph -> [Resource] -> [Resource]")
688     public static List<Resource> connectionExtension(ReadGraph graph, List<Resource> rs) throws DatabaseException {
689
690         StructuralResource2 STR = StructuralResource2.getInstance(graph);
691         HashSet<Resource> extension = new HashSet<Resource>(8);
692         for(Resource r : rs) {
693                 if(graph.isInstanceOf(r, STR.Connection)) {
694                         extension.addAll(graph.syncRequest(new ConnectionComponents(r), TransientCacheListener.<Collection<Resource>>instance()));
695                 }
696                 if(graph.isInstanceOf(r, STR.ConnectionJoin)) {
697                         extension.addAll(graph.syncRequest(new ConnectionJoinComponents(r), TransientCacheListener.<Collection<Resource>>instance()));
698                 }
699         }
700
701         HashSet<Resource> components = new HashSet<Resource>(8);
702         for(Resource r : extension) {
703                 components.addAll(graph.sync(new ObjectsWithType(r, STR.Connects, STR.Component)));
704         }
705         
706         if(!extension.isEmpty()) {
707                 ArrayList<Resource> result = new ArrayList<Resource>(rs.size() + extension.size());
708                 result.addAll(rs);
709                 result.addAll(extension);
710                 result.addAll(components);
711                 rs = result;
712         }
713         
714         return rs;
715         
716     }
717
718         @SCLValue(type = "ReadGraph -> Resource -> [Issue]")
719     public static List<Issue> connectionValidator(ReadGraph graph, Resource component) throws DatabaseException {
720         
721                 if(!graph.hasStatement(component)) return Collections.emptyList();
722
723                 ArrayList<Issue> result = new ArrayList<Issue>();
724                 
725                 Layer0 L0 = Layer0.getInstance(graph);
726                 StructuralResource2 sr = StructuralResource2.getInstance(graph);
727
728                 Resource type = graph.getSingleType(component, sr.Component);
729                 
730                 Set<Resource> requiredConnections = new HashSet<Resource>();
731                 for(Resource connectionRelation : graph.sync(new ObjectsWithType(type, L0.ConsistsOf, sr.ConnectionRelation))) {
732                         Boolean required = graph.getPossibleRelatedValue(connectionRelation, sr.ConnectionRelation_connectionRequired, Bindings.BOOLEAN);
733                         if(required != null && required)
734                                 requiredConnections.add(connectionRelation);
735                 }
736                 
737                 Set<Resource> connections = new HashSet<Resource>();
738
739                 for(Statement stm : graph.getStatements(component, sr.IsConnectedTo)) {
740                         connections.add(stm.getPredicate());
741                         connections.addAll(graph.getSuperrelations(stm.getPredicate()));
742                 }
743
744                 for(Resource req : requiredConnections) {
745                         if(!connections.contains(req)) {
746                                 result.add(new StandardIssue(sr.ConnectionConstraint_ErrorIssue, component, req));
747                         }
748                 }
749
750                 return result;
751         
752     }
753
754     @SCLValue(type = "ReadGraph -> Resource -> Variable -> String")
755     public static String connectionIssueDescription(ReadGraph graph, Resource converter, Variable property) throws DatabaseException {
756         List<Resource> contexts = IssueUtils.getContextsForProperty(graph, property);
757         String attributeName = graph.getRelatedValue(contexts.get(1), Layer0.getInstance(graph).HasName);
758         return "'" + attributeName + "' should be connected.";
759     }
760
761     public static class InterfacePathMap extends VariableRead<GraphMap<Map<String,InterfaceResolution>>> {
762
763                 public InterfacePathMap(Variable context) {
764                         super(context);
765                 }
766
767                 @Override
768                 public GraphMap<Map<String,InterfaceResolution>> perform(ReadGraph graph) throws DatabaseException {
769
770                         return new GraphMap<Map<String,InterfaceResolution>>() {
771
772                                 @Override
773                                 Map<String, InterfaceResolution> get(ReadGraph graph, String key) throws DatabaseException {
774                                         
775                                         Variable child = variable.getChild(graph, key);
776                                         
777                                         Map<String,InterfaceResolution> childMap = new THashMap<String,InterfaceResolution>();
778                                         Collection<InterfaceResolution> paths = computeInterfacePaths(graph, child);//child.getPossiblePropertyValue(graph, "proceduralConnectionPointPath");
779                                         if(paths != null) {
780                                                 for(InterfaceResolution r : paths) {
781                                                         childMap.put(r.interfaceName, r);
782                                                 }
783                                         }
784                                         return childMap;
785
786                                 }
787                                 
788                         };
789                         
790                 }
791         
792     }
793     
794     public static String resolveInterfacePath(ReadGraph graph, Variable context, String component, Resource relation) throws DatabaseException {
795         
796         GraphMap<Map<String,InterfaceResolution>> map = graph.syncRequest(new InterfacePathMap(context), TransientCacheListener.<GraphMap<Map<String,InterfaceResolution>>>instance());
797         Map<String,InterfaceResolution> childMap = map.get(graph, component);
798         if(childMap == null) return "";
799
800         PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(relation), TransientCacheListener.<PropertyInfo>instance());
801
802         InterfaceResolution match = childMap.get(info.name);
803         if(match != null) {
804                 String comp = URIStringUtils.escape(component);
805                 Variable newContext = context.getChild(graph, component);
806                 return "/" + comp + resolveInterfacePath(graph, newContext, match.componentName, match.connectionPoint);
807         } else {
808                 return "/" + URIStringUtils.escape(component) + "#" + URIStringUtils.escape(info.name); 
809         }
810                 
811     }
812     
813     public static class InterfaceResolution {
814         
815         public Resource interfaceConnectionPoint;
816         public String interfaceName;
817         public String componentName;
818         public Resource connectionPoint;
819         
820         public InterfaceResolution(Resource interfaceConnectionPoint, String interfaceName, String componentName, Resource connectionPoint) {
821                 this.interfaceConnectionPoint = interfaceConnectionPoint;
822                 this.interfaceName = interfaceName;
823                 this.componentName = componentName;
824                 this.connectionPoint = connectionPoint;
825         }
826         
827     }
828     
829     public static Collection<InterfaceResolution> computeInterfacePaths(ReadGraph graph, Variable variable) throws DatabaseException {
830
831                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
832                 Resource type = variable.getPossibleType(graph);
833                 if(type != null) {
834                         if(graph.isInstanceOf(type, STR.ProceduralComponentType)) {
835                                 ArrayList<InterfaceResolution> result = new ArrayList<InterfaceResolution>();
836                                 List<SubstructureElement> elements = getProceduralDesc(graph, variable); 
837                                 if(elements != null) {
838                                         for(SubstructureElement e : elements) {
839                                                 if(e instanceof org.simantics.structural2.procedural.Connection) {
840                                                         org.simantics.structural2.procedural.Connection conn = (org.simantics.structural2.procedural.Connection)e;
841                                                         Interface inf = null;
842                                                         for(ConnectionPoint cp : conn.connectionPoints) {
843                                                                 if(cp instanceof Interface) {
844                                                                         if(inf != null) throw new DatabaseException("Multiple interfaces referenced in procedural connection.");
845                                                                         inf = (Interface)cp;
846                                                                 }
847                                                         }
848                                                         if(inf != null && conn.connectionPoints.size() > 1) {
849                                                                 Layer0 L0 = Layer0.getInstance(graph);
850                                                                 String cpName = URIStringUtils.escape( graph.<String>getRelatedValue(inf.relation, L0.HasName, Bindings.STRING) );
851                                                                 for(ConnectionPoint cp : conn.connectionPoints) {
852                                                                         if(cp == inf) continue;
853                                                                         Terminal t = (Terminal)cp;
854                                                                         result.add(new InterfaceResolution(inf.relation, cpName, t.component, t.relation));
855                                                                 }
856                                                         }
857                                                 }
858                                         }
859                                 }
860
861                                 return result;
862                                 
863                         }
864
865                         final Collection<InterfaceResolution> interfaces = graph.syncRequest(new DefinedUCInterfaceMap(type), TransientCacheListener.instance());
866                         if(interfaces != null) return interfaces;
867
868                 }
869                 
870                 return BUILTIN_STRUCTURAL_CPS;
871         
872     }
873     
874     static class InterfacePathRequest extends VariableRead<Collection<InterfaceResolution>> {
875
876                 public InterfacePathRequest(Variable variable) {
877                         super(variable);
878                 }
879                 
880                 @Override
881                 public Collection<InterfaceResolution> perform(ReadGraph graph) throws DatabaseException {
882                         return computeInterfacePaths(graph, variable);
883                 }
884         
885     }
886     
887     public static final Collection<InterfaceResolution> BUILTIN_STRUCTURAL_CPS = new ArrayList<InterfaceResolution>();
888
889         @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
890     public static Object computeExpression(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
891         return CompileStructuralValueRequest.compileAndEvaluate(graph, context);
892     }
893
894     public static Object computeExpressionInContext(ReadGraph graph, Variable context, final String expression) throws DatabaseException {
895         SCLContext sclContext = SCLContext.getCurrent();
896         Object oldGraph = sclContext.get("graph");
897         try {
898             Function1<Object,Object> exp = graph.syncRequest(new CompileStructuralValueRequest(graph, context) {
899                 protected String getExpressionText(ReadGraph graph) throws DatabaseException {
900                     return expression;
901                 }
902             },
903             TransientCacheListener.instance());
904             sclContext.put("graph", graph);
905             return exp.apply(context);
906         } catch (DatabaseException e) {
907             throw (DatabaseException)e;
908         } catch (Throwable t) {
909             throw new DatabaseException(t);
910         } finally {
911             sclContext.put("graph", oldGraph);
912         }
913     }    
914         
915         static abstract class InterfacePathProperty extends LazyPropertyVariable {
916                 
917                 public InterfacePathProperty(Variable parent) {
918                         super(parent, "proceduralConnectionPointPath", Bindings.STRING_ARRAY);
919                 }
920                 
921                 @Override
922                 public <T> T getValue(ReadGraph graph, Binding binding) throws DatabaseException {
923                         return getValue(graph);
924                 }
925                 
926         }
927         
928         static abstract class GraphMap<Value> {
929                 
930                 abstract Value get(ReadGraph graph, String key) throws DatabaseException;
931                 
932         }
933     
934 }