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);
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);
public class L0Validations {
public static String checkValueType(ReadGraph graph, Resource subject, Resource predicate) throws DatabaseException {
-
+
if (subject == null)
return null;
if (predicate == null)
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 ")
}
}
}
-
+
return null;
-
+
}
-
+
}
+/*******************************************************************************
+ * 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;
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;
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;
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) {
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) {
.append(requiredValueType)
.append(", predicate=")
.append(predicate)
+ .append(", isFunctional=")
+ .append(isFunctional)
.append(", isHasProperty=")
.append(isHasProperty)
.append(", hasEnumerationRange=")
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);
}
}
- 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);
}
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;
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;
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);
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);
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,
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
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
protected void test(int timeout) {
testImpl(timeout);
}
-
+
/**
* Executes a test case with given timeout as seconds
*
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>
-package org.simantics.db.testing.cases;
/*******************************************************************************
* Copyright (c) 2007, 2010 Association for Decentralized Information Management
* in Industry THTH ry.
* 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;
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
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();
+ }
+
}
package org.simantics.db.testing.common;
import java.io.File;
+import java.io.IOException;
import java.util.Properties;
import org.eclipse.core.runtime.Platform;
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.
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 {
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;
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;
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;
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)) {
*******************************************************************************/
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;
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;
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();
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;
public PostEventCommand(SWTDocument document, AbstractEventHandler handler, CommandContextMutable context, PostEventCommand next) {
super(document);
+ assert(handler != null);
this.handler = handler;
this.context = context;
this.next = next;
@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;
}
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);
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;
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) {
@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"
@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
""
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)));
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) {
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
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
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
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
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;
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;
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;
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);
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);
}
});
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;
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;
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;
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());
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) {
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);
* 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);
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);
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$
// 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();
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;
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;
</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">
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
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
Example:
> renameNode resource "NewName"
- "Succesfully renamed oldName to NewName"
+ "Successfully renamed oldName to NewName"
or error if failed
"""
Example:
> renameMBNode entity "NewName"
- "Succesfully renamed oldName to NewName"
+ "Successfully renamed oldName to NewName"
or error if failed
"""
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;
}
}
--- /dev/null
+/*******************************************************************************
+ * 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);
+ }
+
+ }
+
+}
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();
@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;
// 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)) {
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);
}
return null;
}
-
+
public static void convertDefaultValue(WriteGraph g,
Resource type, Resource relation, String newSCLType, Resource possibleType) throws DatabaseException {
Resource object = getAssertedObject(g, type, relation);
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) {
return;
}
}
+ } else {
+ return;
}
}
}
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));
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 {
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;
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
output.. = bin/
bin.includes = META-INF/,\
.,\
- graph.tg
+ graph.tg,\
+ scl/
src.includes = graph/
+/*******************************************************************************
+ * 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>
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
--- /dev/null
+/*******************************************************************************
+ * 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"
+/*******************************************************************************
+ * 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
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
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);
}
}
- 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);
}
}
- 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);
infixl 5 (\\), (<<), (<+)
infix 4 (!=), (<), (<=), (>=), (>)
infixr 3 (&&), (&<&)
-infixr 2 (||), orElse, morelse
+infixr 2 (||), orElse, orElseM, morelse
infixr 1 (>>=), (>>), (:=), (>=>)
infixr 1 ($)
infixl 1 catch
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;
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);
}
}
}
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) {