1 package org.simantics.district.network.ui.function;
3 import java.util.Collections;
4 import java.util.HashMap;
7 import java.util.stream.Collectors;
9 import org.eclipse.jface.dialogs.Dialog;
10 import org.eclipse.jface.layout.GridDataFactory;
11 import org.eclipse.swt.SWT;
12 import org.eclipse.swt.events.SelectionAdapter;
13 import org.eclipse.swt.events.SelectionEvent;
14 import org.eclipse.swt.layout.GridData;
15 import org.eclipse.swt.layout.GridLayout;
16 import org.eclipse.swt.widgets.Combo;
17 import org.eclipse.swt.widgets.Composite;
18 import org.eclipse.swt.widgets.Control;
19 import org.eclipse.swt.widgets.Group;
20 import org.eclipse.swt.widgets.Label;
21 import org.eclipse.swt.widgets.Shell;
22 import org.eclipse.ui.PlatformUI;
23 import org.eclipse.ui.dialogs.SelectionStatusDialog;
24 import org.simantics.NameLabelUtil;
25 import org.simantics.Simantics;
26 import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;
27 import org.simantics.browsing.ui.common.modifiers.Enumeration;
28 import org.simantics.browsing.ui.graph.impl.GraphEnumerationModifier;
29 import org.simantics.databoard.Bindings;
30 import org.simantics.db.ReadGraph;
31 import org.simantics.db.Resource;
32 import org.simantics.db.Session;
33 import org.simantics.db.WriteGraph;
34 import org.simantics.db.common.request.IndexRoot;
35 import org.simantics.db.common.request.ObjectsWithType;
36 import org.simantics.db.common.request.ReadRequest;
37 import org.simantics.db.common.request.WriteRequest;
38 import org.simantics.db.exception.DatabaseException;
39 import org.simantics.db.exception.RuntimeDatabaseException;
40 import org.simantics.db.exception.ServiceException;
41 import org.simantics.db.layer0.variable.Variable;
42 import org.simantics.db.layer0.variable.Variables.Role;
43 import org.simantics.db.procedure.Procedure;
44 import org.simantics.diagram.stubs.DiagramResource;
45 import org.simantics.district.network.ontology.DistrictNetworkResource;
46 import org.simantics.layer0.Layer0;
47 import org.simantics.modeling.ModelingResources;
48 import org.simantics.modeling.ModelingUtils;
49 import org.simantics.modeling.adapters.NewCompositeActionFactory;
50 import org.simantics.modeling.typicals.TypicalUtil;
51 import org.simantics.scl.reflection.annotations.SCLValue;
52 import org.simantics.structural.stubs.StructuralResource2;
53 import org.simantics.ui.workbench.action.DefaultActions;
54 import org.simantics.utils.ui.SWTUtils;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public class Functions {
60 private static final Logger LOGGER = LoggerFactory.getLogger(Functions.class);
65 private static class HasMappingEnumerationModifier extends GraphEnumerationModifier {
67 public HasMappingEnumerationModifier(Session session, Resource subject, Resource relation, Enumeration<Resource> enumeration, Resource value) {
68 super(session, subject, relation, enumeration, value);
73 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
74 public static Object defaultEdgeMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
75 Resource diagram = resolveElement(graph, context);
76 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
77 return baseMappingModifier(graph, diagram, DN.EdgeDefaultMapping, DN.Mapping_EdgeMapping, context);
80 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
81 public static Object defaultVertexMappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
82 System.out.println(graph.getURI(resource));
83 System.out.println(context.getURI(graph));
85 Resource diagram = resolveElement(graph, context);
86 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
87 return baseMappingModifier(graph, diagram, DN.VertexDefaultMapping, DN.Mapping_VertexMapping, context);
90 @SCLValue(type = "ReadGraph -> Resource -> Variable -> b")
91 public static Object mappingModifier(ReadGraph graph, Resource resource, final Variable context) throws DatabaseException {
93 Resource element = resolveElement(graph, context);
94 Resource mappingType = resolveMappingType(graph, element);
95 return baseMappingModifier(graph, element, DistrictNetworkResource.getInstance(graph).HasMapping, mappingType, context);
98 public static Map<String, Resource> getVertexMappings(ReadGraph graph, Resource resource) throws DatabaseException {
99 Map<String, Resource> second = getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_VertexMapping);
103 public static Map<String, Resource> getEdgeMappings(ReadGraph graph, Resource resource) throws DatabaseException {
104 Map<String, Resource> second = getNetworkMappingsByType(graph, resource , DistrictNetworkResource.getInstance(graph).Mapping_EdgeMapping);
108 public static Map<String, Resource> getCRSs(ReadGraph graph, Resource resource) throws DatabaseException {
109 Map<String, Resource> result = getNetworkMappingsByType(graph, resource, DistrictNetworkResource.getInstance(graph).SpatialRefSystem);
114 public static Map<String, Resource> getNetworkMappingsByType(ReadGraph graph, Resource element, Resource mappingType) throws DatabaseException {
115 Resource indexRoot = graph.sync(new IndexRoot(element));
116 List<Resource> mappings = ModelingUtils.searchByType(graph, indexRoot, mappingType);
117 Map<String, Resource> result = new HashMap<>(mappings.size());
118 Layer0 L0 = Layer0.getInstance(graph);
119 mappings.forEach(mapping -> {
121 String name = graph.getRelatedValue2(mapping, L0.HasName);
122 result.put(name, mapping);
123 } catch (DatabaseException e) {
130 private static Object baseMappingModifier(ReadGraph graph, Resource element, Resource property, Resource mappingType, Variable context) throws DatabaseException {
131 Resource indexRoot = graph.sync(new IndexRoot(element));
132 List<Resource> mappings = ModelingUtils.searchByType(graph, indexRoot, mappingType);
133 Enumeration<Resource> enums = Enumeration
134 .make(mappings.stream().map(m -> createEnumeratedValue(graph, m)).collect(Collectors.toList()));
136 Resource currentMapping = graph.getSingleObject(element, property);
138 return new HasMappingEnumerationModifier(Simantics.getSession(), element, property, enums, currentMapping);
141 private static Resource resolveMappingType(ReadGraph graph, Resource element) throws DatabaseException {
142 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
143 if (graph.isInstanceOf(element, DN.Edge))
144 return DN.Mapping_EdgeMapping;
145 else if (graph.isInstanceOf(element, DN.Vertex))
146 return DN.Mapping_VertexMapping;
147 throw new IllegalStateException("No mapping type found for element " + element + " : " + graph.getPossibleURI(element));
150 private static Resource resolveElement(ReadGraph graph, Variable variable) throws DatabaseException {
151 Role role = variable.getPossibleRole(graph);
152 if (role.equals(Role.PROPERTY))
153 return resolveElement(graph, variable.getParent(graph));
155 return variable.getRepresents(graph);
158 private static EnumeratedValue<Resource> createEnumeratedValue(ReadGraph graph, Resource resource) {
160 String label = NameLabelUtil.modalName(graph, resource);
161 return new EnumeratedValue<Resource>(label, resource);
162 } catch (DatabaseException e) {
163 throw new RuntimeDatabaseException(e);
167 @SCLValue(type = "ReadGraph -> Resource -> a -> b")
168 public static Object enumerationValues(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
169 Variable var = (Variable) context;
170 System.out.println(graph.getURI(resource));
171 System.out.println(var.getURI(graph));
172 return Collections.emptyList();
175 @SCLValue(type = "ReadGraph -> Resource -> a -> b")
176 public static Object convertToValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
177 return graph.getRelatedValue2(resource, Layer0.getInstance(graph).HasName, Bindings.STRING);
182 @SCLValue(type = "Resource -> String -> Resource -> Resource")
183 public static Resource compositeInstantiator(final Resource compositeType, final String defaultName, final Resource target) throws DatabaseException {
185 return TypicalUtil.syncExec(procedure -> {
186 if (!SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), () -> {
188 queryInitialValuesAndCreateComposite(compositeType, target, defaultName, procedure);
189 } catch (Throwable t) {
190 procedure.exception(t);
193 procedure.execute(null);
198 private static class DefaultMappingsDialog extends SelectionStatusDialog {
200 private Combo vertexMappingCombo;
201 private Combo edgeMappingCombo;
202 private Combo crsCombo;
203 private Composite composite;
205 private Resource configuration;
206 private Map<String, Resource> vertexMappings = new HashMap<>();
207 private Map<String, Resource> edgeMappings = new HashMap<>();
208 private Map<String, Resource> composites = new HashMap<>();
209 private Map<String, Resource> crss = new HashMap<>();
210 private Map<String, Map<String, Resource>> components = new HashMap<>();
212 private Resource defaultVertexMapping;
213 private Resource defaultEdgeMapping;
214 private Resource defaultCRS;
216 private Combo compositeMappingCombo;
217 private Combo componentMappingCombo;
219 protected DefaultMappingsDialog(Shell parentShell, Resource configuration) {
221 this.configuration = configuration;
222 setTitle("Select mappings for new DN diagram");
225 public Resource getDefaultVertexMapping() {
226 return defaultVertexMapping;
229 public Resource getDefaultEdgeMapping() {
230 return defaultEdgeMapping;
234 protected Control createDialogArea(Composite parent) {
235 composite = (Composite) super.createDialogArea(parent);
237 createMappingsGroup(composite);
238 createExistingCompositeGroup(composite);
239 createCRSSettingsGroup(composite);
241 // compute default values
242 Simantics.getSession().asyncRequest(new ReadRequest() {
245 public void run(ReadGraph graph) throws DatabaseException {
247 vertexMappings = getVertexMappings(graph, configuration);
248 edgeMappings = getEdgeMappings(graph, configuration);
250 composites = getComposites(graph, configuration);
251 if (composites.size() > 0) {
252 components = getComponents(graph, composites.get(0));
255 crss = getCRSs(graph, configuration);
257 composite.getDisplay().asyncExec(() -> {
259 vertexMappingCombo.setItems(vertexMappings.keySet().toArray(new String[vertexMappings.size()]));
260 edgeMappingCombo.setItems(edgeMappings.keySet().toArray(new String[edgeMappings.size()]));
262 crsCombo.setItems(crss.keySet().toArray(new String[crss.size()]));
264 compositeMappingCombo.setItems(composites.keySet().toArray(new String[composites.size()]));
265 vertexMappingCombo.select(0);
266 edgeMappingCombo.select(0);
270 if (!composites.isEmpty())
271 compositeMappingCombo.select(0);
279 protected Map<String, Map<String, Resource>> getComponents(ReadGraph graph, Resource resource) {
280 // TODO Auto-generated method stub
284 protected Map<String, Resource> getComposites(ReadGraph graph, Resource element) throws DatabaseException {
286 Resource indexRoot = graph.sync(new IndexRoot(element));
287 List<Resource> diagrams = ModelingUtils.searchByType(graph, indexRoot, DiagramResource.getInstance(graph).Diagram);
289 List<Resource> nonDistrictComposites = composites.values().stream().filter(comp -> {
291 return !graph.isInstanceOf(comp, DistrictNetworkResource.getInstance(graph).Composite);
292 } catch (ServiceException e1) {
293 LOGGER.error("Could not check if composite " + comp + " is instanceOf DistrictNetwork.composite");
296 }).collect(Collectors.toList());
297 Map<String, Resource> result = new HashMap<>(nonDistrictComposites.size());
298 Layer0 L0 = Layer0.getInstance(graph);
299 nonDistrictComposites.forEach(mapping -> {
301 String name = graph.getRelatedValue2(mapping, L0.HasName);
302 result.put(name, mapping);
303 } catch (DatabaseException e) {
304 LOGGER.error("Could not read name of " + mapping, e);
310 private void createMappingsGroup(Composite parent) {
311 Group group= new Group(parent, SWT.NONE);
312 group.setFont(parent.getFont());
313 group.setText("Default mappings");
314 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
315 group.setLayout(new GridLayout(1, false));
317 Composite cmposite = new Composite(group, SWT.NONE);
318 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
319 cmposite.setLayout(new GridLayout(2, false));
321 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
322 vertexMappingLabel.setText("Default vertex mapping");
324 vertexMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
325 GridDataFactory.fillDefaults().grab(true, false).applyTo(vertexMappingCombo);
327 Label edgeMappingLabel = new Label(cmposite, SWT.NONE);
328 edgeMappingLabel.setText("Default edge mapping");
330 edgeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
331 GridDataFactory.fillDefaults().grab(true, false).applyTo(edgeMappingCombo);
334 private void createExistingCompositeGroup(Composite parent) {
335 Group group= new Group(parent, SWT.NONE);
336 group.setFont(parent.getFont());
337 group.setText("Mapped composite");
338 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
339 group.setLayout(new GridLayout(1, false));
341 Composite cmposite = new Composite(group, SWT.NONE);
342 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
343 cmposite.setLayout(new GridLayout(2, false));
345 Label compositeMappingLabel = new Label(cmposite, SWT.NONE);
346 compositeMappingLabel.setText("Select composite");
348 compositeMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
349 GridDataFactory.fillDefaults().grab(true, false).applyTo(compositeMappingCombo);
350 compositeMappingCombo.addSelectionListener(new SelectionAdapter() {
353 public void widgetSelected(SelectionEvent e) {
354 super.widgetSelected(e);
355 recalculateMappapleComponents();
359 Label compojnentMappingLabel = new Label(cmposite, SWT.NONE);
360 compojnentMappingLabel.setText("Select component");
362 componentMappingCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
363 GridDataFactory.fillDefaults().grab(true, false).applyTo(componentMappingCombo);
366 protected void recalculateMappapleComponents() {
367 Simantics.getSession().asyncRequest(new ReadRequest() {
370 public void run(ReadGraph graph) throws DatabaseException {
373 composite.getDisplay().asyncExec(() -> {
380 private void createCRSSettingsGroup(Composite parent) {
381 Group group= new Group(parent, SWT.NONE);
382 group.setFont(parent.getFont());
383 group.setText("CRS settings");
384 GridDataFactory.fillDefaults().grab(true, false).applyTo(group);
385 group.setLayout(new GridLayout(1, false));
387 Composite cmposite = new Composite(group, SWT.NONE);
388 cmposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
389 cmposite.setLayout(new GridLayout(2, false));
391 Label vertexMappingLabel = new Label(cmposite, SWT.NONE);
392 vertexMappingLabel.setText("Default CRS");
394 crsCombo = new Combo(cmposite, SWT.READ_ONLY | SWT.BORDER);
395 GridData textData = new GridData(SWT.FILL, SWT.CENTER, true, false);
396 crsCombo.setLayoutData(textData);
401 protected void computeResult() {
402 defaultVertexMapping = vertexMappings.get(vertexMappingCombo.getItem(vertexMappingCombo.getSelectionIndex()));
403 defaultEdgeMapping = edgeMappings.get(edgeMappingCombo.getItem(edgeMappingCombo.getSelectionIndex()));
404 defaultCRS = crss.get(crsCombo.getItem(crsCombo.getSelectionIndex()));
407 public Resource getCRS() {
413 private static void queryInitialValuesAndCreateComposite(final Resource compositeType, final Resource target,
414 String defaultName, final Procedure<Resource> procedure) {
415 DefaultMappingsDialog dialog = new DefaultMappingsDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), target);
417 if (dialog.open() != Dialog.OK) {
418 procedure.execute(null);
421 Simantics.getSession().asyncRequest(
422 NewCompositeActionFactory.createCompositeRequest(target, defaultName, compositeType),
423 new Procedure<Resource>() {
425 public void execute(Resource composite) {
426 Simantics.getSession().asyncRequest(new WriteRequest() {
429 public void perform(WriteGraph graph) throws DatabaseException {
430 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
431 Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
432 graph.claim(diagram, DN.EdgeDefaultMapping, dialog.getDefaultEdgeMapping());
433 graph.claim(diagram, DN.VertexDefaultMapping, dialog.getDefaultVertexMapping());
434 graph.claim(diagram, DN.HasSpatialRefSystem, dialog.getCRS());
437 DefaultActions.asyncPerformDefaultAction(Simantics.getSession(), composite, false, false, true);
438 procedure.execute(composite);
442 public void exception(Throwable t) {
443 LOGGER.error("Failed to create composite, see exception for details.", t);
444 procedure.exception(t);