]> gerrit.simantics Code Review - simantics/platform.git/commitdiff
Merge "Include disconnected flag terminals for connection judgement"
authorTuukka Lehtonen <tuukka.lehtonen@semantum.fi>
Fri, 6 Sep 2019 13:29:10 +0000 (13:29 +0000)
committerGerrit Code Review <gerrit2@simantics>
Fri, 6 Sep 2019 13:29:10 +0000 (13:29 +0000)
44 files changed:
bundles/org.simantics.browsing.ui.graph.impl/src/org/simantics/browsing/ui/graph/impl/EnumerationVariableModifier3.java
bundles/org.simantics.browsing.ui.graph.impl/src/org/simantics/browsing/ui/graph/impl/GetEnumerationValue.java
bundles/org.simantics.db.common/src/org/simantics/db/common/validation/L0Validations.java
bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/request/PropertyInfo.java
bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/request/PropertyInfoRequest.java
bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/Layer0Utils.java
bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/variable/StandardGraphPropertyVariable.java
bundles/org.simantics.db.testing/META-INF/MANIFEST.MF
bundles/org.simantics.db.testing/src/org/simantics/db/testing/base/SCLScriptTestBase.java
bundles/org.simantics.db.testing/src/org/simantics/db/testing/cases/FreshDatabaseTest.java
bundles/org.simantics.db.testing/src/org/simantics/db/testing/cases/FreshWorkspaceTest.java
bundles/org.simantics.db.testing/src/org/simantics/db/testing/common/AcornTestHandler.java
bundles/org.simantics.db.testing/src/org/simantics/db/testing/common/TestBase.java
bundles/org.simantics.diagram.connection/src/org/simantics/diagram/connection/RouteGraph.java
bundles/org.simantics.document.swt.core/src/org/simantics/document/swt/core/base/PostEventCommand.java
bundles/org.simantics.document.swt.core/src/org/simantics/document/swt/core/widget/ButtonWidget.java
bundles/org.simantics.document.swt.core/src/org/simantics/document/swt/core/widget/CommandEventWidget.java
bundles/org.simantics.document.swt.ontology/graph/Components.pgraph
bundles/org.simantics.issues.common/src/org/simantics/issues/common/AllActiveIssues.java
bundles/org.simantics.issues.ui/src/org/simantics/issues/ui/handler/RunActiveValidations.java
bundles/org.simantics.modeling.ontology/graph/ModelingViewpoint.pgraph
bundles/org.simantics.modeling.ui/scl/Simantics/Testing/BrowseContext.scl
bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/componentTypeEditor/ComponentTypeViewer.java
bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/componentTypeEditor/ComponentTypeViewerData.java
bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/diagram/style/IssueDecorationStyle.java
bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/diagramEditor/OpenDiagramFromComponentAdapter.java
bundles/org.simantics.modeling/adapters.xml
bundles/org.simantics.modeling/scl/Simantics/Ontologies.scl
bundles/org.simantics.modeling/scl/Simantics/Rename.scl
bundles/org.simantics.modeling/src/org/simantics/modeling/Rename.java
bundles/org.simantics.modeling/src/org/simantics/modeling/adapters/SCLCheckedStateRule.java [new file with mode: 0644]
bundles/org.simantics.modeling/src/org/simantics/modeling/adapters/SCLChildRule.java
bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/rules/PageSettingsTypicalRule.java
bundles/org.simantics.modeling/src/org/simantics/modeling/userComponent/ComponentTypeCommands.java
bundles/org.simantics.platform.ui.ontology/META-INF/MANIFEST.MF
bundles/org.simantics.platform.ui.ontology/build.properties
bundles/org.simantics.platform.ui.ontology/graph/PlatformUI.pgraph
bundles/org.simantics.platform.ui.ontology/graph/ValidationView.pgraph [new file with mode: 0644]
bundles/org.simantics.platform.ui.ontology/scl/Simantics/PlatformUI.scl [moved from bundles/org.simantics.platform.ui.ontology/graph/scl/SCLMain.scl with 54% similarity]
bundles/org.simantics.scenegraph.profile/src/org/simantics/scenegraph/profile/common/ObserverGroupListener.java
bundles/org.simantics.scl.db/src/org/simantics/scl/db/SCLFunctions.java
bundles/org.simantics.scl.runtime/scl/Prelude.scl
bundles/org.simantics.selectionview/src/org/simantics/selectionview/function/All.java
bundles/org.simantics/src/org/simantics/SimanticsPlatform.java

index 3bd3e7b91217ef5233388158c88f86e8bb24abdc..52b5012d72b504a3a1f64757dcc50fc66081a36b 100644 (file)
@@ -57,7 +57,7 @@ public class EnumerationVariableModifier3 implements EnumerationModifier {
                 public String perform(ReadGraph graph) throws DatabaseException {
                     EnumerationValue<Resource> ev = graph.syncRequest(new GetEnumerationValue(variable.getParent(graph).getRepresents(graph)));
                     if(ev != null) {
-                           return ev.getEnumeratedValue().getName();
+                        return ev.getEnumeratedValue().getName();
                     }
           //           System.err.println(variable.getURI(graph));
                        return variable.getValue(graph);//variable.getPossiblePropertyValue(graph, Variables.LABEL);
index 9e8adfebea1fa65805c66078c0794e14a49ffec1..0f9d119aca3400a7cd6fbb32ff866514c0de50a8 100644 (file)
@@ -41,7 +41,7 @@ public class GetEnumerationValue extends ResourceRead<EnumerationValue<Resource>
     public EnumerationValue<Resource> perform(ReadGraph graph) throws DatabaseException {
         return enumerate(graph, resource);
     }
-    
+
     public static String getEnumerationValueName(ReadGraph graph, Resource resource) throws DatabaseException {
         Layer0 L0 = Layer0.getInstance(graph);
         String label = graph.getPossibleRelatedValue(resource, L0.HasLabel, Bindings.STRING);
index 99ef91b7aa0040815b23a4dae559fa1ad3d7d6dd..1ff6e5fbcd6fecbb53a6dd17b6b2c6e86459c8ca 100644 (file)
@@ -12,7 +12,7 @@ import org.simantics.scl.compiler.types.Type;
 public class L0Validations {
 
        public static String checkValueType(ReadGraph graph, Resource subject, Resource predicate) throws DatabaseException {
-               
+
                if (subject == null)
                        return null;
                if (predicate == null)
@@ -25,9 +25,34 @@ public class L0Validations {
                        String valueTypeText = graph.getPossibleRelatedValue(predicate, L0.RequiresValueType, Bindings.STRING);
                        if(valueTypeText != null) {
                                Type valueType = CommonDBUtils.getSCLType(graph, subject, valueTypeText);
+                               if(valueType == null) {
+                                       Resource range = graph.getPossibleObject(predicate, L0.HasRange);
+                                       if(range != null) {
+                                               return null;
+                                       } else {
+                                               StringBuilder sb = new StringBuilder()
+                                                               .append("The value type ")
+                                                               .append(valueType)
+                                                               .append(" of predicate ")
+                                                               .append(NameUtils.getSafeName(graph, predicate, true))
+                                                               .append(" cannot be resolved.")
+                                                               .append(NameUtils.getSafeName(graph, object, true))
+                                                               .append(".");
+                                               return sb.toString();
+                                       }
+                               }
                                String valueTypeText2 = graph.getPossibleRelatedValue(object, L0.HasValueType, Bindings.STRING);
                                if(valueTypeText2 != null) {
                                        Type valueType2 = CommonDBUtils.getSCLType(graph, subject, valueTypeText2);
+                                       if(valueType2 == null) {
+                                               StringBuilder sb = new StringBuilder()
+                                                               .append("The value type ")
+                                                               .append(valueType2)
+                                                               .append(" of object ")
+                                                               .append(NameUtils.getSafeName(graph, object, true))
+                                                               .append(" cannot be resolved.");
+                                               return sb.toString();
+                                       }
                                        if(!valueType.equals(valueType2)) {
                                                StringBuilder sb = new StringBuilder()
                                                                .append("The value type ")
@@ -44,9 +69,9 @@ public class L0Validations {
                                }
                        }
                }
-               
+
                return null;
-               
+
        }
-       
+
 }
index f3753ce80bfc3949c84914c234c14f76520c29e4..4d208b4571d14faaac8772dc30e3e0df241d1ef9 100644 (file)
@@ -1,3 +1,14 @@
+/*******************************************************************************
+ * Copyright (c) 2019 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     Semantum Oy - initial API and implementation
+ *******************************************************************************/
 package org.simantics.db.layer0.request;
 
 import java.util.Collection;
@@ -20,6 +31,7 @@ public class PropertyInfo {
        public final Resource predicate;
        public final String name;
        public final boolean isHasProperty;
+       public final boolean isFunctional;
        public final Set<String> classifications;
        public final VariableBuilder builder;
        public final Resource literalRange;
@@ -30,9 +42,10 @@ public class PropertyInfo {
        public final Map<String,Pair<Resource, ChildReference>> subliteralPredicates;
        public final ValueAccessor valueAccessor;
        public final boolean hasEnumerationRange;
-       public PropertyInfo(Resource predicate, String name, boolean isHasProperty, Set<String> classifications, VariableBuilder builder, Resource literalRange, Datatype requiredDatatype, String definedUnit, String requiredValueType, Binding defaultBinding, Map<String,Pair<Resource, ChildReference>> subliteralPredicates, ValueAccessor valueAccessor, boolean hasEnumerationRange) {
+       public PropertyInfo(Resource predicate, String name, boolean isFunctional, boolean isHasProperty, Set<String> classifications, VariableBuilder builder, Resource literalRange, Datatype requiredDatatype, String definedUnit, String requiredValueType, Binding defaultBinding, Map<String,Pair<Resource, ChildReference>> subliteralPredicates, ValueAccessor valueAccessor, boolean hasEnumerationRange) {
                this.predicate = predicate;
                this.name = name;
+               this.isFunctional = isFunctional;
                this.isHasProperty = isHasProperty;
                this.classifications = classifications;
                this.builder = builder;
@@ -45,7 +58,7 @@ public class PropertyInfo {
                this.valueAccessor = valueAccessor;
                this.hasEnumerationRange = hasEnumerationRange;
        }
-       public static PropertyInfo make(ReadGraph graph, Resource predicate, String name, boolean isHasProperty, Set<String> classifications, VariableBuilder builder, Resource literalRange, Datatype requiredDatatype, String definedUnit, String requiredValueType, Map<String,Pair<Resource, ChildReference>> subliteralPredicates, ValueAccessor valueAccessor, boolean hasEnumerationRange) throws DatabaseException {
+       public static PropertyInfo make(ReadGraph graph, Resource predicate, String name, boolean isFunctional, boolean isHasProperty, Set<String> classifications, VariableBuilder builder, Resource literalRange, Datatype requiredDatatype, String definedUnit, String requiredValueType, Map<String,Pair<Resource, ChildReference>> subliteralPredicates, ValueAccessor valueAccessor, boolean hasEnumerationRange) throws DatabaseException {
 
                Layer0 L0 = Layer0.getInstance(graph);
                if(literalRange != null) {
@@ -58,7 +71,7 @@ public class PropertyInfo {
                
                Binding defaultBinding = requiredDatatype != null ? Bindings.getBinding(requiredDatatype) : null;
                
-               return new PropertyInfo(predicate, name, isHasProperty, classifications, builder, literalRange, requiredDatatype, definedUnit, requiredValueType, defaultBinding, subliteralPredicates, valueAccessor, hasEnumerationRange);
+               return new PropertyInfo(predicate, name, isFunctional, isHasProperty, classifications, builder, literalRange, requiredDatatype, definedUnit, requiredValueType, defaultBinding, subliteralPredicates, valueAccessor, hasEnumerationRange);
 
        }
        public boolean hasClassification(String classification) {
@@ -75,6 +88,8 @@ public class PropertyInfo {
                .append(requiredValueType)
                .append(", predicate=")
                .append(predicate)
+               .append(", isFunctional=")
+               .append(isFunctional)
                .append(", isHasProperty=")
                .append(isHasProperty)
                .append(", hasEnumerationRange=")
index 2a181674c49a3cdf06f0317bcb382c5bbe002221..90e63e29f639c10cc7d4ec04caf053c0909116e6 100644 (file)
@@ -41,6 +41,8 @@ final public class PropertyInfoRequest extends ResourceRead<PropertyInfo> {
                String name = graph.getPossibleRelatedValue(resource, L0.HasName, Bindings.STRING);
                if(name != null) name = name.intern();
                
+               boolean isFunctional = graph.isInstanceOf(resource, L0.FunctionalRelation);
+               
                Set<String> classifications = graph.sync(new ClassificationsRequest(graph.getPrincipalTypes(resource)));
                VariableBuilder<?> variableBuilder = graph.getPossibleAdapter(resource, VariableBuilder.class);
                
@@ -88,13 +90,13 @@ final public class PropertyInfoRequest extends ResourceRead<PropertyInfo> {
                                                }
                                        }
                                        
-                                       return PropertyInfo.make(graph, resource, name, isHasProperty, classifications, variableBuilder, literalRange, requiredDataType, definedUnit, requiredValueType, map, accessor, hasEnumerationRange);
+                                       return PropertyInfo.make(graph, resource, name, isFunctional, isHasProperty, classifications, variableBuilder, literalRange, requiredDataType, definedUnit, requiredValueType, map, accessor, hasEnumerationRange);
                                        
                                }
                        }
                }
                
-               return PropertyInfo.make(graph, resource, name, isHasProperty, classifications, variableBuilder, literalRange, requiredDataType, definedUnit, requiredValueType, Collections.<String,Pair<Resource,ChildReference>>emptyMap(), accessor, hasEnumerationRange);
+               return PropertyInfo.make(graph, resource, name, isFunctional, isHasProperty, classifications, variableBuilder, literalRange, requiredDataType, definedUnit, requiredValueType, Collections.<String,Pair<Resource,ChildReference>>emptyMap(), accessor, hasEnumerationRange);
                
        }
        
index 610c8c8bd42d8735868cf1f80e4603ae5e63b7d8..830f7a6bb74776ece6a99b35eb3b9b51999cc10a 100644 (file)
@@ -71,7 +71,6 @@ import org.simantics.db.common.primitiverequest.PossibleRelatedValue;
 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
 import org.simantics.db.common.request.DelayedWriteRequest;
 import org.simantics.db.common.request.ObjectsWithType;
-import org.simantics.db.common.request.PossibleChild;
 import org.simantics.db.common.request.PossibleIndexRoot;
 import org.simantics.db.common.request.WriteRequest;
 import org.simantics.db.common.utils.CommonDBUtils;
@@ -116,9 +115,7 @@ import org.simantics.graph.representation.PrettyPrintTG;
 import org.simantics.graph.representation.TransferableGraph1;
 import org.simantics.layer0.Layer0;
 import org.simantics.operation.Layer0X;
-import org.simantics.scl.compiler.environment.Environments;
 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
-import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
 import org.simantics.scl.compiler.types.Type;
 import org.simantics.scl.osgi.SCLOsgi;
 import org.simantics.scl.runtime.function.Function;
@@ -1382,6 +1379,41 @@ public class Layer0Utils {
        return result;
     }
 
+    public static Resource possibleObjectForType(ReadGraph graph, Resource type, Resource relation) throws DatabaseException {
+        PropertyInfo pi = graph.syncRequest(new PropertyInfoRequest(relation));
+        return possibleObjectForType(graph, type, relation, pi.isFunctional);
+    }
+
+    public static Resource possibleObjectForType(ReadGraph graph, Resource type, Resource relation, boolean functional) throws DatabaseException {
+        if(functional) {
+            Layer0 L0 = Layer0.getInstance(graph);
+            Resource result = graph.getPossibleObject(type, relation);
+            if(result != null)
+                return result;
+            for(Resource su : graph.getObjects(L0.Inherits, type)) {
+                Resource r = possibleObjectForType(graph, su, relation, functional);
+                if(r != null) {
+                    if(result != null)
+                        return null;
+                    result = r;
+                }
+            }
+            return result;
+        } else {
+            Set<Resource> found = objectsForTypeNonFunctional(graph, type, relation, new HashSet<>());
+            return found.size() == 1 ? found.iterator().next() : null;
+        }
+    }
+
+    private static Set<Resource> objectsForTypeNonFunctional(ReadGraph graph, Resource type, Resource relation, Set<Resource> found) throws DatabaseException {
+        Layer0 L0 = Layer0.getInstance(graph);
+        found.addAll(graph.getObjects(type, relation));
+        for(Resource su : graph.getObjects(L0.Inherits, type)) {
+            objectsForTypeNonFunctional(graph, su, relation, found);
+        }
+        return found;
+    }
+
     public static Resource getPossiblePredicateByNameFromType(ReadGraph graph, Resource type, String name) throws DatabaseException {
        Map<String,Resource> domain = getDomainOf(graph, type);
        return domain.get(name); 
index ed58556c7e570814bd4ce25e5473a6821f2c33bc..7927614cd37f9779292ee4ace98e5fd4ba7f00f0 100644 (file)
@@ -38,7 +38,7 @@ public class StandardGraphPropertyVariable extends AbstractPropertyVariable {
     private static final Logger LOGGER = LoggerFactory.getLogger(StandardGraphPropertyVariable.class);
     
        protected static final PropertyInfo NO_PROPERTY = new PropertyInfo(null, null,
-                       false, Collections.<String> emptySet(), null, null, null, null, null, null,
+                       false, false, Collections.<String> emptySet(), null, null, null, null, null, null,
                        Collections.<String, Pair<Resource, ChildReference>> emptyMap(),
                        null, false);
 
index c80729ad86e094b385e0bbcc010c0e7192ef5c23..960ccf0095f1c8eb88811244a48594bf8e1588f7 100644 (file)
@@ -8,17 +8,18 @@ Bundle-RequiredExecutionEnvironment: JavaSE-1.8
 Require-Bundle: org.simantics.db.layer0;bundle-version="1.1.0",
  org.simantics.graph.db;bundle-version="1.1.5";visibility:=reexport,
  org.simantics.project;bundle-version="1.0.1";visibility:=reexport,
- org.apache.log4j;bundle-version="1.2.15",
  org.simantics.db.procore;bundle-version="1.1.1",
  org.simantics.db.services;bundle-version="1.1.0",
  org.eclipse.core.runtime;bundle-version="3.6.0",
  org.simantics.workbench;bundle-version="1.1.0",
  org.simantics.db.management;bundle-version="1.1.0",
+ org.simantics.db.indexing;bundle-version="1.1.0",
  org.simantics;bundle-version="1.0.0";visibility:=reexport,
  org.simantics.scl.osgi;bundle-version="1.0.4",
  org.junit;bundle-version="4.12.0",
  org.simantics.db.server,
- org.apache.commons.math3
+ org.apache.commons.math3,
+ org.slf4j.api;bundle-version="1.7.25"
 Export-Package: org.simantics.db.testing.annotation,
  org.simantics.db.testing.base,
  org.simantics.db.testing.cases,
index 26e916fc1bcdfa53ed8f0076155b33b3d7bf603e..511af6dc3d3ec05e5646d25ed872e06d57740b0c 100644 (file)
@@ -19,21 +19,24 @@ import org.simantics.scl.osgi.SCLOsgi;
 import org.simantics.scl.osgi.internal.Activator;
 import org.simantics.scl.osgi.internal.ServiceBasedModuleSourceRepository;
 import org.simantics.scl.osgi.internal.ServiceBasedTestRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import gnu.trove.map.hash.THashMap;
 
 /**
  * Utilizies {@link TestRepository} for collecting SCL tests from bundles
  * 
- * @author Jani
- *
+ * @author Jani Simomaa
  */
 public class SCLScriptTestBase extends FreshDatabaseTest {
 
+    private static final Logger LOGGER = LoggerFactory.getLogger(SCLScriptTestBase.class);
+
     private Map<String, TestRunnable> testRunnables = new THashMap<String, TestRunnable>();
-    
+
     @Rule public TestName testName = new TestName();
-    
+
     /**
      * Constructor that initially searches for all SCL test scripts and stores
      * them into a Map for later access
@@ -47,14 +50,14 @@ public class SCLScriptTestBase extends FreshDatabaseTest {
             testRunnables.put(runnable.getName(), runnable);
         }
     }
-    
+
     /**
      * Simplest method for running a SCL test
      */
     protected void test() {
         test(-1);
     }
-    
+
     /**
      * Executes a test case with given timeout as seconds. When time runs out one
      * can assume a deadlock has happened. The process is killed after the timeout
@@ -65,7 +68,7 @@ public class SCLScriptTestBase extends FreshDatabaseTest {
     protected void test(int timeout) {
         testImpl(timeout);
     }
-    
+
     /**
      * Executes a test case with given timeout as seconds
      * 
@@ -75,45 +78,57 @@ public class SCLScriptTestBase extends FreshDatabaseTest {
         SCLOsgi.SOURCE_REPOSITORY = new ServiceBasedModuleSourceRepository(Activator.getContext());
         SCLOsgi.MODULE_REPOSITORY = new ModuleRepository(SCLOsgi.SOURCE_REPOSITORY);
         SCLOsgi.TEST_REPOSITORY = new ServiceBasedTestRepository(Activator.getContext());
-                
+
         String testName = resolveTestName();
         TestRunnable runnable = testRunnables.get(testName);
-        
+        if (runnable == null) {
+            LOGGER.error("SCL Test Suite file (.sts) for test {} cannot be found from test repository.", testName);
+            return;
+        }
+
+        long start = System.nanoTime(); 
         if (timeout > -1) {
+            LOGGER.info("Running test {} with a timeout of {} seconds", testName, timeout); //$NON-NLS-1$
             Timer timer = new Timer();
             timer.schedule(new TimerTask() {
 
                 @Override
                 public void run() {
+                    LOGGER.info("Watchdog will kill this test process because it has been executing for over {} seconds", timeout); //$NON-NLS-1$
                     String processName = ManagementFactory.getRuntimeMXBean().getName();
-                    System.out.println("PID: " + processName);
+                    LOGGER.info("Test Process Name: {}", processName); //$NON-NLS-1$
                     String PID = processName.split("@")[0];
                     String command = "taskkill /F /PID " + PID;
-                    System.out.println("Command: " + command);
+                    LOGGER.info("Running command to kill test process: {}", command); //$NON-NLS-1$
                     try {
                         Runtime.getRuntime().exec(command);
                     } catch (IOException e) {
-                        e.printStackTrace();
+                        LOGGER.error("Failed to kill process that ran over its execution time limit of {} seconds", timeout, e);
                     }
                 }
                 
             }, timeout*1000);
             try {
                 runnable.run();
+                long end = System.nanoTime();
+                LOGGER.info("Completed test {} execution in {} seconds", testName, String.format("%.3f", (end-start)*1e-9)); //$NON-NLS-1$
             } catch (Exception e) {
-                e.printStackTrace();
+                LOGGER.error("Failed to run test {} runnable {}", testName, runnable, e);
             } finally {
                 timer.cancel();
             }
         } else {
+            LOGGER.info("Running test {} without timeout", testName); //$NON-NLS-1$
             try {
                 runnable.run();
+                long end = System.nanoTime();
+                LOGGER.info("Completed test {} execution in {} seconds", testName, String.format("%.3f", (end-start)*1e-9)); //$NON-NLS-1$
             } catch (Exception e) {
-                e.printStackTrace();
+                LOGGER.error("Failed to run test {} runnable {}", testName, runnable, e);
             }
         }
     }
-    
+
     /**
      * Resolves the full test name based on the names of classes that extends this
      * SCLScriptTestBase class.<br><br>
index 963b2d9f5d23af902da80f54221f647c04d9a10e..9ad9faf77a4bc3e2e85c69cd2172ddcd4b27df8f 100644 (file)
@@ -1,4 +1,3 @@
-package org.simantics.db.testing.cases;
 /*******************************************************************************
  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
  * in Industry THTH ry.
@@ -10,7 +9,7 @@ package org.simantics.db.testing.cases;
  * Contributors:
  *     VTT Technical Research Centre of Finland - initial API and implementation
  *******************************************************************************/
-
+package org.simantics.db.testing.cases;
 
 import org.junit.After;
 import org.junit.Before;
@@ -25,20 +24,15 @@ import org.simantics.db.testing.common.Tests;
 public class FreshDatabaseTest extends TestBase {
 
     public void configure(TestSettings settings) {
-
     }
 
     @Before
     public void setUp() throws Exception {
-
         TestBase.printStart(this);
         TestSettings testSettings = TestSettings.getInstanceUnsafe();
         configure(testSettings);
-//        state = AcornTests.newSimanticsWorkspace(testSettings, null);
         state = Tests.newSimanticsWorkspace(testSettings, null);
-
         super.setUp();
-
     }
 
     @After
index 0de0785646f8865d4e020504e0e797ef7a19021a..bc46815502c25952aa6a1815af9cbb0528e41b88 100644 (file)
@@ -8,23 +8,22 @@ import org.simantics.db.testing.common.Tests;
 import org.simantics.db.testing.impl.Configuration;
 
 public class FreshWorkspaceTest extends TestBase {
-       
+
        public void configure(TestSettings settins) {
        }
-       
+
        @Before
        public void setUp() throws Exception {
-               
                TestBase.printStart(this);
                configure(TestSettings.getInstanceUnsafe());
                state = Tests.freshWorkspace(Configuration.get().coreDir, initialWorkspaceFiles);
                super.setUp();
        }
-       
-    @After
-    public void tearDown() throws Exception {
-       
-       Tests.shutdown(state);
-       super.tearDown();
-    }
+
+       @After
+       public void tearDown() throws Exception {
+               Tests.shutdown(state);
+               super.tearDown();
+       }
+
 }
index 5f5da8f2e9d7ac1f746605259d59799d7969ac3a..e7e1722ac6f81aedf60022f60c13f153c7d07a9f 100644 (file)
@@ -1,6 +1,7 @@
 package org.simantics.db.testing.common;
 
 import java.io.File;
+import java.io.IOException;
 import java.util.Properties;
 
 import org.eclipse.core.runtime.Platform;
@@ -10,6 +11,7 @@ import org.simantics.db.Manager;
 import org.simantics.db.ServerI;
 import org.simantics.db.Session;
 import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.indexing.DatabaseIndexing;
 
 /**
  * ProCore specific test handler.
@@ -33,15 +35,27 @@ public class AcornTestHandler {
 
     void initNew() throws DatabaseException {
         Management m = getManagement();
-        if (m.exist())
+        if (m.exist()) {
             m.delete();
+        }
+        deleteIndexes();
         m.create();
     }
 
     void initIfNeccessary() throws DatabaseException {
         Management m = getManagement();
-        if (!m.exist())
+        if (!m.exist()) {
             m.create();
+            deleteIndexes();
+        }
+    }
+
+    private void deleteIndexes() throws DatabaseException {
+        try {
+            DatabaseIndexing.deleteAllIndexes();
+        } catch (IOException e) {
+            throw new DatabaseException("Failed to delete all existing indexes", e);
+        }
     }
 
     public Session getSession() throws DatabaseException {
index 1068fc2f50366ae19a72f8a3029534b86f2c7993..d08caea4c4574a705d6ff49d5588c5f03555e47a 100644 (file)
@@ -27,7 +27,6 @@ import org.simantics.db.Session;
 import org.simantics.db.WriteGraph;
 import org.simantics.db.WriteOnlyGraph;
 import org.simantics.db.common.request.WriteOnlyRequest;
-import org.simantics.db.common.utils.Logger;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.exception.ServiceNotFoundException;
 import org.simantics.db.management.SessionContext;
@@ -38,14 +37,17 @@ import org.simantics.db.service.LifecycleSupport;
 import org.simantics.db.testing.impl.Configuration;
 import org.simantics.layer0.Layer0;
 import org.simantics.utils.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
- * Base class for Simantics Test Cases. Assumes that ProCore is already running.
+ * Base class for Simantics Test Cases.
+ * Assumes that the Simantics database is already running.
  *
  * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
- *
  */
-abstract public class TestBase /*extends TestCase*/ {
+public abstract class TestBase {
+    private static final Logger LOGGER = LoggerFactory.getLogger(TestBase.class);
     public static final boolean DEBUG = Configuration.get().debug;
     public static final String ROOT_LIBRARY_URI = "http:/";
     private NoExitSecurityManager noExitSecurityManager;
@@ -56,7 +58,7 @@ abstract public class TestBase /*extends TestCase*/ {
     static boolean printStart = true;
     public static final ArrayList<String> initialWorkspaceFiles = FileUtils.createFileFilter(Platform.getLocation().toFile(), null);
     public static void printStart(Object t) {
-        if(printStart) System.out.println("Test is " + t.getClass().getName() /*+ "." + t.getName()*/);
+        if(printStart) LOGGER.info("Test class is {}", t.getClass().getName());
     }
     protected static void setPrintStart(boolean value) {
         printStart = value;
@@ -270,9 +272,9 @@ abstract public class TestBase /*extends TestCase*/ {
                 try {
                     session.getService(LifecycleSupport.class).close(0, true);
                 } catch (ServiceNotFoundException e) {
-                    Logger.defaultLogError(e);
+                    LOGGER.error("Failed to find LifecycleSupport service", e);
                 } catch (DatabaseException e) {
-                    Logger.defaultLogError(e);
+                    LOGGER.error("Failed to close database", e);
                 }
             }
 //            if (!Thread.currentThread().equals(thread)) {
index 62d3de68fae5f110a6b08eb80dcc7558ca34df80..249399d0a8b5b7b6c875c68d8464fda198961160 100644 (file)
  *******************************************************************************/
 package org.simantics.diagram.connection;
 
-import gnu.trove.list.array.TDoubleArrayList;
-import gnu.trove.map.hash.THashMap;
-import gnu.trove.map.hash.TObjectIntHashMap;
-import gnu.trove.set.hash.THashSet;
-
 import java.awt.geom.Line2D;
 import java.awt.geom.Path2D;
+import java.awt.geom.Point2D;
 import java.awt.geom.Rectangle2D;
 import java.io.PrintStream;
 import java.io.Serializable;
@@ -34,6 +30,11 @@ import org.simantics.diagram.connection.rendering.arrows.PlainLineEndStyle;
 import org.simantics.diagram.connection.segments.Segment;
 import org.simantics.diagram.connection.splitting.SplittedRouteGraph;
 
+import gnu.trove.list.array.TDoubleArrayList;
+import gnu.trove.map.hash.THashMap;
+import gnu.trove.map.hash.TObjectIntHashMap;
+import gnu.trove.set.hash.THashSet;
+
 public class RouteGraph implements Serializable {
 
     private static final long serialVersionUID = 2004022454972623908L;
@@ -1474,6 +1475,46 @@ public class RouteGraph implements Serializable {
             routeLine.collectSegments(segments);
         return segments;
     }
+    
+    public Segment findNearestSegment(double x, double y) {
+        Segment nearest = null;
+        double minDistanceSq = Double.MAX_VALUE;
+
+        for (Segment segment : getSegments()) {
+            RoutePoint p1 = segment.p1;
+            RoutePoint p2 = segment.p2;
+
+            double distanceSq = Line2D.ptSegDistSq(p1.x, p1.y, p2.x, p2.y, x, y);
+            if (distanceSq < minDistanceSq) {
+                minDistanceSq = distanceSq;
+                nearest = segment;
+            }
+        }
+        return nearest;
+    }
+
+    public Point2D findNearestPoint(double x, double y) {
+        Segment nearest = findNearestSegment(x, y);
+        if (nearest == null) return null;
+
+        RoutePoint p1 = nearest.p1;
+        RoutePoint p2 = nearest.p2;
+
+        double d = Math.pow(p2.x - p1.x, 2.0) + Math.pow(p2.y - p1.y, 2.0);
+
+        if (d == 0) {
+            return new Point2D.Double(p1.x, p1.y);
+        } else {
+            double u = ((x - p1.x) * (p2.x - p1.x) + (y - p1.y) * (p2.y - p1.y)) / d;
+            if (u > 1.0) {
+                return new Point2D.Double(p2.x, p2.y);
+            } else if (u <= 0.0) {
+                return new Point2D.Double(p1.x, p1.y);
+            } else {
+                return new Point2D.Double(p2.x * u + p1.x * (1.0-u), (p2.y * u + p1.y * (1.0- u)));
+            }
+        }
+    }
 
     public Path2D getPath2D() {
         Path2D result = new Path2D.Double();
index 7214bdd1f1691057c25a304621b4112339c9ada9..24b6e6111c41774337c9aec5934decaf7c3da8d7 100644 (file)
@@ -13,6 +13,7 @@ package org.simantics.document.swt.core.base;
 
 import org.simantics.document.server.io.AbstractEventHandler;
 import org.simantics.document.server.io.CommandContext;
+import org.simantics.document.server.io.CommandContextImpl;
 import org.simantics.document.server.io.CommandContextMutable;
 import org.simantics.document.swt.core.SWTDocument;
 
@@ -27,6 +28,7 @@ public class PostEventCommand extends AbstractEventCommand {
     
     public PostEventCommand(SWTDocument document, AbstractEventHandler handler, CommandContextMutable context, PostEventCommand next) {
         super(document);
+        assert(handler != null);
         this.handler = handler;
         this.context = context;
         this.next = next;
@@ -34,7 +36,9 @@ public class PostEventCommand extends AbstractEventCommand {
 
     @Override
     public CommandContext handleCommand(CommandContextMutable context) {
-        document.post(handler, context);
+        CommandContextMutable mergedContext = new CommandContextImpl().merge(context)
+                .merge(this.context);
+        document.post(handler, mergedContext);
         return context;
     }
 
index 72c7c360b0566529d0941f58557ed9cd93d4c4eb..88afe7b2ab802bcc235952bdaa6d42766f2cf68a 100644 (file)
@@ -75,6 +75,7 @@ public class ButtonWidget extends LeafWidgetManager<Button> {
             List<ICommand> commands = object.getJSONField("commands");
             HashSet<Object> listeners = new HashSet<Object>();
             List<Pair<WidgetData, ICommand>> data = new ArrayList<>();
+            data.addAll(SWTViews.getTriggeredCommands(document, commands, "click"));
             data.addAll(SWTViews.getTriggeredCommands(document, commands, "eventOut"));
             data.add(new Pair<WidgetData, ICommand>(wd, new Command("onPress")));
             SelectionListener listener = new ButtonSelectionListener(wd, data);
@@ -102,6 +103,7 @@ public class ButtonWidget extends LeafWidgetManager<Button> {
         if("onPress".equals(command.getCommand())) {
             CommandContextMutable context = new CommandContextImpl().merge(p);
             AbstractEventHandler onPress = object.getJSONField("onPress");
+            if(onPress == null) return null;
             return new PostEventCommand(document, onPress, context);
         }
         return null;
index efded8810e0bb738e4e6ed93d7b18490bf882f93..ca6c31ddffdf8e5a565bf3d71f49d41edb7a267f 100644 (file)
@@ -52,6 +52,7 @@ public class CommandEventWidget  extends PropertyWidgetManager<Object> {
             List<DataDefinition> dataDefinitions = object.getJSONField("dataDefinitions");
             CommandContextMutable context = new CommandContextImpl();
             context.merge(p);
+            context.merge(command.getConstants());
             for(DataDefinition dd : dataDefinitions) {
                 WidgetData wd = document.getWidgetData().get(dd.getElementId());
                 if(wd != null && wd.object != null) {
index e577e6c5dadda5e00469d9acdf757ad6b10e2af8..b255c4f2b4bd53863bd6e6471e3e5014d33c3cea 100644 (file)
@@ -47,6 +47,8 @@ COMPONENTS.Component <T DOC.Components.PrimitiveComponent
     @SWT.defAttribute L0.Value "Boolean"
   >-- COMPONENTS.Component.NoScroll
     @SWT.defAttribute L0.Value "Boolean"
+  >-- COMPONENTS.Component.Check
+    @SWT.defAttribute L0.Value "Boolean"
   >-- COMPONENTS.Component.alignment
     @SWT.defAttribute L0.Value "String"
         
@@ -190,6 +192,8 @@ COMPONENTS.Explorer <T COMPONENTS.Component
     @SWT.defAttribute L0.Value "String"
   >-- COMPONENTS.Explorer.dragSourceListenerFactory
     @SWT.defAttribute L0.Value "DragSourceListenerFactory"
+  >-- COMPONENTS.Explorer.onCheck
+    @SWT.defAttribute L0.Value "AbstractEventHandler"
 
   @attribute COMPONENTS.Explorer.browseContext
     ""
index 006e779d47cb105311e11bf66906ca2c1c4de85a..1bb292851111226453f0e0a3f187d6893a570e60 100644 (file)
@@ -47,7 +47,7 @@ public class AllActiveIssues extends ResourceRead<Set<Resource>> {
             result.addAll(graph.syncRequest(new AllModelIssues(model, false)));
         }
 
-        List<Resource> libraries = SCLFunctions.evaluateDB("Simantics/SharedOntologies", "getSharedOntologies", Tuple0.INSTANCE); 
+        List<Resource> libraries = SCLFunctions.evaluateGraph("Simantics/SharedOntologies", "getSharedOntologies", graph, Tuple0.INSTANCE); 
 
         for (Resource library : libraries) {
             result.addAll(graph.syncRequest(new AllModelIssues(library, false)));
index efdba04d0ee07fecb12bbb814628989ef6ec434e..f6121ce19ec6179d824a98ffed7a5493cf4a2a3e 100644 (file)
@@ -69,7 +69,7 @@ public class RunActiveValidations extends AbstractHandler {
     public static void run() throws DatabaseException {
         Resource model = Simantics.getSession().syncRequest(new PossibleActiveModel(Simantics.getProjectResource()));
         if(model != null)
-            run(null);
+            run(model);
     }
 
     public static void run(Resource model) {
index 47931cc4f1172e7eb0bc631471114d8fd648209b..98b7aa98120c69217aba16c8a9cf709a98bccbf0 100644 (file)
@@ -32,6 +32,9 @@ MOD.SCLLabelForegroundColorRule <T VP.VisualsRule
 MOD.SCLLabelBackgroundColorRule <T VP.VisualsRule
   >-- MOD.SCLLabelBackgroundColorRule.getColor ==> "Resource -> Maybe (Double, Double, Double) -> String -> Integer -> <ReadGraph> Maybe (Double, Double, Double)]" <R L0.HasProperty : L0.FunctionalRelation
 
+MOD.SCLCheckedStateRule <T VP.VisualsRule
+  >-- MOD.SCLCheckedStateRule.getState ==> "BrowseNodeRule CheckedState" <R L0.HasProperty : L0.FunctionalRelation
+
 MOD.SCLAction <T ACT.Action
   --> MOD.SCLAction.action ==> "Resource -> <Proc> ()" <R L0.HasProperty : L0.FunctionalRelation 
 
@@ -412,6 +415,13 @@ MOD.sclLabelBackgroundColorRule : L0.Template
             L0.SCLValue.expression %expression
             L0.HasValueType "Resource -> Maybe (Double, Double, Double) -> String -> Integer -> <ReadGraph> Maybe (Double, Double, Double)"
 
+MOD.sclCheckedStateRule : L0.Template
+    @template %action %expression
+        %action : MOD.SCLCheckedStateRule
+          MOD.SCLCheckedStateRule.getState _ : MOD.SCLValue
+            L0.SCLValue.expression %expression
+            L0.HasValueType "Browsable a => a -> <ReadGraph> CheckedState"
+
 MOD.sclAction : L0.Template
     @template %action %expression
         %action : MOD.SCLAction
index 590ddd21ce8f658d40b133dd6cb0fddd3be8607d..d051042d5f4258b6c92acbace7b52eeec2a9114b 100644 (file)
@@ -111,6 +111,9 @@ importJava "org.simantics.browsing.ui.content.LabelDecorator" where
 
 importJava "org.simantics.browsing.ui.CheckedState" where
     data CheckedState
+    CHECKED :: CheckedState
+    GRAYED :: CheckedState
+    NOT_CHECKED :: CheckedState
 
 importJava "org.simantics.browsing.ui.content.Labeler$Modifier" where
     data Modifier
@@ -138,3 +141,6 @@ instanceOfTest :: Variable -> <ReadGraph> (Resource -> <ReadGraph> Boolean)
 instanceOfTest self = do
   typeResource = singleObject (represents $ parent self) MOD.InstanceOfTest.HasType
   (\r -> isInstanceOf r typeResource) 
+
+type BrowseNodeRule a = VariableOrResource -> <ReadGraph,Proc> a  
+  
\ No newline at end of file
index ef63fabe09dc52db6ce5cad752b352c09247d3c6..38f24b4f7ddb53d8d7b6b3dafc84403c35042533 100644 (file)
@@ -200,12 +200,12 @@ public class ComponentTypeViewer {
                         
                         for(Resource assertion : graph.getAssertedObjects(data.componentType, relation)) {
                             try {
-                               expression = graph.getPossibleRelatedValue(assertion, L0.SCLValue_expression, Bindings.STRING);
+                                expression = graph.getPossibleRelatedValue(assertion, L0.SCLValue_expression, Bindings.STRING);
                                 if(expression != null) {
                                        defaultValue = "=" + expression; //$NON-NLS-1$
                                 } else if (graph.sync(new IsEnumeratedValue(assertion))) {
-                                   defaultValue = GetEnumerationValue.getEnumerationValueName(graph, assertion);
-                               } else {
+                                    defaultValue = GetEnumerationValue.getEnumerationValueName(graph, assertion);
+                                } else {
                                        Datatype dt = getPossibleDatatype(graph, assertion);
                                        if (dt == null)
                                            continue;
index 820d45f2e1ecf9365a65aa3895771b68519ee8ee..01c799d45832b824835b1a477c20c3ecd3dfce16 100644 (file)
@@ -3,9 +3,9 @@ package org.simantics.modeling.ui.componentTypeEditor;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
-import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
@@ -42,22 +42,22 @@ import org.simantics.databoard.units.internal.library.UnitLibrary;
 import org.simantics.databoard.util.Limit;
 import org.simantics.databoard.util.Range;
 import org.simantics.databoard.util.RangeException;
-import org.simantics.db.ReadGraph;
 import org.simantics.db.RequestProcessor;
 import org.simantics.db.Resource;
 import org.simantics.db.Statement;
 import org.simantics.db.WriteGraph;
 import org.simantics.db.common.NamedResource;
 import org.simantics.db.common.request.IndexRoot;
-import org.simantics.db.common.request.ResourceRead;
 import org.simantics.db.common.request.WriteRequest;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.function.DbConsumer;
 import org.simantics.db.layer0.QueryIndexUtils;
+import org.simantics.db.layer0.util.Layer0Utils;
 import org.simantics.layer0.Layer0;
 import org.simantics.modeling.userComponent.ComponentTypeCommands;
 import org.simantics.scl.runtime.function.Function2;
 import org.simantics.scl.runtime.function.Function4;
+import org.simantics.utils.datastructures.Pair;
 import org.simantics.utils.threads.ThreadUtils;
 import org.simantics.utils.ui.ErrorLogger;
 
@@ -225,26 +225,6 @@ public class ComponentTypeViewerData {
         editor.setEditor(text, selectedItem, column);
     }
 
-    private static class TypeDefinitionMapRequest extends ResourceRead<Map<String,Resource>> {
-        public TypeDefinitionMapRequest(Resource resource) {
-            super(resource);
-        }
-
-        @Override
-        public Map<String,Resource> perform(ReadGraph graph) throws DatabaseException {
-            Layer0 L0 = Layer0.getInstance(graph);
-            Map<String,Resource> result = new HashMap<>();
-            for(Resource valueType : QueryIndexUtils.searchByType(graph, resource, L0.ValueType)) {
-                Collection<Statement> stms = graph.getAssertedStatements(valueType, L0.HasValueType);
-                if(stms.size() == 1) {
-                    String sclValueType = graph.getValue(stms.iterator().next().getObject(), Bindings.STRING);
-                    result.put(sclValueType, valueType);
-                }
-            }
-            return result;
-        }
-    }
-
     public void editType(Table table, TableEditor editor, final ComponentTypeViewerPropertyInfo propertyInfo, TableItem selectedItem, int column, String range, final boolean convertDefaultValue) {
         int extraStyle = propertyInfo.immutable ? SWT.READ_ONLY : 0;
         final Combo combo = new Combo(table, SWT.NONE | extraStyle);
@@ -282,11 +262,40 @@ public class ComponentTypeViewerData {
                             throws DatabaseException {
                         graph.markUndoPoint();
 
+                        String newValue2 = newValue;
+
+                        Resource possibleGraphType = null;
                         Resource root = graph.syncRequest(new IndexRoot(componentType));
-                        Map<String,Resource> typeDefinitionMap = graph.syncRequest(new TypeDefinitionMapRequest(root));
-                        Resource possibleGraphType = typeDefinitionMap.get(newValue);
 
-                        ComponentTypeCommands.editType(graph, componentType, propertyInfo.resource, convertDefaultValue, newValue, possibleGraphType);
+                        Resource L0Res = graph.getResource("http://www.simantics.org/Layer0-1.1");
+                        Layer0 L0 = Layer0.getInstance(graph);
+
+                        Collection<Resource> graphTypes1 = QueryIndexUtils.searchByTypeAndName(graph, L0Res, L0.ValueType, newValue);
+                        Collection<Resource> graphTypes2 = QueryIndexUtils.searchByTypeAndName(graph, root, L0.ValueType, newValue);
+
+                        Collection<Resource> graphTypes = new HashSet<>(graphTypes1);
+                        graphTypes.addAll(graphTypes2);
+
+                        Set<Pair<Resource, String>> candidates = new HashSet<>();
+                        for (Resource graphType : graphTypes) {
+                            Collection<Statement> stms = graph.getAssertedStatements(graphType, L0.HasValueType);
+                            if(stms.size() == 1) {
+                                // Only accept valueType if it asserts HasValueType with the same name
+                                String hasValueType = graph.getValue(stms.iterator().next().getObject(), Bindings.STRING);
+                                if (hasValueType.equals(newValue)) {
+                                    candidates.add(new Pair<>(graphType, hasValueType));
+                                }
+                            }
+                        }
+
+                        // We support only graph types with unique name at this point. Later we could implement UI to let the user to select from multiple graph types.
+                        if (candidates.size() == 1) {
+                            Pair<Resource, String> result = candidates.iterator().next();
+                            possibleGraphType = result.first;
+                            newValue2 = result.second;
+                        }
+
+                        ComponentTypeCommands.editType(graph, componentType, propertyInfo.resource, convertDefaultValue, newValue2, possibleGraphType);
                         if (range != null) ComponentTypeCommands.setRange(graph, componentType, propertyInfo.resource, range);
                     }
                 });
index d473ff46df044a4db03b1bb694fb23e5bbf3ca3c..68210f9e263f5c48e51eb10bbbc30f0324b85244 100644 (file)
 package org.simantics.modeling.ui.diagram.style;
 
 import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
 import java.awt.geom.Rectangle2D;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -25,9 +28,13 @@ import org.simantics.db.common.procedure.adapter.TransientCacheListener;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.variable.Variable;
 import org.simantics.db.layer0.variable.Variables;
+import org.simantics.diagram.connection.RouteGraph;
 import org.simantics.diagram.elements.DecorationSVGNode;
 import org.simantics.diagram.elements.SVGNode;
+import org.simantics.diagram.handler.Paster;
+import org.simantics.diagram.handler.Paster.RouteLine;
 import org.simantics.diagram.profile.StyleBase;
+import org.simantics.diagram.stubs.DiagramResource;
 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
 import org.simantics.issues.Severity;
 import org.simantics.issues.common.IssueResourcesContexts;
@@ -36,10 +43,13 @@ import org.simantics.modeling.ModelingResources;
 import org.simantics.modeling.ui.Activator;
 import org.simantics.modeling.ui.diagram.style.IssueDecorationStyle.IssueResult;
 import org.simantics.scenegraph.INode;
+import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
 import org.simantics.scenegraph.g2d.nodes.Decoration;
+import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
 import org.simantics.scenegraph.profile.EvaluationContext;
 import org.simantics.scenegraph.profile.common.ProfileVariables;
 import org.simantics.scenegraph.utils.NodeUtil;
+import org.simantics.structural.stubs.StructuralResource2;
 import org.simantics.utils.datastructures.map.Tuple;
 
 
@@ -74,7 +84,6 @@ public class IssueDecorationStyle extends StyleBase<IssueResult> {
             return null;
 
         List<Resource> contexts = getContexts(graph, element);
-        AffineTransform transform = DiagramGraphUtil.getAffineTransform(graph, element);
         Map<Severity, List<Resource>> issuesBySeverity = graph.syncRequest(new ListModelIssuesBySeverity(model, true, true, Severity.NOTE),
                 TransientCacheListener.<Map<Severity, List<Resource>>>instance());
 
@@ -82,14 +91,43 @@ public class IssueDecorationStyle extends StyleBase<IssueResult> {
             List<Resource> issues = issuesBySeverity.get(severity);
             if (issues != null) {
                 Set<Resource> issueContexts = graph.syncRequest(new IssueResourcesContexts(issues));
-                if (!Collections.disjoint(issueContexts, contexts))
-                    return new IssueResult(severity, transform);
+                if (!Collections.disjoint(issueContexts, contexts)) {
+                    return new IssueResult(severity, getIdentifier(graph, runtimeDiagram, element));
+                }
             }
         }
 
         return null;
     }
 
+    private static Object getIdentifier(ReadGraph graph, Resource runtimeDiagram, Resource element) throws DatabaseException {
+        DiagramResource DIA = DiagramResource.getInstance(graph);
+        StructuralResource2 STR = StructuralResource2.getInstance(graph);
+        if (graph.isInstanceOf(element, DIA.RouteGraphConnection)) {
+            Collection<Resource> connectors = graph.getObjects(element, DIA.HasConnector);
+            Collection<Resource> routeNodes = graph.getObjects(element, DIA.HasInteriorRouteNode);
+
+            // This is needed to make this query result change every time the underlying element changes visually.
+            Set<Object> identifier = new HashSet<Object>(connectors.size() + routeNodes.size());
+
+            for (Resource connector : connectors) {
+                for (Resource connectedTo : graph.getObjects(connector, STR.Connects)) {
+                    if (!connectedTo.equals(element)) {
+                        AffineTransform at = DiagramGraphUtil.getDynamicAffineTransform(graph, runtimeDiagram, connectedTo, DIA.HasDynamicTransform, false);
+                        identifier.add(at);
+                    }
+                }
+            }
+            for (Resource routeLine : routeNodes) {
+                RouteLine rl = Paster.readRouteLine(graph, routeLine);
+                identifier.add(rl);
+            }
+            return identifier;
+        } else {
+            return DiagramGraphUtil.getAffineTransform(graph, element);
+        }
+    }
+
     @Override
     public void applyStyleForNode(EvaluationContext observer, INode node, IssueResult result) {
         if (result == null) {
@@ -117,6 +155,18 @@ public class IssueDecorationStyle extends StyleBase<IssueResult> {
     protected AffineTransform getDecorationPosition(INode node) {
        Rectangle2D bounds = NodeUtil.getLocalBounds(node, Decoration.class);
 
+        if (node instanceof ConnectionNode) {
+            for (INode child : ((ConnectionNode)node).getSortedNodes()) {
+                if (child instanceof RouteGraphNode) {
+                    RouteGraphNode rgn = (RouteGraphNode) child;
+                    RouteGraph rg = rgn.getRouteGraph();
+                    Point2D nearest = rg.findNearestPoint(bounds.getCenterX(), bounds.getCenterY());
+                    if (nearest != null) {
+                        return AffineTransform.getTranslateInstance(nearest.getX(), nearest.getY());
+                    }
+                }
+            }
+        }
         double tx = bounds.getX();
         double ty = bounds.getY();
         return AffineTransform.getTranslateInstance(tx, ty);
@@ -148,8 +198,8 @@ public class IssueDecorationStyle extends StyleBase<IssueResult> {
      * element moves.
      */
     public static class IssueResult extends Tuple {
-        public IssueResult(Severity severity, AffineTransform transform) {
-            super(severity, transform);
+        public IssueResult(Severity severity, Object identifier) {
+            super(severity, identifier);
         }
         public Severity getSeverity() {
             return (Severity) getField(0);
index d5071303e4924b22a3f812f05b312141d03a5ed1..6be9f72f92d2939dfafefb7284a36ca2d9d0d87e 100644 (file)
@@ -63,6 +63,15 @@ public class OpenDiagramFromComponentAdapter extends AbstractResourceEditorAdapt
         super(Messages.OpenDiagramFromComponentAdapter_OpenDiagramContainingComponent, Activator.SYMBOL_ICON);
     }
 
+    protected String getEditorId(ReadGraph g, Resource diagram) throws DatabaseException {
+        ModelingResources MOD = ModelingResources.getInstance(g);
+        String preferredEditorId = g.getPossibleRelatedValue(diagram, MOD.PreferredDiagramEditorID);
+        if(preferredEditorId != null)
+            return preferredEditorId;
+        else
+            return EDITOR_ID;
+    }
+
     @Override
     public boolean canHandle(ReadGraph graph, Object input) throws DatabaseException {
         Pair<Resource, String> p = tryGetResource(graph, input);
@@ -153,6 +162,8 @@ public class OpenDiagramFromComponentAdapter extends AbstractResourceEditorAdapt
             Resource composite = g.getSingleObject(component, l0.PartOf);
             Resource diagram = ComponentUtils.getPossibleCompositeDiagram(g, composite);
 
+            String editorId = getEditorId(g, composite);
+
             if (LOGGER.isDebugEnabled()) {
                 LOGGER.debug(getClass().getSimpleName() + ".findDiagram: component: " + NameUtils.getURIOrSafeNameInternal(g, component)); //$NON-NLS-1$
                 LOGGER.debug(getClass().getSimpleName() + ".findDiagram: composite: " + NameUtils.getURIOrSafeNameInternal(g, composite)); //$NON-NLS-1$
@@ -213,7 +224,7 @@ public class OpenDiagramFromComponentAdapter extends AbstractResourceEditorAdapt
                 // Prevent diagram from opening if there's nothing to select
                 // on the diagram based on the received input.
                 if (!selectedObjects.isEmpty())
-                    result.add( NavigateToTarget.editorActivator(EDITOR_ID, diagram, indexRoot, rvi, editorActivationCallback(selectedObjects)) );
+                    result.add( NavigateToTarget.editorActivator(editorId, diagram, indexRoot, rvi, editorActivationCallback(selectedObjects)) );
             } else {
                 final MapSet<NamedResource, Resource> referencingDiagrams = listReferenceDiagrams(g, referenceElements);
                 final Set<NamedResource> diagrams = referencingDiagrams.getKeys();
@@ -238,7 +249,7 @@ public class OpenDiagramFromComponentAdapter extends AbstractResourceEditorAdapt
                     RVI rvi = getDiagramCompositeRvi(g, singleDiagram.getResource());
                     if (rvi != null) {
                         Collection<Resource> selectedObjects = referencingDiagrams.getValues(singleDiagram);
-                        result.add( NavigateToTarget.editorActivator(EDITOR_ID, singleDiagram.getResource(), indexRoot, rvi, editorActivationCallback(selectedObjects)) );
+                        result.add( NavigateToTarget.editorActivator(editorId, singleDiagram.getResource(), indexRoot, rvi, editorActivationCallback(selectedObjects)) );
                     }
                     break;
 
@@ -254,7 +265,7 @@ public class OpenDiagramFromComponentAdapter extends AbstractResourceEditorAdapt
                         if (selected != null) {
                             Collection<Resource> selectedObjects = referencingDiagrams.getValues(selected);
                             RVI drvi = diagramToRvi.get(selected);
-                            NavigateToTarget.editorActivator(EDITOR_ID, selected.getResource(), indexRoot, drvi, editorActivationCallback(selectedObjects)).run();
+                            NavigateToTarget.editorActivator(editorId, selected.getResource(), indexRoot, drvi, editorActivationCallback(selectedObjects)).run();
                         }
                     });
                     break;
index 7693586d8029b79dcb5ccc80d838e3821644e791..063a661c94bbd6bab2285b7df0826562438ae6b8 100644 (file)
         </type>
     </target>
 
+    <target interface="org.simantics.browsing.ui.model.visuals.VisualsRule">
+        <type uri="http://www.simantics.org/Modeling-0.0/SCLCheckedStateRule"
+            class="org.simantics.modeling.adapters.SCLCheckedStateRule">
+            <graph />
+            <this />
+        </type>
+    </target>
+
     <target interface="org.simantics.browsing.ui.model.tests.Test">
         <type uri="http://www.simantics.org/Modeling-0.0/SCLTest"
             class="org.simantics.modeling.adapters.SCLTest">
index 30a482ffc6d068cfcbc45bdd93dba4490a081c52..6a1ed98425149af507f17e6ab3360df7e40d35b1 100644 (file)
@@ -1,6 +1,7 @@
 include "Simantics/DB"
 
 include "http://www.simantics.org/Layer0-1.1" as L0
+include "http://www.simantics.org/Layer0X-1.1" as L0X
 include "http://www.simantics.org/Structural-1.2" as STR
 include "http://www.simantics.org/Diagram-2.2" as DIA
 include "http://www.simantics.org/Modeling-1.2" as MOD
@@ -10,4 +11,5 @@ include "http://www.simantics.org/Spreadsheet-1.2" as SHEET
 include "http://www.simantics.org/Image2-1.2" as IMAGE
 include "http://www.simantics.org/Document-1.2" as DOCUMENT
 include "http://www.simantics.org/Event-1.2" as EVENT
-include "http://www.simantics.org/Project-1.2" as PROJECT
\ No newline at end of file
+include "http://www.simantics.org/Project-1.2" as PROJECT
+include "http://www.simantics.org/Issue-1.2" as ISSUE
index cb048e037ff672cb87841f22bd53adab9316866f..e7667ed877a59ab1bb841341a44f3c1039e110ab 100644 (file)
@@ -11,7 +11,7 @@ importJava "org.simantics.modeling.Rename" where
     Example:
     
         > renameNode resource "NewName"
-        "Succesfully renamed oldName to NewName"
+        "Successfully renamed oldName to NewName"
         
     or error if failed
     """
@@ -26,7 +26,7 @@ Renames the given `entity` with the given `newName` and returns
 Example:
 
     > renameMBNode entity "NewName"
-    "Succesfully renamed oldName to NewName"
+    "Successfully renamed oldName to NewName"
     
 or error if failed
 """
index 5d8543d213131cab85739580703ef6bad121a411..0c5007ba5167a868bb469062f26e2a91781c120b 100644 (file)
@@ -29,7 +29,7 @@ public class Rename {
        CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
        graph.addMetadata(cm.add("Renamed node " + nodeName + ", resource  " + node +  ", to " + newName));
        
-               return "Succesfully renamed "+ nodeName + " to " + newName;
+               return "Successfully renamed "+ nodeName + " to " + newName;
     }
     
 }
diff --git a/bundles/org.simantics.modeling/src/org/simantics/modeling/adapters/SCLCheckedStateRule.java b/bundles/org.simantics.modeling/src/org/simantics/modeling/adapters/SCLCheckedStateRule.java
new file mode 100644 (file)
index 0000000..0c7da8d
--- /dev/null
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 2019 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.modeling.adapters;
+
+import org.simantics.browsing.ui.CheckedState;
+import org.simantics.browsing.ui.model.check.CheckedStateRule;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.VariableOrResource;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.scl.runtime.SCLContext;
+import org.simantics.scl.runtime.function.Function1;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SCLCheckedStateRule implements CheckedStateRule {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(SCLCheckedStateRule.class);
+
+    private Resource rule;
+
+    public SCLCheckedStateRule(ReadGraph graph, Resource rule) {
+        this.rule = rule;
+    }
+
+    @Override
+    public boolean isCompatible(Class<?> contentType) {
+        return contentType.equals(Resource.class) || contentType.equals(Variable.class);
+    }
+
+    @Override
+    public CheckedState getCheckedState(ReadGraph graph, Object content) throws DatabaseException {
+
+        ModelingResources MOD = ModelingResources.getInstance(graph);
+
+        Variable ruleVariable = Variables.getVariable(graph, rule);
+
+        Function1<Object,CheckedState> getLabels = ruleVariable.getPossiblePropertyValue(graph, MOD.SCLCheckedStateRule_getState);
+        if(getLabels == null) {
+            LOGGER.warn("Didn't find value for subject={}, predicate={}.", rule, ModelingResources.URIs.SCLCheckedStateRule_getState);
+            return CheckedState.NOT_CHECKED;
+        }
+
+        SCLContext sclContext = SCLContext.getCurrent();
+        Object oldGraph = sclContext.get("graph");
+        try {
+            sclContext.put("graph", graph);
+            return getLabels.apply(VariableOrResource.make(content));
+        } catch (Throwable t) {
+            LOGGER.error("Calculating checked state failed.", t);
+            throw new DatabaseException(t);
+        } finally {
+            sclContext.put("graph", oldGraph);
+        }
+
+    }
+
+}
index a04b9315f544d698913c655ce084e485ec05224a..1ea88caf4377bb7cb66b31e8b55b8eeafec32ac9 100644 (file)
@@ -41,7 +41,7 @@ public class SCLChildRule implements ChildRule {
         
         Variable ruleVariable = Variables.getVariable(graph, rule);
 
-        Function1<Resource,List<Resource>> getChildren = ruleVariable.getPossiblePropertyValue(graph, MOD.SCLChildRule_getChildren);
+        Function1<Object,List<Resource>> getChildren = ruleVariable.getPossiblePropertyValue(graph, MOD.SCLChildRule_getChildren);
         if(getChildren == null) return Collections.emptyList();
 
         SCLContext sclContext = SCLContext.getCurrent();
index 4ee96f75d8e062fad53dea40bc81e30c997e5b2a..799579377a614aecf4e15aa8e0ceacc241572b56 100644 (file)
@@ -23,7 +23,14 @@ public enum PageSettingsTypicalRule implements ITypicalSynchronizationRule {
 
        @Override
        public boolean synchronize(WriteGraph graph, Resource template, Resource instance, TypicalInfo info) throws DatabaseException {
+               // Diagrams should always have some sort of diagram description.
+               // If the template doesn't have one, the existing description
+               // from the instance shall not be removed.
                DiagramDesc mdesc = graph.syncRequest(DiagramRequests.getDiagramDesc(template));
+               if (mdesc == null) {
+                       info.messageLog.add("\t\ttemplate doesn't have any diagram page settings, doing nothing");
+                       return false;
+               }
                DiagramDesc idesc = graph.syncRequest(DiagramRequests.getDiagramDesc(instance));
                if (mdesc.equals(idesc))
                        return false;
index c92d80c848cec727999d467fefa167ee792fd3a5..9cf93fac5ce83d9067b99d7ebbb7e0da6a272f63 100644 (file)
@@ -223,7 +223,7 @@ public class ComponentTypeCommands {
         // We assert the range of the property only if we are given a dedicated graph value type
         if(g.hasStatement(property, L0.HasRange))
             g.deny(property, L0.HasRange);
-        
+
         if(possibleType != null) {
             // We have a dedicated graph type for this SCL value type
             if(g.hasStatement(possibleType, L0.Enumeration)) {
@@ -297,28 +297,28 @@ public class ComponentTypeCommands {
             return;
         }
 
-       Layer0 L0 = Layer0.getInstance(g);
-       Resource range = g.getPossibleObject(relation, L0.HasRange);
-       if (range != null) {
+        Layer0 L0 = Layer0.getInstance(g);
+        Resource range = g.getPossibleObject(relation, L0.HasRange);
+        if (range != null) {
             if(g.hasStatement(range, L0.Enumeration)) {
-                   Map<String,Resource> values = g.syncRequest(new EnumerationMap(range));
-                   Resource value = values.get(valueText);
-                   if (value != null) {
-                       for(Resource assertion : g.getObjects(type, L0.Asserts)) {
-                           Resource p = g.getSingleObject(assertion, L0.HasPredicate);
-                           if (p.equals(relation)) {
-                               g.deny(assertion, L0.HasObject, object);
-                               g.claim(assertion, L0.HasObject, value);
-                           }
-                       }
-                   }
-                   return;
+                Map<String,Resource> values = g.syncRequest(new EnumerationMap(range));
+                Resource value = values.get(valueText);
+                if (value != null) {
+                    for(Resource assertion : g.getObjects(type, L0.Asserts)) {
+                        Resource p = g.getSingleObject(assertion, L0.HasPredicate);
+                        if (p.equals(relation)) {
+                            g.deny(assertion, L0.HasObject, object);
+                            g.claim(assertion, L0.HasObject, value);
+                        }
+                    }
+                }
+                return;
             }
         }
         
         if(valueText.length() > 0 && valueText.charAt(0) == '=') {
                
-            String expression = valueText.substring(1);
+               String expression = valueText.substring(1);
                ModelingResources MOD = ModelingResources.getInstance(g);
                if(!g.isInstanceOf(object, MOD.SCLValue)) {
                        Resource assertion = g.getSingleObject(object, L0.HasObjectInverse);
@@ -477,7 +477,7 @@ public class ComponentTypeCommands {
         }
         return null;
     }
-    
+
     public static void convertDefaultValue(WriteGraph g,
             Resource type, Resource relation, String newSCLType, Resource possibleType) throws DatabaseException {
         Resource object = getAssertedObject(g, type, relation);
@@ -494,7 +494,7 @@ public class ComponentTypeCommands {
                     Map<String, Resource> enumMap = g.syncRequest(new EnumerationMap(possibleType));
                     String firstKey = Collections.min(enumMap.keySet(), AlphanumComparator.COMPARATOR);
                     Resource defaultValue = enumMap.get(firstKey);
-                    
+
                     if (defaultValue != null) {
                         Resource assertion = findAssertionWithPO(g, type, relation, object);
                         if(assertion != null) {
@@ -506,6 +506,8 @@ public class ComponentTypeCommands {
                             return;
                         }
                     }
+                } else {
+                       return;
                 }
             }
         }
@@ -514,6 +516,16 @@ public class ComponentTypeCommands {
         if (tuple == null)
             return;
 
+        if(g.sync(new IsEnumeratedValue(object))) {
+            Resource assertion = findAssertionWithPO(g, type, relation, object);
+            object = g.newResource();
+            g.claim(object, L0.InstanceOf, L0.Literal);
+            if(assertion != null) {
+                g.deny(assertion, L0.HasObject);
+                g.claim(assertion, L0.HasObject, object);
+            }
+        }
+
         g.claimLiteral(object, L0.HasDataType, L0.DataType, tuple.get(0), Bindings.getBindingUnchecked(Datatype.class));
         g.claimLiteral(object, L0.HasValueType, g.<String>getRelatedValue(relation, L0.RequiresValueType, Bindings.STRING), Bindings.STRING);
         g.claimValue(object, tuple.get(1), (Binding)tuple.get(2));
@@ -523,7 +535,7 @@ public class ComponentTypeCommands {
     public static void convertInstantiatedValue(WriteGraph g, Resource instance, Resource relation, String newSCLType) throws DatabaseException {
        convertInstantiatedValue(g, instance, relation, newSCLType, null);
     }
-    
+
     public static void convertInstantiatedValue(WriteGraph g, Resource instance, Resource relation, String newSCLType, Resource possibleType)
             throws DatabaseException {
 
@@ -531,14 +543,14 @@ public class ComponentTypeCommands {
         if(stm != null && !stm.isAsserted(instance)) {
 
             Layer0 L0 = Layer0.getInstance(g);
-               Resource object = stm.getObject();
+            Resource object = stm.getObject();
 
-               if(g.sync(new IsEnumeratedValue(object))) {
-                       if(!g.isInstanceOf(object, possibleType)) {
-                               g.deny(instance, relation);
-                       }
-                       return;
-               }
+            if(g.sync(new IsEnumeratedValue(object))) {
+                if(!g.isInstanceOf(object, possibleType)) {
+                    g.deny(instance, relation);
+                }
+                return;
+            }
 
             // We can only convert literals
             if(!g.isInstanceOf(object, L0.Literal)) return;
index 3aaaed2f668aa308727dc4947ef2993d0854ee27..1e8ad54e13d4b8396d0f37626eb7b488322c0428 100644 (file)
@@ -18,7 +18,8 @@ Require-Bundle: org.simantics.layer0,
  org.simantics.modeling.template2d.ontology;bundle-version="1.0.0",
  org.simantics.spreadsheet.ontology;bundle-version="1.2.0",
  org.simantics.selectionview.ui.ontology;bundle-version="1.1.0",
- org.simantics.diagram.ontology;bundle-version="2.2.0"
+ org.simantics.diagram.ontology;bundle-version="2.2.0",
+ org.simantics.issues.ontology;bundle-version="1.2.0"
 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
 Export-Package: org.simantics.platform.ui
 Automatic-Module-Name: org.simantics.platform.ui.ontology
index cda1dacf966eb0b731d8df17785754decdbc2b0d..0a96411a7e286c5cfcbdf337444a7d29929746a3 100644 (file)
@@ -2,5 +2,6 @@ source.. = src/
 output.. = bin/
 bin.includes = META-INF/,\
                .,\
-               graph.tg
+               graph.tg,\
+               scl/
 src.includes = graph/
index 11b07f80eba5ab9520a20a9582a9f3d0d47fb0af..78f9204cf4b1070b838c1ca1f19941d6b6fb0e29 100644 (file)
@@ -1,3 +1,15 @@
+/*******************************************************************************
+ * Copyright (c) 2019 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     VTT Technical Research Centre of Finland - initial API and implementation
+ *     Semantum Oy - reorganization
+ *******************************************************************************/
 L0 = <http://www.simantics.org/Layer0-1.1>
 PROJECT = <http://www.simantics.org/Project-1.2>
 MOD = <http://www.simantics.org/Modeling-1.2>
@@ -17,8 +29,7 @@ PlatformUI = <http://www.simantics.org/PlatformUI-1.0> : L0.Ontology
     L0.IsLinkedTo MOD
     
 PlatformUI.SCLMain : L0.SCLModule
-    L0.SCLModule.definition _ : L0.String
-      @L0.loadString "scl/SCLMain.scl"
+    L0.SCLModule.definition """ include "Simantics/PlatformUI" """
     
 PlatformUI.NameLabelMode <T L0.String
     @L0.tag L0.Enumeration
diff --git a/bundles/org.simantics.platform.ui.ontology/graph/ValidationView.pgraph b/bundles/org.simantics.platform.ui.ontology/graph/ValidationView.pgraph
new file mode 100644 (file)
index 0000000..31aeb3c
--- /dev/null
@@ -0,0 +1,78 @@
+/*******************************************************************************
+ * Copyright (c) 2019 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     Semantum Oy - initial API and implementation
+ *******************************************************************************/
+L0 = <http://www.simantics.org/Layer0-1.1>
+DOC = <http://www.simantics.org/Documentation-1.2>
+SWT = <http://www.simantics.org/SWT-1.0>
+STR = <http://www.simantics.org/Structural-1.2>
+SEL = <http://www.simantics.org/SelectionView-1.2>
+COMPONENTS = <http://www.simantics.org/SWT-1.0/Components>
+VIEWS = <http://www.simantics.org/PlatformUI-1.0/Views>
+VP = <http://www.simantics.org/Viewpoint-1.2>
+MOD = <http://www.simantics.org/Modeling-1.2>
+PROJECT = <http://www.simantics.org/Project-1.2>
+ISSUE = <http://www.simantics.org/Issue-1.2>
+
+VIEWS.ValidationContribution : SWT.TypedVariableTabContribution
+    SEL.AbstractVariableTabContribution.HasPriority 1
+    SEL.AbstractTypedVariableTabContribution.HasType L0.IndexRoot
+    SWT.TypedVariableTabContribution.HasView VIEWS.Validations
+    L0.HasLabel "Validation"
+
+VIEW = VIEWS.Validations : DOC.Document
+VIEW.Root : DOC.Components.Root
+  @DOC.child1_
+    VIEW.Panel
+      @SWT.scrolledComposite
+      @DOC.child2_ VIEW.Explorer
+      @DOC.child1_
+        VIEW.Panel2
+          @SWT.gridComposite 2
+          @DOC.child1_
+            VIEW.Cell1
+              @SWT.gridCell _ false false 1
+                VIEW.ConfigureButton
+                  @SWT.button "Configure"
+                  @VIEWS.sclEvent COMPONENTS.Button.onPress "configureButtonClick self"
+          @DOC.child2_
+            VIEW.Cell2
+              @SWT.gridCell _ false false 1
+                VIEW.ValidateButton
+                  @SWT.button "Validate"
+                  @VIEWS.sclEvent COMPONENTS.Button.onPress "validateButtonClick self"
+
+VIEW.Columns = { columns = [
+          {key = "single", label = "Issue sources", tooltip = "Issue sources", width = 80, weight = 1, alignment = "LEFT", grab = true}
+          ]} : SWT.Literals.Columns
+
+VIEW.Explorer
+  COMPONENTS.Component.Check true
+  @SWT.explorer true true
+    "http://www.simantics.org/PlatformUI-1.0/Views/Validations/BrowseContext"
+    "#ValidationSelection"
+    VIEW.Columns
+  @VIEWS.sclEvent COMPONENTS.Explorer.onCheck "issueSourceExplorerCheck self"
+
+MBC = MOD.ModelingBrowseContext
+
+VIEWS.Validations.BrowseContext : VP.BrowseContext
+    VP.BrowseContext.Includes PROJECT.ProjectBrowseContext
+    VP.BrowseContext.HasVisualsContribution PROJECT.Contributions.StandardNameLabelRule
+    VP.BrowseContext.HasChildContribution VIEWS.Validations.BrowseContext.Children : VP.ChildContribution
+        VP.ChildContribution.HasParentNodeType MBC.Variable
+        VP.ChildContribution.HasChildNodeType ISSUE.IssueSource
+        VP.ChildContribution.HasRule VIEWS.Validations.BrowseContext.Children.Rule : MOD.SCLChildRule
+            @MOD.scl MOD.SCLChildRule.getChildren "usedIssueSources" "Resource -> <ReadGraph> [Resource]"
+    VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution
+        VP.VisualsContribution.HasNodeType ISSUE.IssueSource
+        VP.VisualsContribution.HasPriority 1.0
+        VP.VisualsContribution.HasRule VIEWS.Validations.BrowseContext.Checked
+          @MOD.sclCheckedStateRule "checkedStateRule"
similarity index 54%
rename from bundles/org.simantics.platform.ui.ontology/graph/scl/SCLMain.scl
rename to bundles/org.simantics.platform.ui.ontology/scl/Simantics/PlatformUI.scl
index 44c53d80e4cfa35e9320f51ae3b93227eac94dbe..07309cb7b2876ea7a233439edea2e57d00e5c0d9 100644 (file)
@@ -1,5 +1,19 @@
+/*******************************************************************************
+ * Copyright (c) 2019 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     VTT Technical Research Centre of Finland - initial API and implementation
+ *     Semantum Oy - reorganization
+ *******************************************************************************/
 include "Simantics/All"
 include "SWT/All"
+import "UI/Progress"
+import "Simantics/IssueUI"
 
 useSelectedHandler :: Variable -> (String -> Maybe String) -> <WriteGraph> String
 useSelectedHandler input parameters = do
@@ -84,4 +98,48 @@ standardPropertiesElementTransformation var = do
           Nothing -> var
           Just component -> resourceVariable component
       else var
-  
\ No newline at end of file
+
+configureButtonClickHandler :: Resource -> CommandContext -> <Proc> Maybe CommandResult
+configureButtonClickHandler indexRoot context = do
+    showIssueConfigurationDialog indexRoot 
+    Nothing
+      
+configureButtonClick :: Variable -> <ReadGraph,Proc> AbstractEventHandler
+configureButtonClick self = do
+  indexRoot = represents $ contextVariable self
+  eventHandler2 $ configureButtonClickHandler indexRoot
+
+validateButtonClickHandler :: Resource -> CommandContext -> <Proc> Maybe CommandResult
+validateButtonClickHandler indexRoot context = do
+    runActiveValidations (createNullProgressMonitor ()) indexRoot
+    Nothing
+
+validateButtonClick :: Variable -> <ReadGraph,Proc> AbstractEventHandler
+validateButtonClick self = do
+  indexRoot = represents $ contextVariable self
+  eventHandler2 $ validateButtonClickHandler indexRoot
+
+issueSourceExplorerCheckHandler :: Resource -> CommandContext -> <Proc> Maybe CommandResult
+issueSourceExplorerCheckHandler indexRoot context = match possibleValue context "item" with
+  Nothing -> Nothing
+  Just issueSource -> match possibleValue context "checked" with
+    Nothing -> Nothing
+    Just value -> if value then do
+        syncWrite $ \_ -> claim issueSource ISSUE.IssueSource.Selected (parent issueSource)
+        Nothing
+      else do
+        syncWrite $ \_ -> denyByPredicate issueSource ISSUE.IssueSource.Selected
+        Nothing  
+
+issueSourceExplorerCheck :: Variable -> <ReadGraph,Proc> AbstractEventHandler
+issueSourceExplorerCheck self = do
+  indexRoot = represents $ contextVariable self
+  eventHandler2 $ issueSourceExplorerCheckHandler indexRoot
+
+usedIssueSources :: Resource -> <ReadGraph> [Resource]
+usedIssueSources indexRoot = do
+   objectsWithType indexRoot L0.ConsistsOf ISSUE.IssueSource
+
+checkedStateRule :: BrowseNodeRule CheckedState
+checkedStateRule (ResourceX r) = if existsStatement3 r ISSUE.IssueSource.Selected (parent r) then CHECKED else NOT_CHECKED
+      
\ No newline at end of file
index 497b401a2a1d502ce00e352fe1301cef66c244ae..31295b9b692f60178c422ad7dda719089d87b76c 100644 (file)
@@ -66,7 +66,7 @@ public class ObserverGroupListener implements SetListener<Resource> {
             return true;
         else if (object == null)
             return false;
-        else if (ObserverGroupListener.class != object.getClass())
+        else if (getClass() != object.getClass())
             return false;
         ObserverGroupListener other = (ObserverGroupListener)object;
         return observer.equals(other.observer) && group.equals(other.group) && style.equals(other.style);
index d8f83e05f5b2f231bc5dcd14bf27bf93ff85ffdc..2fd74b21e3e1c25e7b7b520ba24f559ff0749a06 100644 (file)
@@ -151,7 +151,7 @@ public class SCLFunctions {
         }
     }
     
-    public static <T> T evaluateGraph(String module, String function, Object graph, Object ... args) throws DatabaseException {
+    public static <T> T evaluateGraph(String module, String function, ReadGraph graph, Object ... args) throws DatabaseException {
         final SCLContext context = SCLContext.getCurrent();
         SCLContext.push(context);
         Object oldGraph = context.put(GRAPH, graph);
@@ -163,7 +163,7 @@ public class SCLFunctions {
         }
     }
 
-    public static void runWithGraph(Object graph, Runnable r) {
+    public static void runWithGraph(ReadGraph graph, Runnable r) {
         final SCLContext context = SCLContext.getCurrent();
         SCLContext.push(context);
         Object oldGraph = context.put(GRAPH, graph);
index f983251093272d2168cb9eacc05db4542660afa0..86d13fb6628e77401b7a7fd0be2866834216ffca 100644 (file)
@@ -75,7 +75,7 @@ infixl 6  (+), (-)
 infixl 5  (\\), (<<), (<+)
 infix  4  (!=), (<), (<=), (>=), (>)
 infixr 3  (&&), (&<&)
-infixr 2  (||), orElse, morelse
+infixr 2  (||), orElse, orElseM, morelse
 infixr 1  (>>=), (>>), (:=), (>=>)
 infixr 1  ($)
 infixl 1  catch
index 233a1e5a11608fd20088deeb0a82f9c6d31d422d..d26d86682874a15e61551de5cfcd66907ec975b4 100644 (file)
@@ -13,7 +13,6 @@ import org.eclipse.swt.widgets.Control;
 import org.eclipse.swt.widgets.FontDialog;
 import org.simantics.Simantics;
 import org.simantics.browsing.ui.NodeContext;
-import org.simantics.browsing.ui.common.modifiers.EnumerationValue;
 import org.simantics.browsing.ui.content.Labeler.DialogModifier;
 import org.simantics.browsing.ui.graph.impl.GetEnumerationValue;
 import org.simantics.common.format.Formatter;
@@ -473,7 +472,7 @@ public class All {
                        Resource possibleValue = context.getParent(graph).getPossibleRepresents(graph);
                        if(possibleValue != null) {
                                if(graph.syncRequest(new IsEnumeratedValue(possibleValue))) {
-                       return GetEnumerationValue.getEnumerationValueName(graph, possibleValue);
+                                       return GetEnumerationValue.getEnumerationValueName(graph, possibleValue);
                                }
                        }
 
index 7839ce70db31de7b0de4dc80d6725e8dc603b505..c0a85cd1ac1c06343b7a9bfb516b2efb84eb80fc 100644 (file)
@@ -678,10 +678,11 @@ public class SimanticsPlatform implements LifecycleListener {
     }
 
     public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
+        // TODO: fix this to use Path APIs
         File dbLocation = Platform.getLocation().append("db").toFile();
         if(!dbLocation.exists()) return;
         try { // Load driver
-            Driver driver = Manager.getDriver("procore");
+            Driver driver = Manager.getDriver("acorn");
             Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
             management.delete();
         } catch (DatabaseException e) {