]> gerrit.simantics Code Review - simantics/platform.git/commitdiff
Merge "(refs #6878) Don't validate SCL expressions in console input area"
authorHannu Niemistö <hannu.niemisto@semantum.fi>
Wed, 17 May 2017 10:53:26 +0000 (13:53 +0300)
committerGerrit Code Review <gerrit2@www.simantics.org>
Wed, 17 May 2017 10:53:26 +0000 (13:53 +0300)
123 files changed:
bundles/org.simantics.acorn/src/org/simantics/acorn/lru/LRU.java
bundles/org.simantics.browsing.ui.swt/META-INF/MANIFEST.MF
bundles/org.simantics.browsing.ui.swt/src/org/simantics/browsing/ui/swt/widgets/SCLEditor.java [deleted file]
bundles/org.simantics.db.common/src/org/simantics/db/common/service/ServiceActivityMonitorImpl.java
bundles/org.simantics.db.layer0/adapters.xml
bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/migration/NamespaceMigrationStep.java
bundles/org.simantics.debug.ui/plugin.xml
bundles/org.simantics.debug.ui/src/org/simantics/debug/ui/internal/TGEditorAdapter.java [new file with mode: 0644]
bundles/org.simantics.diagram.profile/src/org/simantics/diagram/profile/view/SCLEditorComposite.java
bundles/org.simantics.diagram.svg/src/org/simantics/diagram/svg/export/DiagramToSVG.java
bundles/org.simantics.diagram/src/org/simantics/diagram/adapter/FlagClassFactory.java
bundles/org.simantics.diagram/src/org/simantics/diagram/flag/IFlagType.java
bundles/org.simantics.diagram/src/org/simantics/diagram/handler/Paster.java
bundles/org.simantics.diagram/src/org/simantics/diagram/profile/StyleBase.java
bundles/org.simantics.document.server.io/src/org/simantics/document/server/io/CommandContextImpl.java
bundles/org.simantics.document.server/scl/Document/All.scl
bundles/org.simantics.document.server/src/org/simantics/document/server/Functions.java
bundles/org.simantics.g2d/src/org/simantics/g2d/canvas/Hints.java
bundles/org.simantics.graph.db/META-INF/MANIFEST.MF
bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldMissingDependencyException.java [deleted file]
bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldTransferableGraphImportProcess1.java [deleted file]
bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldTransferableGraphs.java [deleted file]
bundles/org.simantics.graph/META-INF/MANIFEST.MF
bundles/org.simantics.graph/src/org/simantics/graph/query/TransferableGraphConversion.java
bundles/org.simantics.graph/src/org/simantics/graph/refactoring/GraphRefactoringUtils.java
bundles/org.simantics.graph/src/org/simantics/graph/refactoring/PrintReferencesTool.java [deleted file]
bundles/org.simantics.graph/src/org/simantics/graph/refactoring/RefactoringTool.java [deleted file]
bundles/org.simantics.graph/src/org/simantics/graph/representation/PrettyPrintTG.java
bundles/org.simantics.graph/src/org/simantics/graph/representation/old/OldTransferableGraph1.java [deleted file]
bundles/org.simantics.graph/src/org/simantics/graph/representation/old/OldValue1.java [deleted file]
bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/TestRefactoring.java [deleted file]
bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/TestRefactoring2.java [deleted file]
bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/mappingSpec.txt [deleted file]
bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/xor5.aprosSymbol [deleted file]
bundles/org.simantics.modeling.ui/META-INF/MANIFEST.MF
bundles/org.simantics.modeling.ui/scl/Simantics/Testing/BrowseContext.scl
bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/componentTypeEditor/PGraphEditorDocumentProvider.java
bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/pdf/PDFPainter.java
bundles/org.simantics.modeling/scl/Simantics/All.scl
bundles/org.simantics.modeling/scl/Simantics/Misc.scl
bundles/org.simantics.modeling/src/org/simantics/modeling/CompilePGraphs.java
bundles/org.simantics.modeling/src/org/simantics/modeling/ModelingUtils.java
bundles/org.simantics.modeling/src/org/simantics/modeling/scl/GraphModuleSourceRepository.java
bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/SVGNode.java
bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/connection/RouteGraphNode.java
bundles/org.simantics.scl.compiler.dummy/.classpath [deleted file]
bundles/org.simantics.scl.compiler.dummy/.project [deleted file]
bundles/org.simantics.scl.compiler.dummy/.settings/org.eclipse.jdt.core.prefs [deleted file]
bundles/org.simantics.scl.compiler.dummy/META-INF/MANIFEST.MF [deleted file]
bundles/org.simantics.scl.compiler.dummy/build.properties [deleted file]
bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/ErrorMessage.java [deleted file]
bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/InvalidInputException.java [deleted file]
bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompiler.java [deleted file]
bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompilerConfiguration.java [deleted file]
bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/StandardSCLCompilerConfiguration.java [deleted file]
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/CommandSession.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/TestScriptExecutor.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/common/names/Names.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/expressions/EApply.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/java/LoggingModule.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/internal/codegen/ssa/exits/Switch.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/internal/codegen/utils/ValueFromMethod.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/module/coverage/CoverageUtils.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/top/ExpressionEvaluator.java
bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/top/SCLExpressionCompilationException.java
bundles/org.simantics.scl.osgi/src/org/simantics/scl/osgi/SCLOsgi.java
bundles/org.simantics.scl.runtime/scl/Junit/Assert.scl [new file with mode: 0644]
bundles/org.simantics.scl.ui.editor/.classpath [deleted file]
bundles/org.simantics.scl.ui.editor/.gitignore [deleted file]
bundles/org.simantics.scl.ui.editor/.project [deleted file]
bundles/org.simantics.scl.ui.editor/.settings/org.eclipse.jdt.core.prefs [deleted file]
bundles/org.simantics.scl.ui.editor/META-INF/MANIFEST.MF [deleted file]
bundles/org.simantics.scl.ui.editor/build.properties [deleted file]
bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLAnnotationAccess.java [deleted file]
bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLSourceViewerConfiguration.java [deleted file]
bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLTextEditor.java [deleted file]
bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SharedTextColors.java [deleted file]
bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/TestTextEditor.java [deleted file]
bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/error_tsk.gif [deleted file]
bundles/org.simantics.scl.ui/src/org/simantics/scl/ui/editor2/SCLModuleEditor2.java
bundles/org.simantics.simulation/src/org/simantics/simulation/experiment/ExperimentUtil.java
bundles/org.simantics.spreadsheet.graph/META-INF/MANIFEST.MF
bundles/org.simantics.tests.modelled.ontology/META-INF/MANIFEST.MF
bundles/org.simantics.tests.modelled.ontology/graph/Tests.pgraph
bundles/org.simantics.tests.modelled.ui.ontology/META-INF/MANIFEST.MF
bundles/org.simantics.tests.modelled.ui.ontology/graph/TestsUI.pgraph
bundles/org.simantics.tests.modelled.ui.ontology/graph/images/testignored.gif [new file with mode: 0644]
bundles/org.simantics.tests.modelled.ui/META-INF/MANIFEST.MF
bundles/org.simantics.tests.modelled.ui/adapters.xml
bundles/org.simantics.tests.modelled.ui/plugin.xml
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/Activator.java
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSEditorAdapter.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSEditorInputFactory.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSTestEditor.java
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSTestEditorDocumentProvider.java
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSTestEditorInput.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSTestSuiteModel.java
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/adapters/IsTestIgnored.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/rules/TestImageRule.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled/META-INF/MANIFEST.MF
bundles/org.simantics.tests.modelled/adapters.xml [new file with mode: 0644]
bundles/org.simantics.tests.modelled/build.properties
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/RuntimeSTSRunner.java
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/RuntimeSTSSuiteRunner.java
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/RuntimeSTSTestRunner.java
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/RuntimeTestCollector.java
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSRunner.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSSuiteRunner.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSTestRunner.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/ModelledSTSSuite.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/ModelledSTSTest.java [new file with mode: 0644]
bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/STSSuiteTestCollector.java [new file with mode: 0644]
bundles/pom.xml
features/org.simantics.browsing.ui.feature/feature.xml
features/org.simantics.scl.feature/feature.xml
features/org.simantics.tests.modelled.feature/feature.xml
releng/org.simantics.sdk.build.p2.site/pom.xml
releng/org.simantics.sdk.build.targetdefinition/org.simantics.sdk.build.targetdefinition.target
releng/org.simantics.sdk.build.targetdefinition/simantics.target
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/ModuleRegressionTests.java
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/TestCommandSession.java
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Matching6.scl [new file with mode: 0644]
tests/org.simantics.scl.osgi.tests/src/org/simantics/scl/osgi/tests/TestSCLOsgi.java

index 80fec7032940ac3e7a6a1abbebb02325880a8bfc..690ba426f209afd52035ac875530b1f7e2b3d763 100644 (file)
@@ -556,14 +556,18 @@ public class LRU<MapKey,MapValue extends LRUObject<MapKey, MapValue>> {
                 boolean gotMutex = impl.tryAcquireMutex();
 
                 boolean done = false;
+                // TODO: fix this properly pleease
+                int count = 0;
                 while (!done) {
 
                     if (gotMutex || borrowMutex) {
                         runWithMutex();
                         done = true;
                     } else {
-                        LOGGER.warn("Retry mutex acquire");
+                        if (count % 100 == 0)
+                            LOGGER.warn("Retry mutex acquire");
                         gotMutex = impl.tryAcquireMutex();
+                        count++;
                     }
 
                 }
index 37466aedaec815dd3ae618a0c57592d90bfedc92..4eaa04be30a13ee80dc906ee7c41200992243257 100644 (file)
@@ -14,8 +14,6 @@ Require-Bundle: org.simantics.utils.thread.swt;bundle-version="1.0.0",
  org.simantics.g2d;bundle-version="[1.0.0,2.0.0)",
  org.eclipse.ui.forms;bundle-version="3.4.1",
  com.lowagie.text;bundle-version="2.1.5",
- org.simantics.scl.ui.editor;bundle-version="0.1.3";visibility:=reexport,
- org.simantics.scl.compiler.dummy;bundle-version="0.1.3",
  org.eclipse.e4.core.contexts;bundle-version="1.4.0",
  org.slf4j.api;bundle-version="1.7.20"
 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
diff --git a/bundles/org.simantics.browsing.ui.swt/src/org/simantics/browsing/ui/swt/widgets/SCLEditor.java b/bundles/org.simantics.browsing.ui.swt/src/org/simantics/browsing/ui/swt/widgets/SCLEditor.java
deleted file mode 100644 (file)
index 109d840..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2012 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
- *******************************************************************************/
-package org.simantics.browsing.ui.swt.widgets;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.simantics.browsing.ui.swt.widgets.impl.ReadFactory;
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
-import org.simantics.db.management.ISessionContext;
-import org.simantics.db.procedure.Listener;
-import org.simantics.scl.compiler.StandardSCLCompilerConfiguration;
-import org.simantics.scl.ui.editor.SCLTextEditor;
-import org.simantics.utils.ui.SWTUtils;
-
-public class SCLEditor extends WidgetImpl {
-
-       private ReadFactory<?, String> textFactory;
-       
-       final private SCLTextEditor editor;
-       
-       public SCLEditor(Composite parent, WidgetSupport support, int style) {
-               super(support);
-               editor = new SCLTextEditor(parent, style, StandardSCLCompilerConfiguration.INSTANCE);
-               support.register(this);
-       }
-       
-       public void setTextFactory(ReadFactory<?, String> textFactory) {
-               this.textFactory = textFactory;
-       }
-       
-       public SCLTextEditor getWidget() {
-               return editor;
-       }
-       
-       @Override
-       public Control getControl() {
-               return editor;
-       }
-
-       @Override
-       public void setInput(ISessionContext context, Object input) {
-
-               if(textFactory != null) {
-                       textFactory.listen(context, input, new Listener<String>() {
-
-                               public void exception(final Throwable t) {
-                                       SWTUtils.asyncExec(editor, new Runnable() {
-
-                                               @Override
-                                               public void run() {
-                                                       if(isDisposed()) return;
-//                                                     System.out.println("Button received new text: " + text);
-                                                       editor.setContent(t.toString());
-                                               }
-
-                                       });
-                               }
-
-                               @Override
-                               public void execute(final String s) {
-                                       SWTUtils.asyncExec(editor, new Runnable() {
-
-                                               @Override
-                                               public void run() {
-                                                       if(isDisposed()) return;
-                                                       editor.setContent(s);
-                                               }
-
-                                       });
-                               }
-
-                               @Override
-                               public boolean isDisposed() {
-                                       return editor.isDisposed();
-                               }
-
-                       });
-               
-               }
-               
-       }
-       
-       public void setContent(String s) {
-               editor.setContent(s);
-       }
-       
-       public String getContent() {
-               return editor.getContent();
-       }
-
-}
index 1858e87ddea8af1249af7343f95cb1a2037548ae..541380dc59e250567a0ad647e5829c2e9d7fdf13 100644 (file)
@@ -5,12 +5,16 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.simantics.db.service.ServiceActivityMonitor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import gnu.trove.map.TObjectIntMap;
 import gnu.trove.map.hash.TObjectIntHashMap;
 
 public class ServiceActivityMonitorImpl implements ServiceActivityMonitor {
 
+    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceActivityMonitorImpl.class);
+
     public static final long REPORTING_PERIOD = 5L;
     
     Semaphore sem = new Semaphore(1);
@@ -46,8 +50,8 @@ public class ServiceActivityMonitorImpl implements ServiceActivityMonitor {
             if(waitForCompletion(REPORTING_PERIOD, TimeUnit.SECONDS))
                 return;
             synchronized (ids) {
-                System.err.println("ServiceActivityMonitorImpl.waitForCompletion: " + ids);
-            }    
+                LOGGER.info("waitForCompletion: " + ids);
+            }
         }
     }
 
index 13fbd87b2b7c5d03ca082e011d17e968bd470721..5586b5fd1c8598e459b411d81310596ee54b1386 100644 (file)
                        class="org.simantics.db.layer0.adapter.impl.SharedOntologyCopyHandler">
                        <this />
                </type>
+               <type
+                       uri="http://www.simantics.org/Layer0-0.0/Ontology"
+                       class="org.simantics.db.layer0.adapter.impl.SharedOntologyCopyHandler">
+                       <this />
+               </type>
        </target>
 
        <target
index 1262f3909d92bf6895f5a13b15e86d86e103c15a..a0d4f9da5e202f87a893aa76556c942b83c81e1b 100644 (file)
@@ -11,8 +11,6 @@
  *******************************************************************************/
 package org.simantics.db.layer0.migration;
 
-import gnu.trove.set.hash.TIntHashSet;
-
 import java.util.ArrayList;
 
 import org.eclipse.core.runtime.IProgressMonitor;
@@ -29,12 +27,19 @@ import org.simantics.graph.refactoring.GraphRefactoringException;
 import org.simantics.graph.refactoring.GraphRefactoringUtils;
 import org.simantics.graph.refactoring.MappingSpecification;
 import org.simantics.graph.refactoring.MappingSpecification.MappingRule;
+import org.simantics.graph.representation.Identity;
+import org.simantics.graph.representation.Internal;
 import org.simantics.graph.representation.TransferableGraph1;
 import org.simantics.graph.store.IdentityStore;
 import org.simantics.layer0.Layer0;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import gnu.trove.set.hash.TIntHashSet;
 
 public class NamespaceMigrationStep implements MigrationStep {
-       
+    private static final Logger LOGGER = LoggerFactory.getLogger(NamespaceMigrationStep.class);
+
     final ArrayList<MappingRule> rules;
     
        public NamespaceMigrationStep(ReadGraph graph, Resource step) throws DatabaseException {
@@ -50,7 +55,7 @@ public class NamespaceMigrationStep implements MigrationStep {
                                if(fromURI != null && toURI != null)
                                        rules.add(new MappingRule(fromURI, toURI));
                                else
-                                       System.err.println("Namespace migration uri formation error: base " + base + " from " + from + " to " + to);
+                                   LOGGER.error("Namespace migration uri formation error: base " + base + " from " + from + " to " + to);
                        }
                }
        }
@@ -63,9 +68,13 @@ public class NamespaceMigrationStep implements MigrationStep {
         try {
             MappingSpecification mappingSpec = new MappingSpecification(rules);
             boolean fixed = GraphRefactoringUtils.fixIncorrectRoot(tg.identities);
-            System.err.println("fixed=" + fixed);
+            LOGGER.info("fixed=" + fixed);
             IdentityStore idStore = TransferableGraphConversion.extractIdentities(tg);
-            idStore.printChildMap();
+            // Mark internal identities new
+            for(Identity id : tg.identities)
+                if(id.definition instanceof Internal)
+                    idStore.markNew(id.resource);
+//            idStore.printChildMap();
 //            System.err.println("ids: " + idStore);
 //            System.err.println("rc: " + tg.resourceCount);
 //            System.err.println("idStore: " + idStore.toArray().length);
@@ -79,7 +88,7 @@ public class NamespaceMigrationStep implements MigrationStep {
             if(fixed)
                 GraphRefactoringUtils.unfixIncorrectRoot(tg.identities);
 
-            System.err.println("rc2: " + tg.resourceCount);
+            LOGGER.info("rc2: " + tg.resourceCount);
 //            System.err.println("idStore2: " + idStore.toArray().length);
 
         } catch (GraphRefactoringException e) {
index 6ed0b55c213ffad78bb011b8a12e5e5b175470e1..abceb0952ea63ebaf17abad361e0ca8fa2c97c24 100644 (file)
             id="org.simantics.debug.adapter2"
             priority="-1">
       </adapterClass>
+      <adapterClass
+            class="org.simantics.debug.ui.internal.TGEditorAdapter"
+            id="org.simantics.debug.adapter3"
+            priority="-1">
+      </adapterClass>
    </extension>
 
    <extension
diff --git a/bundles/org.simantics.debug.ui/src/org/simantics/debug/ui/internal/TGEditorAdapter.java b/bundles/org.simantics.debug.ui/src/org/simantics/debug/ui/internal/TGEditorAdapter.java
new file mode 100644 (file)
index 0000000..a941ecb
--- /dev/null
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2010 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
+ *******************************************************************************/
+package org.simantics.debug.ui.internal;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.PossibleIndexRoot;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.layer0.Layer0;
+import org.simantics.ui.SimanticsUI;
+import org.simantics.ui.workbench.ResourceEditorInput;
+import org.simantics.ui.workbench.editor.AbstractResourceEditorAdapter;
+
+/**
+ * @author Antti Villberg
+ */
+public class TGEditorAdapter extends AbstractResourceEditorAdapter {
+
+       public static final String EDITOR_ID = "org.simantics.modeling.ui.pgraphEditor";
+       
+    public TGEditorAdapter() {
+        super("Ontology Viewer", SimanticsUI.getImageDescriptor("icons/etool16/bug.png"));
+    }
+
+    @Override
+    public boolean canHandle(ReadGraph g, Resource r) throws DatabaseException {
+       Resource indexRoot = g.syncRequest(new PossibleIndexRoot(r));
+       if(indexRoot == null) return false;
+       Layer0 L0 = Layer0.getInstance(g);
+       return g.isInstanceOf(indexRoot, L0.Ontology);
+    }
+
+    @Override
+    public void openEditor(Resource r) throws Exception {
+        openEditorWithId(EDITOR_ID, new ResourceEditorInput(EDITOR_ID,r));
+    }
+    
+}
index c73efe63f1b3df5a549bd5f6ab183d922db24b81..391648b62117b6c9b0add1664def09f31355fc37 100644 (file)
@@ -18,8 +18,8 @@ import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Display;
 import org.eclipse.ui.IWorkbenchSite;
 import org.simantics.browsing.ui.swt.widgets.Button;
-import org.simantics.browsing.ui.swt.widgets.SCLEditor;
 import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;
+import org.simantics.browsing.ui.swt.widgets.Text;
 import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;
 import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
 import org.simantics.db.Resource;
@@ -32,7 +32,7 @@ import org.simantics.selectionview.ConfigurationComposite;
 
 public class SCLEditorComposite extends ConfigurationComposite {
     
-       private SCLEditor editor;
+       private Text editor;
        
     public void create(Composite body, IWorkbenchSite site, ISessionContext context, final WidgetSupport support) {
         
@@ -47,10 +47,10 @@ public class SCLEditorComposite extends ConfigurationComposite {
                
                @Override
                public void beforeApply() {
-                       content = editor.getContent();
-                       editor.getWidget().storeSelectedRange();
+                       content = editor.getWidget().getText();
+                       //editor.getWidget().storeSelectedRange();
                        editor.getControl().setFocus();
-                       editor.getWidget().restoreSelectedRange();
+                       //editor.getWidget().restoreSelectedRange();
                }
                
                        @Override
@@ -61,7 +61,7 @@ public class SCLEditorComposite extends ConfigurationComposite {
                        
                });
        
-       editor = new SCLEditor(body, support, SWT.BORDER | SWT.FLAT);
+       editor = new Text(body, support, SWT.BORDER | SWT.FLAT);
        editor.setTextFactory(new StringPropertyFactory(Layer0X.URIs.HasExpression));
        //editor.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasExpression));
        GridDataFactory.fillDefaults().grab(true, true).span(2, 1).applyTo(editor.getControl());
index 3c110976294a86bf1aa2414ea50eda567881365b..9964592f95c6136eed0b38a426fc840db49e4ca3 100644 (file)
@@ -20,6 +20,7 @@ import org.simantics.db.request.Read;
 import org.simantics.diagram.elements.DiagramNodeUtil;
 import org.simantics.diagram.export.ImagePrinter;
 import org.simantics.diagram.stubs.DiagramResource;
+import org.simantics.g2d.canvas.Hints;
 import org.simantics.g2d.canvas.impl.CanvasContext;
 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
 import org.simantics.layer0.Layer0;
@@ -29,6 +30,7 @@ import org.simantics.structural2.StructuralVariables;
 import org.simantics.utils.DataContainer;
 import org.simantics.utils.datastructures.Pair;
 import org.simantics.utils.page.MarginUtils.Margins;
+import org.simantics.utils.threads.IThreadWorkQueue;
 import org.simantics.utils.threads.ThreadUtils;
 import org.simantics.utils.threads.WorkerThread;
 
@@ -127,13 +129,11 @@ public class DiagramToSVG {
                if (diagram == null)
                        throw new DatabaseException("Input " + input + " cannot be resolved as diagram");
                
-               
-       
-               
                final WorkerThread thread = new WorkerThread("Diagram Image Painter");
                thread.start();
                
         final CanvasContext ctx = new CanvasContext(thread);
+        ctx.getDefaultHintContext().setHint(Hints.KEY_DISABLE_GRAPH_MODIFICATIONS, Boolean.TRUE);
         final AtomicReference<ICanvasSceneGraphProvider> sgProvider = new AtomicReference<ICanvasSceneGraphProvider>();
                final ISessionContext sessionContext = Simantics.getSessionContext();
                final DataContainer<String> result = new DataContainer<String>(null);
@@ -203,8 +203,6 @@ public class DiagramToSVG {
         return model;
     }
 
-
-
     private static String resolveRVI(ReadGraph graph, Resource diagram) throws DatabaseException {
        ModelingResources mod = ModelingResources.getInstance(graph);
         Resource composite = graph.getSingleObject(diagram, mod.DiagramToComposite);
@@ -213,4 +211,74 @@ public class DiagramToSVG {
         return StructuralVariables.getRVI(graph, variablePath);
     }
 
+       public static String renderWithLoader(final Resource input, final ImagePrinter.ImageExportPlan exportPlan,
+                       Margins margins, SVGGraphics2D svgExporter,
+                       IThreadWorkQueue loaderThread,
+                       IThreadWorkQueue painterThread) throws Exception {
+
+               if(!painterThread.currentThreadAccess()) throw new IllegalStateException("The callable should be called from the contextThread");
+
+               final CanvasContext ctx = new CanvasContext(loaderThread);
+               ctx.getDefaultHintContext().setHint(Hints.KEY_DISABLE_GRAPH_MODIFICATIONS, Boolean.TRUE);
+               final AtomicReference<ICanvasSceneGraphProvider> sgProvider = new AtomicReference<ICanvasSceneGraphProvider>();
+               final DataContainer<String> result = new DataContainer<String>(null);
+               final DataContainer<Exception> exception = new DataContainer<Exception>(null);
+
+               try {
+                       
+                       final ISessionContext sessionContext = Simantics.getSessionContext();
+
+                       Pair<Resource, String> modelAndRVI = sessionContext.getSession().syncRequest(new UniqueRead<Pair<Resource, String>>() {
+                               @Override
+                               public Pair<Resource, String> perform(ReadGraph graph) throws DatabaseException {
+                                       return new Pair<Resource, String>( resolveModel(graph, exportPlan.diagram ), resolveRVI(graph, exportPlan.diagram) );
+                               }
+                       });
+
+                       ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(ctx, modelAndRVI.first, exportPlan.diagram, modelAndRVI.second);
+                       sgProvider.set( provider );
+
+                       final Semaphore done = new Semaphore(0);
+
+                       ThreadUtils.asyncExec(loaderThread, new Runnable() {
+                               @Override
+                               public void run() {
+                                       try {
+                                               SVGBuilder chassis = margins != null ?
+                                                               new SVGBuilder(exportPlan.dpi,exportPlan.size,margins) :
+                                                                       new SVGBuilder(exportPlan.dpi,exportPlan.size,exportPlan.margin);
+                                                               result.set(chassis.paint(ctx, svgExporter));
+                                       } catch (DatabaseException e) {
+                                               exception.set(e);
+                                               done.release();
+                                       } catch (Throwable e) {
+                                               exception.set(new DatabaseException(e));
+                                               done.release();
+                                       } finally {
+                                               done.release();
+                                       }
+                               }
+                       });
+
+                       done.acquire();
+
+               } catch (DatabaseException e) {
+                       exception.set(e);
+               } catch (Throwable e) {
+                       exception.set(new DatabaseException(e));
+               } finally {
+
+                       if (sgProvider.get() != null)
+                               sgProvider.get().dispose();
+                       ctx.dispose();
+
+               }
+
+               if(exception.get() != null) 
+                       throw exception.get();
+
+               return result.get();
+               
+       }
+       
 }
index 30efa54f0301b3724f2fe0f95e88e5df56c6e202..56c2ceef42ae172e53f5aae6624e568bd9f23d13 100644 (file)
@@ -184,7 +184,7 @@ public class FlagClassFactory extends SyncElementFactory {
             if (ftr != null) {
                 IFlagType ft = ftr.read(g, flag, modelingRules);
 
-                FlagInfo info = ft.getInfo(g);
+                FlagInfo info = ft.getInfo(g, canvas);
 
                 Shape shape = info.getShape();
                 if (shape != null) {
index 8176d1e7931081fdc66665ff1cb1065b2d4731c0..0c5974a8f54f968030f4ebbc695cc032f6c7363e 100644 (file)
@@ -17,6 +17,7 @@ import java.awt.geom.Rectangle2D;
 
 import org.simantics.db.ReadGraph;
 import org.simantics.db.exception.DatabaseException;
+import org.simantics.g2d.canvas.ICanvasContext;
 import org.simantics.g2d.elementclass.FlagClass;
 import org.simantics.g2d.utils.Alignment;
 
@@ -46,7 +47,23 @@ public interface IFlagType {
      * @param graph database read access
      * @return all info gathered up about the flag
      * @throws DatabaseException
+     * @Deprecated implement {@link #getInfo(ReadGraph, ICanvasContext)} instead
      */
-    FlagInfo getInfo(ReadGraph graph) throws DatabaseException;
+    default FlagInfo getInfo(ReadGraph graph) throws DatabaseException {
+        throw new UnsupportedOperationException();
+    }
+
+    /**
+     * Reads and calculates information about this flags graphical
+     * representation.
+     * 
+     * @param graph database read access
+     * @param context the canvas context with which the info is loaded 
+     * @return all info gathered up about the flag
+     * @throws DatabaseException
+     */
+    default FlagInfo getInfo(ReadGraph graph, ICanvasContext context) throws DatabaseException {
+        return getInfo(graph);
+    }
 
 }
index c8995f4c1f4777be79311bc0d502616af534f147..6672599073b1b18e717bd1f79c36f6e3ac0bdb78 100644 (file)
@@ -1364,4 +1364,8 @@ public class Paster {
     protected PasteOperation getOperation() {
        return op;
     }
+    
+    public WriteGraph getGraph() {
+               return graph;
+       }
 }
index 5aed90b48931b2a15bb911b0986860d96e01481f..ee203616da950f31d0fa1f1abbfae793de988f2d 100644 (file)
@@ -457,7 +457,11 @@ public abstract class StyleBase<Result> implements Style {
      * @param items the diagram data items that need to be cleaned up
      */
     protected final void cleanupItems(final EvaluationContext evaluationContext, final IDiagram diagram, final Object[] items) {
-        AWTThread.getThreadAccess().asyncExec(new Runnable() {
+
+        ICanvasContext context = evaluationContext.getConstant(ProfileKeys.CANVAS);
+
+       context.getThreadAccess().asyncExec(new Runnable() {
+               
             @Override
             public void run() {
                 
index 3277bbd1edfe02440a1b944f7f6c192c4808875c..5b49810fad9f8109c5a4a637ab24444ea3bf059c 100644 (file)
@@ -80,11 +80,24 @@ public class CommandContextImpl implements CommandContextMutable {
        @Override
        public String toString() {
                StringBuilder sb = new StringBuilder();
+               sb.append("CommandContext:\n");
                for (Map.Entry<String, List<List<Object>>> entry : data.entrySet()) {
-                        sb.append(entry.getKey());
-                        sb.append(":");
-                        sb.append(entry.getValue());
-                        sb.append("\n");
+                       String key = entry.getKey();
+                       if(key.startsWith("__")) continue;
+                       sb.append(key);
+                       sb.append(":");
+                       List<List<Object>> value = entry.getValue();
+                       if(value.size() == 1) {
+                               List<Object> t = (List<Object>)value.get(0);
+                               if(t.size() == 2) {
+                                       sb.append(t.get(1));
+                               } else {
+                                       sb.append(t);
+                               }
+                       } else {
+                               sb.append(value);
+                       }
+                       sb.append("\n");
                }
                return sb.toString();
        }
index fa83a224acfc2d7076af4417e2f2e181680e93e7..7781cfdb3ffaa9595eb322be7d01ffc286bf48c0 100644 (file)
@@ -85,6 +85,9 @@ instance Coercible CommandContextMutable CommandContext where
 cloneCommandContext :: CommandContext -> <Proc> CommandContextMutable
 cloneCommandContext context = merge (commandContext ()) context
 
+instance Show CommandContext where
+    show ctx = printContext ctx
+
 importJava "org.simantics.document.server.io.CommandResult" where
     data CommandResult
 
@@ -143,10 +146,10 @@ displayValue var str = propertyValue (property var str) "HasDisplayValue"
 displayValue0 :: Variable -> <ReadGraph> String
 displayValue0 var = propertyValue var "HasDisplayValue"
 
-consoleLog :: Variable -> String -> <ReadGraph> ()
-consoleLog state message = do
-    console = state#console
-    runProc $ addMessage console message
+consoleLog :: CommandContext -> String -> ()
+consoleLog context message = match possibleValue context "console" with
+  Nothing -> ()
+  Just console -> runProc $ addMessage console message
 
 contextDocument :: CommandContext -> <Proc> IDocument
 contextDocument ctx = justValue ctx "__document__"
index 25bec0c919248d5efc14c54d921f3b3f5ea5fbba..20fa2a71b7b272cec574e351c715a17c25479f04 100644 (file)
@@ -51,6 +51,7 @@ 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.server.io.CommandResult;
+import org.simantics.document.server.io.IConsole;
 import org.simantics.document.server.request.ServerSCLHandlerValueRequest;
 import org.simantics.document.server.request.ServerSCLValueRequest;
 import org.simantics.document.server.serverResponse.ServerResponse;
@@ -674,7 +675,9 @@ public class Functions {
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
                                
-                final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
+                               IConsole console = parameters.getValue("__console__");
+                               SCLReportingHandler printer = (console != null) ? new ConsoleSCLReportingHandler(console)
+                                               : (SCLReportingHandler) SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
                 
                 try {
                        
@@ -727,7 +730,15 @@ public class Functions {
                                });
 
                        } else {
-                               result = fn.apply(parameters);
+                               
+                                               SCLContext sclContext = SCLContext.getCurrent();
+                                               Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
+                                               try {
+                                                       result = fn.apply(parameters);
+                                               } finally {
+                                                       sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
+                                               }
+
                        }
 
                        if (result instanceof org.simantics.document.server.serverResponse.Error) {
@@ -970,9 +981,7 @@ public class Functions {
     }
     
     public static String printContext(CommandContext context) {
-       String str = context.toString();
-       System.err.println(str);
-       return str;
+       return context.toString();
     }
     
     @SCLValue(type = "AbstractEventHandler")
@@ -1164,4 +1173,35 @@ public class Functions {
        return graph.syncRequest(new PathExistsRequest(context));
     }
     
+       static class ConsoleSCLReportingHandler implements SCLReportingHandler {
+
+               private final IConsole console;
+
+               ConsoleSCLReportingHandler(IConsole console) {
+                       this.console = console;
+               }
+
+               @Override
+               public void print(String text) {
+                       console.addMessage(text);
+               }
+
+               @Override
+               public void printError(String error) {
+                       console.addMessage(error);
+               }
+
+               @Override
+               public void printCommand(String command) {
+                       console.addMessage(command);
+               }
+
+               @Override
+               public void didWork(double amount) {
+                       console.addMessage("didWork " + amount);
+               }
+
+       }
+    
+    
 }
\ No newline at end of file
index cf5f70610210ff7646828f9273dc33b6964ae4b2..3fd43f0f08dd17121ac5bc43e3aeb2c4d22af20e 100644 (file)
@@ -92,8 +92,14 @@ public class Hints {
      * Set to true when the canvas is rendering to a printer
      */
     public static final Key KEY_PRINT = new KeyOf(Boolean.class, "PRINTING");
-   
-    
+
+    /**
+     * Set this hint to <code>true</code> to prevent any modifications from
+     * being made to the diagram model by the diagram loading logic. Using this
+     * may be necessary for printing.
+     */
+    public static final Key KEY_DISABLE_GRAPH_MODIFICATIONS = new KeyOf(Boolean.class, "DISABLE_GRAPH_MODIFICATIONS");
+
     private interface Dirty {}
 
     /**
index f21b3e776dd1dd7cd981113b6da07374c1b9c9f4..165a104edcb543c35a24b29ad32ed016675a46bc 100644 (file)
@@ -9,6 +9,5 @@ Require-Bundle: org.simantics.graph;bundle-version="1.0.0";visibility:=reexport,
  gnu.trove3;bundle-version="3.0.3",
  org.simantics.layer0;bundle-version="1.0.0",
  org.slf4j.api;bundle-version="1.7.2"
-Export-Package: org.simantics.graph.db,
- org.simantics.graph.db.old
+Export-Package: org.simantics.graph.db
 Bundle-Vendor: VTT Technical Research Centre of Finland
diff --git a/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldMissingDependencyException.java b/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldMissingDependencyException.java
deleted file mode 100644 (file)
index 7ca83f3..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-package org.simantics.graph.db.old;
-
-import java.util.Set;
-
-import org.simantics.db.exception.DatabaseException;
-
-public class OldMissingDependencyException extends DatabaseException {
-
-       private static final long serialVersionUID = -1579450497603555931L;
-       
-       private final OldTransferableGraphImportProcess1 process;
-       
-       public OldMissingDependencyException(OldTransferableGraphImportProcess1 process) {
-               super(createMessage(process));
-               this.process = process;
-       }
-
-       private static String createMessage(OldTransferableGraphImportProcess1 process) {
-               StringBuilder b = new StringBuilder();
-               b.append("The following references were not found:\r\n");
-               for(String missing : process.missingExternals) {
-                       b.append(" -" + missing + "\r\n");
-               }
-               return b.toString();
-       }
-       
-       public Set<String> getMissingURIs() {
-               return process.missingExternals;
-       }
-
-}
diff --git a/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldTransferableGraphImportProcess1.java b/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldTransferableGraphImportProcess1.java
deleted file mode 100644 (file)
index 6a69e8d..0000000
+++ /dev/null
@@ -1,479 +0,0 @@
-package org.simantics.graph.db.old;
-
-import java.io.DataOutput;
-import java.io.DataOutputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.simantics.databoard.Bindings;
-import org.simantics.databoard.adapter.AdaptException;
-import org.simantics.databoard.binding.mutable.Variant;
-import org.simantics.db.ReadGraph;
-import org.simantics.db.Resource;
-import org.simantics.db.VirtualGraph;
-import org.simantics.db.WriteOnlyGraph;
-import org.simantics.db.common.WriteBindings;
-import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
-import org.simantics.db.common.uri.UnescapedChildMapOfResource;
-import org.simantics.db.common.utils.Logger;
-import org.simantics.db.exception.DatabaseException;
-import org.simantics.db.exception.ResourceNotFoundException;
-import org.simantics.db.service.ClusterBuilder;
-import org.simantics.db.service.ClusterBuilder.ResourceHandle;
-import org.simantics.db.service.SerialisationSupport;
-import org.simantics.db.service.TransferableGraphSupport;
-import org.simantics.graph.db.CoreInitialization;
-import org.simantics.graph.db.IImportAdvisor;
-import org.simantics.graph.representation.Extensions;
-import org.simantics.graph.representation.External;
-import org.simantics.graph.representation.Identity;
-import org.simantics.graph.representation.IdentityDefinition;
-import org.simantics.graph.representation.Internal;
-import org.simantics.graph.representation.Optional;
-import org.simantics.graph.representation.Root;
-import org.simantics.graph.representation.TransferableGraphUtils;
-import org.simantics.graph.representation.old.OldTransferableGraph1;
-import org.simantics.graph.representation.old.OldValue1;
-
-public class OldTransferableGraphImportProcess1 {
-       
-    public static String LOG_FILE = "transferableGraphs.log";
-    final static private boolean LOG = false;
-    
-    static DataOutput log;
-
-    static {
-
-        if (LOG) {
-            try {
-                FileOutputStream stream = new FileOutputStream(LOG_FILE);
-                log = new DataOutputStream(stream);
-            } catch (FileNotFoundException e) {
-                e.printStackTrace();
-            }
-        }
-
-    }
-    
-    private static void log(String line) {
-        if (LOG) {
-            try {
-                log.writeUTF(line + "\n");
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-        }
-    }
-    
-    OldTransferableGraph1 tg;
-    IImportAdvisor advisor;
-    
-    Resource[] resources;
-    ResourceHandle[] handles;
-    
-    Set<String> missingExternals = new HashSet<String>(); 
-    
-    // Builtins
-    Resource RootLibrary;
-    Resource String;
-    Resource Library;
-    
-    Resource InstanceOf;
-    Resource ConsistsOf;
-    Resource PartOf;
-    Resource HasName;
-    Resource NameOf;    
-                
-    public OldTransferableGraphImportProcess1(OldTransferableGraph1 tg, IImportAdvisor advisor) {
-        this.tg = tg;
-        this.advisor = advisor;
-        /*System.out.println("Transferable graph identities:");
-        for(Identity id : tg.identities) {
-            if(id.definition instanceof Internal) {
-                Internal def = (Internal)id.definition;
-                System.out.println("    internal " + def.name);
-            }
-            else if(id.definition instanceof External) {
-                External def = (External)id.definition;
-                System.out.println("    external " + def.name);
-            }
-        }*/
-    }
-    
-    public void findBuiltins(WriteOnlyGraph g) throws DatabaseException {
-        RootLibrary = g.getBuiltin("http:/");
-        String = g.getBuiltin(CoreInitialization.LAYER0 + "String");
-        Library = g.getBuiltin(CoreInitialization.LAYER0 + "Library");
-        InstanceOf = g.getBuiltin(CoreInitialization.LAYER0 + "InstanceOf");
-        ConsistsOf = g.getBuiltin(CoreInitialization.LAYER0 + "ConsistsOf");
-        PartOf = g.getBuiltin(CoreInitialization.LAYER0 + "PartOf");
-        HasName = g.getBuiltin(CoreInitialization.LAYER0 + "HasName");
-        NameOf = g.getBuiltin(CoreInitialization.LAYER0 + "NameOf");
-    }
-    
-    public void findBuiltins(ReadGraph g) throws DatabaseException {
-        RootLibrary = g.getBuiltin("http:/");
-        String = g.getBuiltin(CoreInitialization.LAYER0 + "String");
-        Library = g.getBuiltin(CoreInitialization.LAYER0 + "Library");
-        InstanceOf = g.getBuiltin(CoreInitialization.LAYER0 + "InstanceOf");
-        ConsistsOf = g.getBuiltin(CoreInitialization.LAYER0 + "ConsistsOf");
-        PartOf = g.getBuiltin(CoreInitialization.LAYER0 + "PartOf");
-        HasName = g.getBuiltin(CoreInitialization.LAYER0 + "HasName");
-        NameOf = g.getBuiltin(CoreInitialization.LAYER0 + "NameOf");
-    }
-
-    /* Preparation that is used when the core is empty. 
-     */
-    void initialPrepare(WriteOnlyGraph graph) throws DatabaseException {
-        findBuiltins(graph);
-        
-        resources = new Resource[tg.resourceCount];
-        
-        int Root = -1;
-        int SimanticsDomain = -1;
-        int Layer0 = -1;
-        
-        for(Identity identity : tg.identities) {
-            if(identity.definition instanceof Internal) {
-                Internal def = (Internal)identity.definition;
-                Resource res = null;
-                if(def.parent == Layer0) {
-                    try {
-                        res = graph.getBuiltin(CoreInitialization.LAYER0 + def.name);
-                    } catch(ResourceNotFoundException e) {                                      
-                    }
-                }
-                else if(def.parent == SimanticsDomain) {
-                    if(def.name.equals("Layer0-1.1"))
-                        Layer0 = identity.resource;
-                }
-                else if(def.parent == Root) {
-                    if(def.name.equals("www.simantics.org"))
-                        SimanticsDomain = identity.resource;
-                }
-
-                if(res == null)
-                    res = createChild(graph, resources[def.parent], def.name);
-                else
-                    createChild(graph, res, resources[def.parent], def.name);
-                resources[identity.resource] = res;
-            }
-            else if(identity.definition instanceof Root) {
-                Root = identity.resource;
-                resources[identity.resource] = RootLibrary;             
-            } 
-        }
-    }
-    
-    void addMissing(String external) {
-        Set<String> removals = new HashSet<String>();
-        for(String ext : missingExternals) if(ext.startsWith(external)) return;
-        for(String ext : missingExternals) if(external.startsWith(ext)) removals.add(ext);
-        missingExternals.removeAll(removals);
-        missingExternals.add(external);
-    }
-    
-    void prepare(ReadGraph graph) throws DatabaseException {
-        findBuiltins(graph);
-        
-        Resource[] resources = new Resource[tg.resourceCount];
-        
-        for(Identity identity : tg.identities) {
-            IdentityDefinition definition = identity.definition;
-            if(definition instanceof External) {
-                External def = (External)definition;
-                if(def.parent == -1) {
-                    resources[identity.resource] = RootLibrary;
-                } else {
-                    if("@inverse".equals(def.name)) {
-                        Resource parent = resources[def.parent];
-                        Resource child = graph.getInverse(parent);
-                        resources[identity.resource] = child;
-                    } else {
-                        Resource parent = resources[def.parent];
-                        // TODO: escape should be removed when names become well-behaving
-                        if(parent != null) {
-                            Resource child = graph
-                            .syncRequest(new UnescapedChildMapOfResource(parent),
-                                    new TransientCacheAsyncListener<Map<String, Resource>>())
-                                    .get(def.name);
-                            if(child == null) {
-                                addMissing(graph.getURI(parent) + "/" + def.name);
-                            }
-                            resources[identity.resource] = child;
-                        } else {
-                            addMissing(TransferableGraphUtils.getURI(tg.resourceCount, tg.identities, def.parent) + "/" + def.name);
-                        }
-                    }
-                }
-            }
-            else if(definition instanceof Internal) {
-                // Do not do anything for now
-            }
-            else if(definition instanceof Root) {
-                Root root = (Root)definition;
-                if(root.name.equals(""))
-                    resources[identity.resource] = RootLibrary;
-                else 
-                    advisor.analyzeRoot(graph, root);                   
-            }
-            else if(definition instanceof Optional) {
-                External def = (External)definition;
-                Resource parent = resources[def.parent];
-                if(parent != null)
-                    resources[identity.resource] = 
-                        graph.syncRequest(new UnescapedChildMapOfResource(parent)).get(def.name);               
-            }
-        }       
-        
-        this.resources = resources;
-        
-        if(!missingExternals.isEmpty()) throw new OldMissingDependencyException(this);
-        
-    }
-
-    Resource createChild(WriteOnlyGraph graph, Resource parent, String name) throws DatabaseException {
-        Resource child = graph.newResource();
-        graph.claim(parent, ConsistsOf, PartOf, child);
-        Resource nameResource = graph.newResource();
-        graph.claim(nameResource, InstanceOf, null, String);
-        graph.claimValue(nameResource, name, WriteBindings.STRING);
-        graph.claim(child, HasName, NameOf, nameResource);
-        return child;
-    }
-    
-    void createChild(WriteOnlyGraph graph, Resource child, Resource parent, String name) throws DatabaseException {
-        graph.claim(parent, ConsistsOf, PartOf, child);
-        Resource nameResource = graph.newResource();
-        graph.claim(nameResource, InstanceOf, null, String);
-        graph.claimValue(nameResource, name, WriteBindings.STRING);
-        graph.claim(child, HasName, NameOf, nameResource);
-    }
-    
-    int[] getClustering() {
-        Variant v = tg.extensions.get(Extensions.CLUSTERING);
-        if(v == null) return null;
-        try {
-            return (int[])v.getValue(Bindings.INT_ARRAY);
-        } catch (AdaptException e) {
-            Logger.defaultLogError(e);
-            return null;
-        }
-    }
-    
-    void write(WriteOnlyGraph graph) throws DatabaseException {
-
-        Resource[] resources = this.resources;
-
-        this.handles = new ResourceHandle[resources.length];
-        
-        ResourceHandle[] handles = this.handles; 
-
-        int[] clustering = getClustering();
-
-        // Internal identities      
-        for(Identity identity : tg.identities) {
-            IdentityDefinition definition = identity.definition;
-            if(resources[identity.resource] != null)
-                continue;
-            if(definition instanceof External) {
-                // Already done everything
-            }
-            else if(definition instanceof Internal) {
-                Internal def = (Internal)definition;
-                resources[identity.resource] = 
-                    createChild(graph, resources[def.parent], def.name);
-            }
-            else if(definition instanceof Root) {
-                Root root = (Root)definition;               
-                resources[identity.resource] = advisor.createRoot(graph, root);                 
-            }
-            else if(definition instanceof Optional) {
-                Optional def = (Optional)definition;
-                Resource child = createChild(graph, resources[def.parent], def.name);
-                graph.claim(child, InstanceOf, null, Library); // ???
-                resources[identity.resource] = child;                   
-            }
-        }       
-
-        ClusterBuilder builder = graph.getService(ClusterBuilder.class);
-        SerialisationSupport ss = graph.getService(SerialisationSupport.class);
-
-        if(clustering != null) {
-            
-            int i = 0;
-            for(int c : clustering) {
-                builder.newCluster();
-                for(int r=0;r<c;r++, i++)
-                    if(resources[i] == null)
-                        handles[i] = builder.newResource();
-                    else 
-                        handles[i] = builder.resource(resources[i]);
-
-            }
-
-            for(;i<resources.length;++i)
-                if(resources[i] == null)
-                    handles[i] = builder.newResource();
-                else 
-                    handles[i] = builder.resource(resources[i]);
-            
-        } else {
-        
-            // Create blank resources
-            for(int i=0;i<resources.length;++i)
-                if(resources[i] == null)
-                    handles[i] = builder.newResource();
-                else 
-                    handles[i] = builder.resource(resources[i]);
-
-        }
-        
-        // Write statements
-        int[] statements = tg.statements;
-        
-        int internals = tg.resourceCount - tg.identities.length;
-        
-        for(int i=0;i<statements.length;i+=4) {
-
-            int sub = statements[i];
-            int pred = statements[i+1];
-            int inv = statements[i+2];
-            int obj = statements[i+3];
-
-            ResourceHandle subject = handles[sub];
-            ResourceHandle predicate = handles[pred];
-            ResourceHandle object = handles[obj];
-
-            if(resources[sub] == null) {
-                subject.addStatement(graph, predicate, object); 
-            } else {
-                graph.claim(
-                        handles[sub].resource(ss),
-                        handles[pred].resource(ss),
-                        null, handles[obj].resource(ss));
-            }
-            
-            if(inv >= 0) {
-                
-                if(resources[obj] == null) {
-                    ResourceHandle inverse = handles[inv];
-                    object.addStatement(graph, inverse, subject);   
-                } else {
-                    graph.claim(
-                            handles[obj].resource(ss),
-                            handles[inv].resource(ss),
-                            null, handles[sub].resource(ss));
-                }
-                
-            }
-            
-            if(LOG) {
-                log("[STATEMENT] " + resources[statements[i]].getResourceId() + ", " + resources[statements[i+1]].getResourceId() + ", " + resources[statements[i+3]].getResourceId());
-            }
-            
-        }
-                
-        // Write values
-        TransferableGraphSupport tgSupport = 
-            graph.getService(TransferableGraphSupport.class);
-        VirtualGraph vg = graph.getProvider();
-        for(OldValue1 value : tg.values) {
-            int file = value.resource & 0x80000000;
-            int resource = value.resource & 0x7FFFFFFF;
-            if (file != 0) {
-                graph.claimValue(handles[resource].resource(ss), value.value, Bindings.BYTE_ARRAY);
-            } else {
-                if(resource < internals) {
-                    handles[resource].addValue(graph, value.value);
-                } else {
-                    tgSupport.setValue(graph, handles[resource].resource(ss), vg, value.value);
-                }
-                //tgSupport.setValue(resources[resource], vg, value.value);
-            }
-        }
-    }
-    
-    void write2(WriteOnlyGraph graph) throws DatabaseException {
-        Resource[] resources = this.resources;
-        
-        // Internal identities      
-        for(Identity identity : tg.identities) {
-            IdentityDefinition definition = identity.definition;
-            if(resources[identity.resource] != null)
-                continue;
-            if(definition instanceof External) {
-                // Already done everything
-            }
-            else if(definition instanceof Internal) {
-                Internal def = (Internal)definition;
-                resources[identity.resource] = 
-                    createChild(graph, resources[def.parent], def.name);
-            }
-            else if(definition instanceof Root) {               
-                Root root = (Root)definition;               
-                resources[identity.resource] = advisor.createRoot(graph, root);                 
-            }
-            else if(definition instanceof Optional) {
-                Optional def = (Optional)definition;
-                Resource child = createChild(graph, resources[def.parent], def.name);
-                graph.claim(child, InstanceOf, null, Library); // ???
-                resources[identity.resource] = child;                   
-            }
-        }       
-        
-        // Create blank resources
-        for(int i=0;i<resources.length;++i)
-            if(resources[i] == null)
-                resources[i] = graph.newResource();
-        
-        // Write statements
-        int[] statements = tg.statements;
-        
-        for(int i=0;i<statements.length;i+=4) {
-            int inv = statements[i+2];
-            graph.claim(
-                    resources[statements[i]],
-                    resources[statements[i+1]],
-                    inv < 0 ? null : resources[inv],
-                    resources[statements[i+3]]
-                    );
-            if(LOG) {
-                log("[STATEMENT] " + resources[statements[i]].getResourceId() + ", " + resources[statements[i+1]].getResourceId() + ", " + resources[statements[i+3]].getResourceId());
-            }
-        }
-                
-        // Write values
-        TransferableGraphSupport tgSupport = 
-            graph.getService(TransferableGraphSupport.class);
-        VirtualGraph vg = graph.getProvider();
-        for(OldValue1 value : tg.values) {
-            int file = value.resource & 0x80000000;
-            int resource = value.resource & 0x7FFFFFFF;
-            if (file != 0) {
-                graph.claimValue(resources[resource], value.value, Bindings.BYTE_ARRAY);
-            } else {
-                tgSupport.setValue(graph, resources[resource], vg, value.value);
-            }
-        }
-    }
-    
-    
-    public long[] getResourceIds(SerialisationSupport serializer) throws DatabaseException {
-        final int count = resources.length;
-        long[] resourceIds = new long[count];
-        if(handles != null) {
-            for(int i=0;i<count;++i)
-                resourceIds[i] = serializer.getRandomAccessId(handles[i].resource(serializer));
-        } else {
-            for(int i=0;i<count;++i)
-                resourceIds[i] = serializer.getRandomAccessId(resources[i]);
-        }
-        return resourceIds;
-    }
-    
-}
\ No newline at end of file
diff --git a/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldTransferableGraphs.java b/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldTransferableGraphs.java
deleted file mode 100644 (file)
index 4786abd..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 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
- *******************************************************************************/
-package org.simantics.graph.db.old;
-
-import java.util.function.BiFunction;
-
-import org.simantics.db.ReadGraph;
-import org.simantics.db.Session;
-import org.simantics.db.WriteGraph;
-import org.simantics.db.WriteOnlyGraph;
-import org.simantics.db.common.request.ReadRequest;
-import org.simantics.db.common.request.WriteOnlyRequest;
-import org.simantics.db.exception.DatabaseException;
-import org.simantics.graph.db.IImportAdvisor;
-import org.simantics.graph.db.ImportAdvisor;
-import org.simantics.graph.db.TransferableGraphException;
-import org.simantics.graph.representation.old.OldTransferableGraph1;
-
-public class OldTransferableGraphs {
-
-    public static void importGraph1(Session session, final OldTransferableGraph1 tg, IImportAdvisor advisor, final BiFunction<WriteOnlyGraph, OldTransferableGraphImportProcess1, Boolean> callback) throws DatabaseException, TransferableGraphException {
-        final OldTransferableGraphImportProcess1 process = new OldTransferableGraphImportProcess1(tg, 
-                advisor == null ? new ImportAdvisor() : advisor);
-        session.syncRequest(new ReadRequest() {
-            @Override
-            public void run(ReadGraph graph) throws DatabaseException {
-                process.prepare(graph);
-            }
-        });
-        session.syncRequest(new WriteOnlyRequest() {
-            @Override
-            public void perform(WriteOnlyGraph graph) throws DatabaseException {
-                process.write(graph);
-                if(callback != null)
-                    callback.apply(graph, process);
-            }
-        });
-    }
-    
-    public static void importGraph1(WriteGraph graph, final OldTransferableGraph1 tg, IImportAdvisor advisor) throws DatabaseException {
-        final OldTransferableGraphImportProcess1 process = new OldTransferableGraphImportProcess1(tg, 
-                advisor == null ? new ImportAdvisor() : advisor);
-        process.prepare(graph);
-        process.write2(graph);
-       
-    }
-    
-}
index 5f4404acc377654f15cb79c95be04028b3fc09a7..6ae6e86fe08dfbfbbf7a901827a061f43d989732 100644 (file)
@@ -12,9 +12,9 @@ Export-Package: org.simantics.graph,
  org.simantics.graph.query,
  org.simantics.graph.refactoring,
  org.simantics.graph.representation,
- org.simantics.graph.representation.old,
  org.simantics.graph.store,
  org.simantics.graph.tests.conversion,
  org.simantics.graph.utils
 Bundle-ClassPath: .
 Bundle-Vendor: VTT Technical Research Centre of Finland
+Import-Package: org.slf4j
index 850c47d8598c3bbdd46bc49ae5eb4f0356bdc10d..9c96f834dd61c6ca75292630b2481ab765b47129 100644 (file)
@@ -15,7 +15,6 @@ import org.simantics.graph.representation.Optional;
 import org.simantics.graph.representation.Root;
 import org.simantics.graph.representation.TransferableGraph1;
 import org.simantics.graph.representation.Value;
-import org.simantics.graph.representation.old.OldTransferableGraph1;
 import org.simantics.graph.store.GraphStore;
 import org.simantics.graph.store.IStore;
 import org.simantics.graph.store.IdentityStore;
@@ -44,10 +43,6 @@ public class TransferableGraphConversion {
            return extractIdentities(tg.resourceCount, tg.identities);
        }
        
-       public static IdentityStore extractIdentities(OldTransferableGraph1 tg) {
-        return extractIdentities(tg.resourceCount, tg.identities);
-    }
-       
        private static IdentityStore extractIdentities(int resourceCount, Identity[] ids) {
            IdentityStore identities = new IdentityStore();
         identities.setResourceCount(resourceCount);
index 9882048b788144c74de9ac5ec56b69f6954ff384..9f8eca398f139c10a5a18801522230427fa29f08 100644 (file)
@@ -1,6 +1,5 @@
 package org.simantics.graph.refactoring;
 
-import java.util.ArrayList;
 import java.util.Arrays;
 
 import org.simantics.databoard.util.URIStringUtils;
@@ -11,23 +10,19 @@ import org.simantics.graph.query.UriUtils;
 import org.simantics.graph.refactoring.MappingSpecification.MappingRule;
 import org.simantics.graph.representation.External;
 import org.simantics.graph.representation.Identity;
-import org.simantics.graph.representation.IdentityDefinition;
 import org.simantics.graph.representation.Internal;
-import org.simantics.graph.representation.Optional;
 import org.simantics.graph.representation.Root;
 import org.simantics.graph.representation.TransferableGraph1;
 import org.simantics.graph.representation.TransferableGraphUtils;
-import org.simantics.graph.representation.old.OldTransferableGraph1;
-import org.simantics.graph.representation.old.OldValue1;
 import org.simantics.graph.store.GraphStore;
 import org.simantics.graph.store.IdentityStore;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-import gnu.trove.list.array.TIntArrayList;
-import gnu.trove.map.hash.TIntIntHashMap;
 import gnu.trove.set.hash.TIntHashSet;
 
 public class GraphRefactoringUtils {
-
+    private static final Logger LOGGER = LoggerFactory.getLogger(GraphRefactoringUtils.class);
     /**
      * Moves an external resource. Returns true if did something.
      * @param parentsAffected 
@@ -48,7 +43,7 @@ public class GraphRefactoringUtils {
         // Find parent id
         int toParentId = ids.createPathToId(to.parent);
         if(ids.hasChild(toParentId, to.name)) {
-               System.err.println("refactor statements from " + from + " to " + to);
+            LOGGER.info("refactor statements from " + from + " to " + to);
             //throw new GraphRefactoringException("External reference to " + to + " already exists.");
                int toId = ids.pathToId(to);
             int[] statements = tg.statements;
@@ -68,7 +63,7 @@ public class GraphRefactoringUtils {
             if(!(rule.to instanceof PathChild))
                 throw new GraphRefactoringException("Invalid target URI " + rule.to);
             if(!moveExternal(tg, ids, rule.from, (PathChild)rule.to, parentsAffected))
-                System.err.println("Didn't find " + rule.from);
+                LOGGER.warn("Didn't find " + rule.from);
         }
     }
 
@@ -159,69 +154,4 @@ public class GraphRefactoringUtils {
         }
     }
 
-    public static void compactify(OldTransferableGraph1 tg,
-            TIntHashSet removed) {
-        // Filter removed set
-        for(Identity id : tg.identities) {
-            IdentityDefinition def = id.definition;
-            if(def instanceof Root)
-                removed.remove(id.resource);
-            else if(def instanceof External)
-                removed.remove(((External)def).parent);
-            else if(def instanceof Internal)
-                removed.remove(((Internal)def).parent);
-            else if(def instanceof Optional)
-                removed.remove(((Optional)def).parent);
-        }
-        for(int r : tg.statements)
-            removed.remove(r);
-        for(OldValue1 value : tg.values)
-            removed.remove(value.resource);
-        
-        // Compactify
-        if(!removed.isEmpty()) {
-            // create map
-            int resourceCount = tg.resourceCount;
-            int[] map = new int[resourceCount];
-            for(int i=0;i<resourceCount;++i)
-                map[i] = i;
-            for(int r : removed.toArray()) {
-                map[--resourceCount] = map[r];
-            }
-            
-            // map
-            ArrayList<Identity> newIdentities = new ArrayList<Identity>(tg.identities.length);
-            for(Identity id : tg.identities) {
-                if(removed.contains(id.resource))
-                    continue;
-                else
-                    newIdentities.add(id);                
-                id.resource = map[id.resource];
-                IdentityDefinition def = id.definition;
-                if(def instanceof External) {
-                    External d = (External)def;
-                    d.parent = map[d.parent];
-                }
-                else if(def instanceof Internal) {
-                    External d = (External)def;
-                    d.parent = map[d.parent];
-                }
-                else if(def instanceof Optional) {
-                    External d = (External)def;
-                    d.parent = map[d.parent];
-                }
-            }
-            tg.identities = newIdentities.toArray(new Identity[newIdentities.size()]);
-            int[] statements = tg.statements;
-            for(int i=0;i<statements.length;++i) {
-                int r = statements[i];                        
-                if(r >= 0)
-                    statements[i] = map[r];
-            }
-            for(OldValue1 value : tg.values)
-                value.resource = map[value.resource];
-            tg.resourceCount = resourceCount;
-        }
-    }
-
 }
diff --git a/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/PrintReferencesTool.java b/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/PrintReferencesTool.java
deleted file mode 100644 (file)
index d980692..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.simantics.graph.refactoring;
-
-import gnu.trove.map.hash.THashMap;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-
-import org.simantics.databoard.Files;
-import org.simantics.graph.query.TransferableGraphConversion;
-import org.simantics.graph.representation.old.OldTransferableGraph1;
-import org.simantics.graph.store.IdentityStore;
-import org.simantics.graph.store.IdentityStore.ConsistsOf;
-
-public class PrintReferencesTool {
-
-    public static void main(String[] args) throws Exception {
-        print(new File(args[0]));
-    }
-    
-    public static void print(File input) throws IOException {
-        OldTransferableGraph1 tg = (OldTransferableGraph1)
-                Files.readFile(input, OldTransferableGraph1.BINDING);
-        GraphRefactoringUtils.fixIncorrectRoot(tg.identities);
-        IdentityStore idStore = TransferableGraphConversion.extractIdentities(tg);
-        printExternals(idStore, idStore.getRoot(""), 0);
-    }
-
-    private static void printExternals(IdentityStore idStore, int cur, int indentation) {
-        THashMap<String, ConsistsOf> map = idStore.getChildMap(cur);
-        if(map == null)
-            return;
-        ArrayList<String> names = new ArrayList<String>(map.keySet());
-        Collections.sort(names);
-        for(String name : names) {
-            ConsistsOf co = map.get(name);
-            if(!idStore.isNewResource(co.child)) {
-                for(int i=0;i<indentation;++i)
-                    System.out.print("    ");
-                System.out.println(name);
-                printExternals(idStore, co.child, indentation+1);
-            }
-        }
-    }
-    
-}
diff --git a/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/RefactoringTool.java b/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/RefactoringTool.java
deleted file mode 100644 (file)
index c172e98..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.simantics.graph.refactoring;
-
-import gnu.trove.set.hash.TIntHashSet;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.ArrayList;
-
-import org.simantics.databoard.Files;
-import org.simantics.graph.query.Path;
-import org.simantics.graph.query.TransferableGraphConversion;
-import org.simantics.graph.query.UriUtils;
-import org.simantics.graph.refactoring.MappingSpecification.MappingRule;
-import org.simantics.graph.representation.old.OldTransferableGraph1;
-import org.simantics.graph.store.IdentityStore;
-
-
-public class RefactoringTool {
-
-    public static void main(String[] args) throws Exception {
-        if(args.length != 3)
-            System.out.println("Usage: java " + RefactoringTool.class.getCanonicalName() + " mappingSpec input.tg ouput.tg");
-        refactor(new File(args[0]), new File(args[1]), new File(args[2]));
-    }
-
-    public static void refactor(File mappingSpec, File input, File output) throws IOException, GraphRefactoringException  {
-        if(!mappingSpec.exists()) {
-            System.out.println("Mapping specification " + mappingSpec + " does not exist.");
-            return;
-        }
-        if(!input.exists()) {
-            System.out.println("Input tg " + input + " does not exist.");
-            return;
-        }
-         
-        MappingSpecification spec = readMappingSpec(mappingSpec);
-        
-        // Refactor old format
-        OldTransferableGraph1 tg = (OldTransferableGraph1)
-                Files.readFile(input, OldTransferableGraph1.BINDING);
-        boolean fixed = GraphRefactoringUtils.fixIncorrectRoot(tg.identities);
-        IdentityStore idStore = TransferableGraphConversion.extractIdentities(tg);
-        TIntHashSet parentsAffected = new TIntHashSet(); 
-        GraphRefactoringUtils.refactor(null, idStore, spec, parentsAffected);
-        tg.resourceCount = idStore.getResourceCount();
-        tg.identities = idStore.toArray();
-        GraphRefactoringUtils.compactify(tg, parentsAffected);
-        if(fixed)
-            GraphRefactoringUtils.unfixIncorrectRoot(tg.identities);
-        
-        // Write to output file
-        Files.writeFile(output, OldTransferableGraph1.BINDING, tg);
-    }
-
-    private static MappingSpecification readMappingSpec(File mappingSpec) throws IOException {
-        BufferedReader reader = new BufferedReader(new FileReader(mappingSpec));
-        ArrayList<MappingRule> rules = new ArrayList<MappingRule>();
-        while(true) {
-            String line = reader.readLine();
-            if(line == null)
-                break;
-            line = line.trim();
-            if(line.isEmpty())
-                continue;
-            String[] parts = line.trim().split(" ");
-            if(parts.length != 2)
-                throw new IOException("Invalid mapping spec format. Every non-empty line should contain two URIs.");
-            
-            Path from = UriUtils.uriToPath(parts[0]);
-            Path to = UriUtils.uriToPath(parts[1]);
-            
-            rules.add(new MappingRule(from, to));
-        }
-        reader.close();
-        
-        return new MappingSpecification(rules);
-    }
-           
-}
index 5968b6822e35a122fac68158119151783247c4d8..3243b82bd1c3aeb6be8e424ac7b907845ddaa240 100644 (file)
@@ -7,10 +7,16 @@ import java.io.InputStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 import java.util.TreeMap;
 
 import org.simantics.databoard.binding.Binding;
+import org.simantics.databoard.binding.mutable.Variant;
 import org.simantics.databoard.container.DataContainers;
+import org.simantics.databoard.type.Datatype;
 
 import gnu.trove.list.array.TIntArrayList;
 import gnu.trove.map.hash.TIntObjectHashMap;
@@ -24,7 +30,7 @@ public class PrettyPrintTG extends TransferableGraphUtils {
 
        int blankCounter = 0;
        
-       StringBuilder output = new StringBuilder();
+       final StringBuilder output;
        
        static class ResourceInfo {
                final boolean hasURI;
@@ -33,6 +39,7 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                boolean newResource = false;
                int owner = 0;
                int ownerPredicate = 0;
+               String aliasURI = null;
                TIntArrayList owned = new TIntArrayList();
                TIntArrayList statements = new TIntArrayList();
                public ResourceInfo(boolean hasURI, String name, int resource) {
@@ -42,10 +49,23 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                }
        }
        
+       public PrettyPrintTG(StringBuilder b) {
+               output = b;
+       }
+       
+       public PrettyPrintTG() {
+               this(new StringBuilder());
+       }
+
        TIntObjectHashMap<ResourceInfo> infos = new TIntObjectHashMap<>();
        
+       String tgNodeName(String name) {
+               if(name.contains(" ")) return "\"" + name + "\"";
+               else return name;
+       }
+       
        ResourceInfo recurseURI(TransferableGraph1 graph, Identity parent, String parentName) {
-               String name = parentName + ".\"" + getName(parent) + "\"";
+               String name = parentName + "." + tgNodeName(getName(parent));
                ResourceInfo info = new ResourceInfo(true, name, parent.resource); 
                infos.put(parent.resource, info);
                for(Identity child : getChildren(graph, parent)) {
@@ -62,6 +82,12 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                        if(objectId != null) {
                                if(objectId.definition instanceof External) continue;
                        }
+                       Value value = TransferableGraphUtils.findValue(graph, object);
+                       if(value != null) {
+                               infos.put(object, new ResourceInfo(false, printValue(value), object));
+                               continue;
+                       }
+                       
                        ResourceInfo existing = infos.get(object);
                        if(existing == null) {
                                existing = new ResourceInfo(false, "blank" + blankCounter++, object);
@@ -91,6 +117,12 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                info.statements = statements;
        }
        
+       String printValue(Value value) {
+               Variant variant = value.value;
+               Datatype dt = variant.getBinding().type();
+               return "\"" + variant.getValue() + "\"";
+       }
+       
        void fixInstanceOf(TransferableGraph1 graph, ResourceInfo info) {
                Identity id = getIdentity(graph, info.resource);
                if(id == null) return;
@@ -106,8 +138,8 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                String name = ext.name;
                if(name.contains(" ")) name = name.replace(" ", "_").replaceAll("@", "_");//name = "\"" + name + "\"";
                int parentId = ext.parent;
-               if(parentId == 0) return ext.name;
-               else {
+               //if(parentId == 0) return ext.name;
+//             else {
                        Identity id = getIdentity(tg, parentId);
                        if(id.definition instanceof External) {
                                return getExternalURI(tg, (External)id.definition) + "/" + name;
@@ -117,7 +149,7 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                        } else {
                                return null;
                        }
-               }
+//             }
        }
 
        public static String getExternalURI(TransferableGraph1 tg, int resource) {
@@ -143,6 +175,7 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                uri = uri.replace("http://www.simantics.org/G2D-1.1", "G2D");
                uri = uri.replace("http://www.simantics.org/Image2-1.2", "IMAGE2");
                uri = uri.replace("http://www.simantics.org/SelectionView-1.2", "SEL");
+               uri = uri.replace("http://www.simantics.org/Viewpoint-1.2", "VP");
                uri = uri.replace("http://www.simantics.org/GraphFile-0.1", "GRAPHFILE");
                uri = uri.replace("http://www.semantum.fi/Simupedia-1.0", "SIMUPEDIA");
                uri = uri.replace("http://www.semantum.fi/SimupediaWorkbench-1.0", "SIMUPEDIA_WB");
@@ -177,16 +210,22 @@ public class PrettyPrintTG extends TransferableGraphUtils {
        long longStm(int predicate, int object) {
         return (predicate<<32) | (object & 0xffffffffL); 
        }
+
+       void addStatement(Map<String,List<String>> statements, String predicate, String object) {
+               List<String> objects = statements.get(predicate);
+               if(objects == null) {
+                       objects = new ArrayList<String>();
+                       statements.put(predicate, objects);
+               }
+               objects.add(object);
+       }
        
        void printURI(TransferableGraph1 graph, ResourceInfo info) {
+               
                if(!info.hasURI) return;
-               if("ROOT".equals(info.name)) {
-                       output.append("ROOT=<http:/>\n");
-               } else {
-                       output.append(info.name + "\n");
-               }
-               if(info.newResource)
-                       output.append("  @L0.new\n");
+               
+               Map<String,List<String>> statements = new HashMap<>();
+               Identity consistsOf = findExternal(graph, "http://www.simantics.org/Layer0-1.1/ConsistsOf");
                TLongHashSet processed = new TLongHashSet();
                for(int i=0;i<info.owned.size();i+=2) {
                        String predicateURI = rewritePredicateURI(graph, info.owned.get(i));
@@ -199,7 +238,6 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                        processed.add(stmId);
                        printBlank(graph, predicateURI, ownedInfo);
                }
-               Identity consistsOf = findExternal(graph, "http://www.simantics.org/Layer0-1.1/ConsistsOf");
                for(int i=0;i<info.statements.size();i+=2) {
                        long stmId = longStm(info.statements.get(i), info.statements.get(i+1));
                        if(processed.contains(stmId)) continue;
@@ -208,29 +246,109 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                        ResourceInfo objectInfo = infos.get(info.statements.get(i+1));
                        if(objectInfo == null) {
                                String objectURI = rewritePredicateURI(graph, info.statements.get(i+1));
-                               output.append("  " + predicateURI + " " + objectURI + "\n");
+                               //output.append("  " + predicateURI + " " + objectURI + "\n");
+                               addStatement(statements, predicateURI, objectURI);
                        } else {
-                               output.append("  " + predicateURI + " " + objectInfo.name + "\n");
+                               //output.append("  " + predicateURI + " " + objectInfo.name + "\n");
+                               addStatement(statements, predicateURI, objectInfo.name);
+                       }
+               }
+               
+               if("ROOT".equals(info.name)) {
+                       output.append("ROOT=<http:/>");
+               } else if (info.aliasURI != null) {
+                       output.append(info.name + " = <" + info.aliasURI + ">");
+               } else {
+                       output.append(info.name);
+               }
+               
+               List<String> instanceOfs = statements.get("L0.InstanceOf");
+               if(instanceOfs != null) {
+                       for(String instanceOf : instanceOfs) {
+                               output.append(" : " + instanceOf);              
                        }
                }
+
+               List<String> subrelationOfs = statements.get("L0.SubrelationOf");
+               if(subrelationOfs != null) {
+                       for(String subrelationOf : subrelationOfs) {
+                               output.append(" <R " + subrelationOf);          
+                       }
+               }
+               
+               List<String> inherits = statements.get("L0.Inherits");
+               if(inherits != null) {
+                       for(String inherit : inherits) {
+                               output.append(" <T " + inherit);                
+                       }
+               }
+
+               output.append("\n");
+               
+               if(info.newResource)
+                       output.append("  @L0.new\n");
+               
+               for(Map.Entry<String, List<String>> entry : statements.entrySet()) {
+                       String predicate = entry.getKey();
+                       if("L0.InstanceOf".equals(predicate)) continue;
+                       if("L0.SubrelationOf".equals(predicate)) continue;
+                       if("L0.Inherits".equals(predicate)) continue;
+                       List<String> objects = entry.getValue();
+                       if(objects.size() == 1) {
+                               output.append("  " + predicate + " " + objects.iterator().next() + "\n");       
+                       } else{
+                               output.append("  " + predicate + "\n"); 
+                               for(String object : objects) {
+                                       output.append("    " + object + "\n");  
+                               }
+                       }
+               }
+               
        }
 
        void prettyPrint(Path input, Path output) throws Exception {
+
                System.out.format("Converting exported shared ontology%n\t" + input.toString() + "%nto bundle-compatible ontology%n\t" + output.toString());
                try (InputStream is = new BufferedInputStream(Files.newInputStream(input), 128*1024)) {
+                       
                        DataInput dis = new DataInputStream(is);
                        org.simantics.databoard.container.DataContainer container = 
                                        DataContainers.readFile(dis); 
                        Binding binding = TransferableGraph1.BINDING;
                        TransferableGraph1 graph = (TransferableGraph1)container.content.getValue(binding);
+                       prettyPrint(graph);
+                       Files.write(output, this.output.toString().getBytes());
+                       
+               }
+
+       }
+
+       void prettyPrint(TransferableGraph1 graph) {
+       
                        // Discover resources with URI
-                       for(Identity id : TransferableGraphUtils.getRoots(graph)) {
-                               String name = "ROOT";
-                               ResourceInfo info = new ResourceInfo(true, name, id.resource); 
-                               infos.put(id.resource, info);
-                               for(Identity child : getChildren(graph, id)) {
-                                       ResourceInfo childInfo = recurseURI(graph, child, name);
-                                       childInfo.newResource = true;
+//                     for(Identity id : TransferableGraphUtils.getRoots(graph)) {
+//                             String name = "ROOT";
+//                             ResourceInfo info = new ResourceInfo(true, name, id.resource); 
+//                             infos.put(id.resource, info);
+//                             for(Identity child : getChildren(graph, id)) {
+//                                     ResourceInfo childInfo = recurseURI(graph, child, name);
+//                                     childInfo.newResource = true;
+//                             }
+//                     }
+                       for(Identity id : graph.identities) {
+                               if(id.definition instanceof Internal) {
+                                       Internal internal = (Internal)id.definition;
+                                       Identity parent = TransferableGraphUtils.getIdentity(graph, internal.parent);
+                                       if(parent.definition instanceof External) {
+                                               String name = "BASE";
+                                               ResourceInfo info = new ResourceInfo(true, name, id.resource);
+                                               info.aliasURI = TransferableGraphUtils.getURI(graph, id.resource);
+                                               info.newResource = true;
+                                               infos.put(id.resource, info);
+                                               for(Identity child : getChildren(graph, id)) {
+                                                       recurseURI(graph, child, name);
+                                               }
+                                       }
                                }
                        }
                        // Discover other resources
@@ -269,6 +387,7 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                        this.output.append("DOC = <http://www.simantics.org/Document-1.2>\n");
                        this.output.append("G2D = <http://www.simantics.org/G2D-1.1>\n");
                        this.output.append("SEL = <http://www.simantics.org/SelectionView-1.2>\n");
+                       this.output.append("VP =  <http://www.simantics.org.Viewpoint-1.2>\n");
                        this.output.append("IMAGE2 = <http://www.simantics.org/Image2-1.2>\n");
                        this.output.append("GRAPHFILE = <http://www.simantics.org/GraphFile-0.1>\n");
                        this.output.append("APROS_OPER = <http://www.apros.fi/OperationUI-6.6>\n");
@@ -276,15 +395,15 @@ public class PrettyPrintTG extends TransferableGraphUtils {
                        this.output.append("SIMUPEDIA_WB = <http://www.semantum.fi/SimupediaWorkbench-1.0>\n");
                        this.output.append("SIMUPEDIA_STD = <http://semantum.fi/SimupediaStandardLibrary@1.3-trunk>\n");
                        
-//                     uri = uri.replace("http://semantum.fi/SimupediaStandardLibrary@1.3-trunk/", "SIMUPEDIA_STD.");
-
-                       
                        for(ResourceInfo info : order.values())
                                printURI(graph, info);
                        
-                       Files.write(output, this.output.toString().getBytes());
-                               
-               }
+       }
+       
+       public static String print(TransferableGraph1 tg) {
+               StringBuilder b = new StringBuilder();
+               new PrettyPrintTG(b).prettyPrint(tg);
+               return b.toString();
        }
 
        public static void main(String[] args) throws Exception {
diff --git a/bundles/org.simantics.graph/src/org/simantics/graph/representation/old/OldTransferableGraph1.java b/bundles/org.simantics.graph/src/org/simantics/graph/representation/old/OldTransferableGraph1.java
deleted file mode 100644 (file)
index b68bea3..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 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
- *******************************************************************************/
-package org.simantics.graph.representation.old;
-
-import java.util.TreeMap;
-
-import org.simantics.databoard.Bindings;
-import org.simantics.databoard.binding.Binding;
-import org.simantics.databoard.binding.mutable.Variant;
-import org.simantics.databoard.serialization.Serializer;
-import org.simantics.graph.representation.External;
-import org.simantics.graph.representation.Identity;
-import org.simantics.graph.representation.Internal;
-import org.simantics.graph.representation.Root;
-import org.simantics.graph.tests.conversion.TransferableGraph0;
-
-
-/**
- * Transferable graph datatype. 
- * See <a href="https://www.simantics.org/wiki/index.php/Graph_exchange_format">specification</a>. 
- * @author Hannu Niemist�
- * 
- * @deprecated superceded by {@link TransferableGraph0}
- */
-@Deprecated
-public class OldTransferableGraph1 {
-       public static Binding BINDING = Bindings.getBindingUnchecked(OldTransferableGraph1.class);
-       public static Serializer SERIALIZER = Bindings.getSerializerUnchecked(BINDING);
-       
-       public int resourceCount;
-       public Identity[] identities;   
-       public int[] statements;
-       public OldValue1[] values;
-       public TreeMap<String, Variant> extensions;
-       
-       public OldTransferableGraph1() {}
-       
-       public OldTransferableGraph1(int resourceCount, Identity[] identities,
-                       int[] statements, OldValue1[] values) {
-               this(resourceCount, identities, statements, values,
-                               new TreeMap<String, Variant>());
-       }
-       
-       public OldTransferableGraph1(int resourceCount, Identity[] identities,
-                       int[] statements, OldValue1[] values, TreeMap<String, Variant> extensions) {
-               this.resourceCount = resourceCount;
-               this.identities = identities;
-               this.statements = statements;
-               this.values = values;
-               this.extensions = extensions;
-       }
-
-       public void print() {
-               System.out.println("Identities");
-               for(Identity id : identities) {
-                       System.out.print("    " + id.resource + " = ");
-                       if(id.definition instanceof Root) {
-                               Root def = (Root)id.definition;
-                               System.out.println("ROOT(" + def.name + ")");
-                       }
-                       else if(id.definition instanceof External) {
-                               External def = (External)id.definition;
-                               System.out.println("EXTERNAL(" + def.parent + ", " + def.name + ")");
-                       }
-                       else if(id.definition instanceof Internal) {
-                               Internal def = (Internal)id.definition;
-                               System.out.println("INTERNAL(" + def.parent + ", " + def.name + ")");
-                       }
-               }
-               System.out.println("Statements:");
-               for(int i=0;i<statements.length;i+=4)
-                       System.out.println("    " + 
-                                       statements[i] + " " +
-                                       statements[i+1] + " " +
-                                       statements[i+2] + " " +
-                                       statements[i+3]
-                                       );
-       }
-}
diff --git a/bundles/org.simantics.graph/src/org/simantics/graph/representation/old/OldValue1.java b/bundles/org.simantics.graph/src/org/simantics/graph/representation/old/OldValue1.java
deleted file mode 100644 (file)
index 0994b07..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 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
- *******************************************************************************/
-package org.simantics.graph.representation.old;
-
-
-/**
- * A part of TransferableGraph data structure.
- * Says that the resource has a literal with given value.
- * @author Hannu Niemist�
- */
-public class OldValue1 {
-       public int resource;
-       public byte[] value;
-       
-       public OldValue1() {
-       }
-       
-       public OldValue1(int resource, byte[] value) {
-               this.resource = resource;
-               this.value = value;
-       }       
-}
diff --git a/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/TestRefactoring.java b/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/TestRefactoring.java
deleted file mode 100644 (file)
index f7c7cb1..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-package org.simantics.graph.tests.refactoring;
-
-import java.io.File;
-import java.net.URLDecoder;
-
-import org.simantics.graph.refactoring.PrintReferencesTool;
-import org.simantics.graph.refactoring.RefactoringTool;
-
-public class TestRefactoring {
-
-    public static void main(String[] args) throws Exception {
-        File dir = new File(URLDecoder.decode(TestRefactoring.class.getResource(".").getPath(), "UTF-8")).getAbsoluteFile();// new File(TestRefactoring.class.getResource(".").getFile());
-        System.out.println(dir);
-        File input = new File(dir, "xor5.aprosSymbol");
-        File mappingSpec = new File(dir, "mappingSpec.txt");
-        File output = new File(dir, "xor5_refactored.aprosSymbol");
-        
-        System.out.println("-- Before refactoring");
-        System.out.println("------------------------------------------");
-        PrintReferencesTool.print(input);
-        
-        RefactoringTool.refactor(mappingSpec, input, output);
-        
-        System.out.println("-- After refactoring");
-        System.out.println("------------------------------------------");
-        PrintReferencesTool.print(output);
-    }
-    
-}
diff --git a/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/TestRefactoring2.java b/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/TestRefactoring2.java
deleted file mode 100644 (file)
index c122cff..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.simantics.graph.tests.refactoring;
-
-import java.io.File;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.simantics.graph.refactoring.RefactoringTool;
-
-public class TestRefactoring2 {
-
-    public static void main(String[] args) throws Exception {
-        File dir = new File(URLDecoder.decode(TestRefactoring2.class.getResource(".").getPath(), "UTF-8")).getAbsoluteFile();// new File(TestRefactoring.class.getResource(".").getFile());
-        System.out.println(dir);
-        File allFiles[] = dir.listFiles();
-        List<File> inputFiles = new ArrayList<File>();
-        List<File> outputFiles = new ArrayList<File>();
-        String ext = ".aprosSymbol";
-        File outDir = new File(dir,"out");
-        if (!outDir.exists())
-               outDir.mkdir();
-        for (File f: allFiles) {
-               if (!f.isFile())
-                       continue;
-               if (!f.getName().endsWith(ext))
-                       continue;
-               inputFiles.add(f);
-               String outputName = f.getName();
-               outputFiles.add(new File(outDir,outputName));
-        }
-        
-        File mappingSpec = new File(dir, "mappingSpec.txt");
-        for (int i = 0; i < inputFiles.size() ; i++) {
-               
-               File input = inputFiles.get(i);
-               File output = outputFiles.get(i);
-               
-               System.out.println(input + " -> " + output);   
-               
-               RefactoringTool.refactor(mappingSpec, input, output);
-        }
-    }
-    
-}
diff --git a/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/mappingSpec.txt b/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/mappingSpec.txt
deleted file mode 100644 (file)
index d85d332..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-http://www.apros.fi/AprosStatic-6.0 http://www.apros.fi/Combustion/Configuration-6.0
-http://www.apros.fi/AprosDiagram-6.0/Terminals http://www.apros.fi/Apros-6.1/Terminals
-http://www.apros.fi/AprosDiagram-6.0/Relations http://www.apros.fi/Combustion/Diagram-6.0/Relations
-http://www.apros.fi/AprosDiagram-6.0/Symbols http://www.apros.fi/Combustion/Diagram-6.0/Symbols
-http://www.apros.fi/AprosDiagram-6.0/AnalogSignalOutputRelation http://www.apros.fi/Combustion/Diagram-6.0/AnalogSignalOutputRelation
-http://www.apros.fi/AprosDiagram-6.0/BinarySignalOutputRelation http://www.apros.fi/Combustion/Diagram-6.0/BinarySignalOutputRelation
\ No newline at end of file
diff --git a/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/xor5.aprosSymbol b/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/xor5.aprosSymbol
deleted file mode 100644 (file)
index d005eb2..0000000
Binary files a/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/xor5.aprosSymbol and /dev/null differ
index 525c8da5244abc27f19951b450c52d5136266dc0..a426ba5c9b0c0bbc61df9c9419238d68712df11f 100644 (file)
@@ -35,7 +35,6 @@ Require-Bundle: org.simantics.project;bundle-version="1.0.0",
  org.bouncycastle.bcprov-jdk14;bundle-version="1.38.0",
  org.simantics.image2.ontology;bundle-version="1.1.0",
  org.simantics.scl.compiler;bundle-version="0.4.0",
- org.simantics.scl.compiler.dummy;bundle-version="1.0.0",
  org.simantics.scl.osgi;bundle-version="1.0.4",
  org.eclipse.jface.text;bundle-version="3.7.1",
  org.simantics.graphviz,
index cd4e9755dfa1e9a81d343c19189e235a8bf9e2d7..a662f57f4a47695501052d30dba1072e5d6ad66f 100644 (file)
@@ -1,6 +1,6 @@
 import "Simantics/Variables"
 import "Map" as Map
-import "Simantics/Testing/BuiltinKeys"
+include "Simantics/Testing/BuiltinKeys" as BuiltinKeys
 
 importJava "org.simantics.browsing.ui.model.browsecontexts.BrowseContext" where
     """
@@ -68,7 +68,7 @@ importJava "org.simantics.browsing.ui.NodeContext" where
     """
     Finds value with the specified key or <code>null</code> if there was no value for the key
     """
-    getConstant :: NodeContext -> ConstantKey -> <Proc> a
+    getConstant :: NodeContext -> BuiltinKeys.ConstantKey -> <Proc> a
 
 importJava "org.eclipse.jface.resource.ImageDescriptor" where
     data ImageDescriptor
index 69449fd8f0f7c2bdf86acee536af1f86d630240d..ad247b6bd8cf70e0bf8dd993ed2b96ff9ea0ae4a 100644 (file)
@@ -20,12 +20,18 @@ import org.simantics.databoard.Bindings;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
 import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.PossibleIndexRoot;
 import org.simantics.db.common.request.ReadRequest;
 import org.simantics.db.common.request.UniqueRead;
 import org.simantics.db.common.request.WriteRequest;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.graph.refactoring.GraphRefactoringUtils;
+import org.simantics.graph.representation.PrettyPrintTG;
+import org.simantics.graph.representation.TransferableGraph1;
 import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingUtils;
+import org.simantics.modeling.ui.sharedontology.wizard.Constants;
 import org.simantics.scl.compiler.errors.CompilationError;
 import org.simantics.scl.compiler.errors.Locations;
 import org.simantics.ui.workbench.ResourceEditorInput;
@@ -48,9 +54,21 @@ public class PGraphEditorDocumentProvider extends AbstractDocumentProvider {
                 @Override
                 public Document perform(ReadGraph graph) throws DatabaseException {
                     Layer0 L0 = Layer0.getInstance(graph);
-                    currentText = graph.getRelatedValue(resource, L0.PGraph_definition, Bindings.STRING);
-                    errorHappened = false;
-                    return new Document(currentText != null ? currentText : "");
+                    if(graph.isInstanceOf(resource, L0.PGraph)) {
+                        currentText = graph.getRelatedValue(resource, L0.PGraph_definition, Bindings.STRING);
+                        errorHappened = false;
+                        return new Document(currentText != null ? currentText : "");
+                    } else {
+                       Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(resource));
+                       if(indexRoot != null && graph.isInstanceOf(indexRoot, L0.Ontology)) {
+                               TransferableGraph1 tg = ModelingUtils.exportSharedOntology(graph, indexRoot, null, Constants.SHARED_LIBRARY_FORMAT, Constants.SHARED_LIBRARY_CURRENT_VERSION);
+                                       GraphRefactoringUtils.fixOntologyExport(tg);
+                            currentText = PrettyPrintTG.print(tg);
+                            errorHappened = false;
+                            return new Document(currentText != null ? currentText : "");
+                       }
+                       throw new DatabaseException("Could not get PGraph from " + resource);
+                    }
                 }
             });
         } catch (DatabaseException e) {
index 1adcf25c23d33a2b2f7ede11eaf9210697097fb6..bec1e5408ae414c82c568b102cff6743cefec5ac 100644 (file)
@@ -64,6 +64,7 @@ public class PDFPainter {
         ICanvasSceneGraphProvider[] sgProvider = { null };
 
         CanvasContext ctx = new CanvasContext(thread);
+        ctx.getDefaultHintContext().setHint(Hints.KEY_DISABLE_GRAPH_MODIFICATIONS, Boolean.TRUE);
 
         try {
             final Semaphore done = new Semaphore(0);
index 00d6980cfb07165a33e9694eb1dfb1e6d36ade53..85d42e103d1599d4a590ad26810bce6131a1f404 100644 (file)
@@ -32,4 +32,5 @@ include "Simantics/UI"
 include "Simantics/SelectionView"
 include "Simantics/Formatting"
 include "Simantics/Action"
-include "Simantics/Testing/BrowseContext"
\ No newline at end of file
+include "Simantics/Testing/BrowseContext"
+include "Debug" as Debug
\ No newline at end of file
index e3c7977155964bea6611bafe067df0d05f277211..c00c564e839fb8d662134c0821e78baaa0f51689 100644 (file)
@@ -140,7 +140,7 @@ loop4 testScan testList found = do
 
 importJava "java.lang.System" where
     @JavaName "getProperty"
-    getSystemProperty :: String -> String
+    getSystemProperty :: String -> Maybe String
     
 importJava "org.simantics.modeling.LifeCycleContext" where
     data LifeCycleContext
index 9b620c2f7c55e39e0d789b6d926759b8939d475a..10e23c65bbd72340277652d8c9618ab4f7032147 100644 (file)
@@ -89,21 +89,10 @@ public class CompilePGraphs {
         final Collection<ISource> sources = new ArrayList<>();
         Collection<TransferableGraph1> dependencies = new ArrayList<>();
 
-        for (Bundle b : Activator.getContext().getBundles()) {
-            URL tg = b.getEntry("/graph.tg");
-            if (tg == null) continue;
-            File f = url2file(FileLocator.resolve(tg), b.getSymbolicName());
-            try {
-                dependencies.add(GraphCompiler.read(f));
-            } catch (Exception e) {
-                throw new IOException("Failed to read compiled transferable graph as dependency: " + f, e);
-            }
-        }
-
-        final TransferableGraph1 thisOntology = Simantics.sync(new UniqueRead<TransferableGraph1>() {
+        final Pair<String, TransferableGraph1> thisOntology = Simantics.sync(new UniqueRead<Pair<String, TransferableGraph1>>() {
 
             @Override
-            public TransferableGraph1 perform(ReadGraph graph) throws DatabaseException {
+            public Pair<String, TransferableGraph1> perform(ReadGraph graph) throws DatabaseException {
                 Layer0 L0 = Layer0.getInstance(graph);
                 Resource parent = graph.getSingleObject(r, L0.PartOf);
 
@@ -130,12 +119,13 @@ public class CompilePGraphs {
                     }
                 };
 
+                String uri = graph.getURI(r);
                 SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();
                 ch.copyToClipboard(graph, clipboard);
                 for (Set<Representation> object : clipboard.getContents()) {
                     TransferableGraph1 tg = ClipboardUtils.accept(graph, object, SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
                     if (tg != null)
-                        return tg;
+                        return Pair.make(uri, tg);
                 }
 
                 return null;
@@ -145,7 +135,24 @@ public class CompilePGraphs {
         if (thisOntology == null)      
             throw new DatabaseException("Failed to dump the containing ontology of " + r + " into TransferableGraph1");
 
-        dependencies.add(thisOntology);
+        dependencies.add(thisOntology.second);
+        
+        for (Bundle b : Activator.getContext().getBundles()) {
+                       String id = b.getSymbolicName();
+                       String name = (String) b.getHeaders().get("Bundle-Name");
+                       if (name == null) name = id;
+                       if (name.equals(thisOntology.first))
+                               continue;
+            URL tg = b.getEntry("/graph.tg");
+            if (tg == null) continue;
+            File f = url2file(FileLocator.resolve(tg), b.getSymbolicName());
+            try {
+                dependencies.add(GraphCompiler.read(f));
+            } catch (Exception e) {
+                throw new IOException("Failed to read compiled transferable graph as dependency: " + f, e);
+            }
+        }
+
 
         Simantics.sync(new ReadRequest() {
             @Override
index 3b4806c7ce927a78b46bdc60f8931b3bb6db535d..8a5b92228a74f52dd5e4bf41665bf09a0567c88b 100644 (file)
@@ -1470,7 +1470,7 @@ public class ModelingUtils {
        
     }
        
-    public static void exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
+    public static TransferableGraph1 exportSharedOntology(IProgressMonitor monitor, RequestProcessor processor, File location, String format, int version, final LibraryInfo info) throws DatabaseException, IOException {
        
        if(monitor == null) monitor = new NullProgressMonitor();
        
@@ -1504,13 +1504,20 @@ public class ModelingUtils {
                metadata.put(ExternalDownloadBean.EXTENSION_KEY, edb);
             }
 
-            monitor.setTaskName("Writing transferable graph...");
-            DataContainers.writeFile(location, new DataContainer(
-                    format, version,
-                    metadata, new Variant(TransferableGraph1.BINDING, tg)));
-
-            monitor.worked(5);
+            if(location != null) {
+                   monitor.setTaskName("Writing transferable graph...");
+                   DataContainers.writeFile(location, new DataContainer(
+                           format, version,
+                           metadata, new Variant(TransferableGraph1.BINDING, tg)));
+                   monitor.worked(5);
+            }
+            
+            return tg;
+            
         }
+        
+        throw new DatabaseException("Failed to export");
+        
     }
 
     public static TreeMap<String, Variant> getExportMetadata() {
@@ -2205,7 +2212,7 @@ public class ModelingUtils {
 
        }
 
-       public static void exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
+       public static TransferableGraph1 exportSharedOntology(ReadGraph graph, Resource library, String fileName, String format, int version) throws DatabaseException {
                
         Layer0 L0 = Layer0.getInstance(graph);
         String name = graph.getRelatedValue(library, L0.HasName, Bindings.STRING);
@@ -2217,7 +2224,7 @@ public class ModelingUtils {
         LibraryInfo info = new LibraryInfo(name, library, draft);
                
        try {
-                       exportSharedOntology(new NullProgressMonitor(), graph, new File(fileName), format, version, info);
+                       return exportSharedOntology(new NullProgressMonitor(), graph, fileName != null ? new File(fileName) : null, format, version, info);
                } catch (IOException e) {
                        throw new DatabaseException(e);
                }
index c75f7a941a55f76c2bd668b0646a5fa76f40d826..09f7694dd482e5f1ce53ab784160ec3a078a2967 100644 (file)
@@ -71,7 +71,7 @@ public enum GraphModuleSourceRepository implements ModuleSourceRepository {
         }
         @Override
         public void removeListener(UpdateListener listener) {
-            listener = null;
+            this.listener = null;
         }
         @Override
         public boolean isDisposed() {
index cdd6a26458f578d4b30fbe3e5b8099a6191f6550..2dd285fd89d966387d6df759cb365af31740dca5 100644 (file)
@@ -278,7 +278,11 @@ public class SVGNode extends G2DNode implements InitValueSupport, LoaderNode {
                 if ("$text".equals(ass.attributeNameOrId)) {
                     if (e instanceof Tspan) {
                         Tspan t = (Tspan) e;
-                        t.setText(ass.value);
+                        if (ass.value.trim().isEmpty()) {
+                               t.setText("-");
+                        } else {
+                               t.setText(ass.value);
+                        }
                         SVGElement parent = t.getParent();
                         if (parent instanceof Text)
                             ((Text) parent).rebuild();
index 4650d2e13587c46cc85e3a2cccc3ba8470c0bda5..084c0d6582874a7f7cb64439a58e2495e4da12f8 100644 (file)
@@ -215,7 +215,7 @@ public class RouteGraphNode extends G2DNode implements ISelectionPainterNode, In
         if(dynamicColor != null || dynamicStroke != null) {
             BasicConnectionStyle baseStyle = (BasicConnectionStyle)tryGetStyle(baseRenderer);
             try {
-               Constructor<? extends BasicConnectionStyle> c = baseStyle.getClass().getConstructor(Color.class, Color.class, double.class, Stroke.class, Stroke.class, double.class);
+               Constructor<? extends BasicConnectionStyle> c = baseStyle.getClass().getConstructor(Color.class, Color.class, double.class, Stroke.class, Stroke.class, double.class, double.class);
                renderer = new StyledRouteGraphRenderer(c.newInstance(
                         dynamicColor != null ? dynamicColor : baseStyle.getLineColor(),
                                 baseStyle.getBranchPointColor(), baseStyle.getBranchPointRadius(),
diff --git a/bundles/org.simantics.scl.compiler.dummy/.classpath b/bundles/org.simantics.scl.compiler.dummy/.classpath
deleted file mode 100644 (file)
index eca7bdb..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
-       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
-       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
-       <classpathentry kind="src" path="src"/>
-       <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/bundles/org.simantics.scl.compiler.dummy/.project b/bundles/org.simantics.scl.compiler.dummy/.project
deleted file mode 100644 (file)
index 62879b7..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
-       <name>org.simantics.scl.compiler.dummy</name>
-       <comment></comment>
-       <projects>
-       </projects>
-       <buildSpec>
-               <buildCommand>
-                       <name>org.eclipse.jdt.core.javabuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-               <buildCommand>
-                       <name>org.eclipse.pde.ManifestBuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-               <buildCommand>
-                       <name>org.eclipse.pde.SchemaBuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-       </buildSpec>
-       <natures>
-               <nature>org.eclipse.pde.PluginNature</nature>
-               <nature>org.eclipse.jdt.core.javanature</nature>
-       </natures>
-</projectDescription>
diff --git a/bundles/org.simantics.scl.compiler.dummy/.settings/org.eclipse.jdt.core.prefs b/bundles/org.simantics.scl.compiler.dummy/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644 (file)
index 0c68a61..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.8
diff --git a/bundles/org.simantics.scl.compiler.dummy/META-INF/MANIFEST.MF b/bundles/org.simantics.scl.compiler.dummy/META-INF/MANIFEST.MF
deleted file mode 100644 (file)
index da14e13..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Dummy SCL compiler
-Bundle-SymbolicName: org.simantics.scl.compiler.dummy
-Bundle-Version: 1.0.0.qualifier
-Bundle-RequiredExecutionEnvironment: JavaSE-1.8
-Export-Package: org.simantics.scl.compiler
-Require-Bundle: org.simantics.scl.runtime;bundle-version="0.2.0"
diff --git a/bundles/org.simantics.scl.compiler.dummy/build.properties b/bundles/org.simantics.scl.compiler.dummy/build.properties
deleted file mode 100644 (file)
index 34d2e4d..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
-               .
diff --git a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/ErrorMessage.java b/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/ErrorMessage.java
deleted file mode 100644 (file)
index 958fd12..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-package org.simantics.scl.compiler;
-
-public class ErrorMessage {
-    int line;
-    int start;
-    int stop;
-    String message;
-    
-    public ErrorMessage(int line, int start, int stop, String message) {
-        this.line = line;
-        this.start = start;
-        this.stop = stop;
-        this.message = message;
-    }
-    
-    public int getLine() {
-        return line;
-    }
-    
-    public int getStart() {
-        return start;
-    }
-    
-    public int getStop() {
-        return stop;
-    }
-    
-    public String getMessage() {
-        return message;
-    }
-    
-    @Override
-    public String toString() {
-        return "at " + line + ":" + start + "-" + stop + " " + message;
-    }
-}
diff --git a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/InvalidInputException.java b/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/InvalidInputException.java
deleted file mode 100644 (file)
index 7a61c27..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-package org.simantics.scl.compiler;
-
-import java.util.Collection;
-
-public class InvalidInputException extends Exception {
-
-    private static final long serialVersionUID = 2923907879583127677L;
-    
-    Collection<ErrorMessage> errors;
-
-    public InvalidInputException(Collection<ErrorMessage> errors) {
-        this.errors = errors;
-    }
-    
-    public Collection<ErrorMessage> getErrors() {
-        return errors;
-    }
-
-}
diff --git a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompiler.java b/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompiler.java
deleted file mode 100644 (file)
index b552c70..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.simantics.scl.compiler;
-
-import java.io.InputStream;
-import java.util.Collections;
-
-import org.simantics.scl.runtime.Computation;
-
-public class SCLCompiler {
-    
-    public SCLCompiler(SCLCompilerConfiguration configuration) {
-    }
-    
-    public static Computation compileExpression(SCLCompilerConfiguration configuration, InputStream code) throws InvalidInputException {
-       throw new InvalidInputException(Collections.singleton(new ErrorMessage(0, 0, 0, "No SCL compiler")));
-    }
-    
-    public static Computation compileExpression(SCLCompilerConfiguration configuration, String code) throws InvalidInputException {
-       throw new InvalidInputException(Collections.singleton(new ErrorMessage(0, 0, 0, "No SCL compiler")));
-    }
-    
-}
diff --git a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompilerConfiguration.java b/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompilerConfiguration.java
deleted file mode 100644 (file)
index de0461f..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.simantics.scl.compiler;
-
-
-public interface SCLCompilerConfiguration {
-}
diff --git a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/StandardSCLCompilerConfiguration.java b/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/StandardSCLCompilerConfiguration.java
deleted file mode 100644 (file)
index e86be85..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-package org.simantics.scl.compiler;
-
-
-public class StandardSCLCompilerConfiguration implements SCLCompilerConfiguration {
-
-    public static final SCLCompilerConfiguration INSTANCE = new StandardSCLCompilerConfiguration();
-
-}
index 82d615ca89f476e248615ffb158075d5b7fa5826..1cf6d0de9c5f0786fe4df80072602e22670f514e 100644 (file)
@@ -76,7 +76,12 @@ public class CommandSession {
     THashMap<String,Type> variableTypes = new THashMap<String,Type>();
     
     PrintStream fileOutput;
-
+    
+    /**
+     * Only checks the commands for compilation errors but does not run them.
+     */
+    private boolean validateOnly; 
+    
     public CommandSession(ModuleRepository moduleRepository, SCLReportingHandler handler) {
         this.moduleRepository = moduleRepository;
         this.defaultHandler = new PrintDecorator(
@@ -320,6 +325,7 @@ public class CommandSession {
         Function command = (Function)evaluator
             .localEnvironment(localEnvironment)
             .decorateExpression(true)
+            .validateOnly(validateOnly)
             .eval();
         return new CompiledCommand(command, evaluator.getType());
     }
@@ -361,7 +367,9 @@ public class CommandSession {
                 handler.printCommand(reader.extractString(expression.location));
                 command = compile(expression);
             } catch (SCLExpressionCompilationException e) {
-                CompilationError[] errors = ((SCLExpressionCompilationException)e).getErrors();
+                if(validateOnly)
+                    throw e;
+                CompilationError[] errors = e.getErrors();
                 for(CompilationError error : errors) {
                     if(error.location != Locations.NO_LOCATION)
                         handler.printError(reader.locationUnderlining(error.location));
@@ -371,11 +379,15 @@ public class CommandSession {
             }
             reader.forgetEverythingBefore(Locations.endOf(expression.location));
 
-            Object resultValue = command.command.apply(variableValues);
-            String resultString = toString(resultValue, command.type);
-            if(!resultString.isEmpty())
-                handler.print(resultString);
+            if(!validateOnly) {
+                Object resultValue = command.command.apply(variableValues);
+                String resultString = toString(resultValue, command.type);
+                if(!resultString.isEmpty())
+                    handler.print(resultString);
+            }
         } catch(Exception e) {
+            if(validateOnly)
+                throw e;
             if(!(e instanceof CancelExecution)) {
                 if(e instanceof InterruptedException)
                     handler.printError("Execution interrupted.");
@@ -463,6 +475,24 @@ public class CommandSession {
         }
     }
     
+    private CompilationError[] validate(Reader commandReader) {
+        CommandParser parser = new CommandParser(defaultHandler, new MemoReader(commandReader));
+        validateOnly = true;
+        try {
+            parser.parseCommands();
+            parser.finishBlock();
+            return CompilationError.EMPTY_ARRAY;
+        } catch(SCLExpressionCompilationException e) {
+            return e.getErrors();
+        } catch(SCLSyntaxErrorException e) {
+            return new CompilationError[] { new CompilationError(e.location, e.getMessage()) };
+        } catch(Exception e) {
+            return new CompilationError[] { new CompilationError(Locations.NO_LOCATION, e.getMessage()) };
+        } finally {
+            validateOnly = false;
+        }
+    }
+    
     public void execute(Reader commandReader, SCLReportingHandler handler) {
         if(handler == null)
             handler = defaultHandler;
@@ -494,16 +524,6 @@ public class CommandSession {
         execute(new StringReader(command), handler);
     }
 
-    public CompilationError[] validate(String command) {
-        return CompilationError.EMPTY_ARRAY;
-        /*try {
-            compile(command);
-            return CompilationError.EMPTY_ARRAY;
-        } catch(SCLExpressionCompilationException e) {
-            return e.getErrors();
-        }*/
-    }
-
     private static final String THIS_CLASS_NAME = CommandSession.class.getName(); 
 
     public static void formatException(
@@ -632,4 +652,18 @@ public class CommandSession {
             formatException(handler, e);
         }
     }
+    
+    public static CompilationError[] validate(ModuleRepository moduleRepository,StringReader commandReader) {
+        CommandSession session = new CommandSession(moduleRepository, null);
+        return session.validate(commandReader);
+    }
+    
+    public static CompilationError[] validate(ModuleRepository moduleRepository,String command) {
+        return validate(moduleRepository, new StringReader(command));
+    }
+
+    public CompilationError[] validate(String command) {
+        return validate(new StringReader(command));
+    }
+
 }
index ab39d538a23a4f808440855956ea15a5b8e02d40..4afeef91c69b83f884aaacaa4b3baeb2e965d862 100644 (file)
@@ -12,11 +12,17 @@ public class TestScriptExecutor {
     private final CommandSession session;
     private final BufferedReader reader;
     private final SCLReportingHandler handler;
+    private boolean ignorePrints;
     
     public TestScriptExecutor(CommandSession session, BufferedReader reader, SCLReportingHandler handler) {
+        this(session, reader, handler, false);
+    }
+    
+    public TestScriptExecutor(CommandSession session, BufferedReader reader, SCLReportingHandler handler, boolean ignorePrints) {
         this.session = session;
         this.reader = reader;
         this.handler = handler == null ? SCLReportingHandler.DEFAULT : handler;
+        this.ignorePrints = ignorePrints;
     }
 
     public void execute() throws IOException {
@@ -67,7 +73,8 @@ public class TestScriptExecutor {
                     @Override
                     public void print(String text) {
                         handler.print(text);
-                        actualResponse.append(text).append('\n');
+                        if (!ignorePrints)
+                            actualResponse.append(text).append('\n');
                     }
                     
                     @Override
index 1737a0d7d8d7646665283d80eb32740783704aeb..1c4255b46c14ae83b9455fba3afb450a9d5e432e 100644 (file)
@@ -33,12 +33,13 @@ public class Names {
     public static final Name Prelude_bind = Name.create("Prelude", ">>=");
     public static final Name Prelude_build = Name.create("Prelude", "build");
     public static final Name Prelude_concatMap = Name.create("Prelude", "concatMap");
+    public static final Name Prelude_dollar = Name.create("Prelude", "$");
     public static final Name Prelude_elem = Name.create("Prelude", "elem");
     public static final Name Prelude_elemMaybe = Name.create("Prelude", "elemMaybe");
     public static final Name Prelude_emptyList = Name.create("Prelude", "emptyList");
     public static final Name Prelude_foldl = Name.create("Prelude", "foldl");
-    public static final Name Prelude_fromDouble = Name.create("Prelude", "fromDouble");    
-    public static final Name Prelude_fromInteger = Name.create("Prelude", "fromInteger"); 
+    public static final Name Prelude_fromDouble = Name.create("Prelude", "fromDouble");
+    public static final Name Prelude_fromInteger = Name.create("Prelude", "fromInteger");
     public static final Name Prelude_guardList = Name.create("Prelude", "guardList");
     public static final Name Prelude_iterList = Name.create("Prelude", "iterList");
     public static final Name Prelude_mapFirst = Name.create("Prelude", "mapFirst");
index fd5822743432a533e3ec9d5e482adfb2582733b1..501c7f95d3db2c4c52fbba2caa630ee1716bb1f1 100644 (file)
@@ -3,6 +3,7 @@ package org.simantics.scl.compiler.elaboration.expressions;
 import java.util.ArrayList;
 
 import org.simantics.scl.compiler.common.names.Name;
+import org.simantics.scl.compiler.common.names.Names;
 import org.simantics.scl.compiler.constants.NoRepConstant;
 import org.simantics.scl.compiler.elaboration.contexts.ReplaceContext;
 import org.simantics.scl.compiler.elaboration.contexts.SimplificationContext;
@@ -287,12 +288,16 @@ public class EApply extends Expression {
     
     @Override
     public Expression inferType(TypingContext context) {
+        if(parameters.length == 2 && function instanceof EConstant && ((EConstant)function).value.getName() == Names.Prelude_dollar)
+            return new EApply(location, parameters[0], parameters[1]).inferType(context);
         inferType(context, false);
         return this;
     }
     
     @Override
     public Expression checkIgnoredType(TypingContext context) {
+        if(parameters.length == 2 && function instanceof EConstant && ((EConstant)function).value.getName() == Names.Prelude_dollar)
+            return new EApply(location, parameters[0], parameters[1]).inferType(context);
         inferType(context, true);
         if(Types.canonical(getType()) != Types.UNIT)
             return new ESimpleLet(location, null, this, new ELiteral(NoRepConstant.PUNIT));
index fa5059626a12b1b881a2f6d913b74d4ef3bad3bc..45596c5704e5aad359f197e445781cca148509b7 100644 (file)
@@ -2,6 +2,7 @@ package org.simantics.scl.compiler.elaboration.java;
 
 import org.cojen.classfile.TypeDesc;
 import org.osgi.service.component.annotations.Component;
+import org.simantics.scl.compiler.commands.CommandSession;
 import org.simantics.scl.compiler.common.names.Name;
 import org.simantics.scl.compiler.constants.JavaMethod;
 import org.simantics.scl.compiler.elaboration.contexts.SimplificationContext;
@@ -48,8 +49,13 @@ public class LoggingModule extends ConcreteModule {
                 @Override
                 public Expression apply(SimplificationContext context, Type[] typeParameters, EApply apply) {
                     ConcreteModule module = context.getCompilationContext().module;
+                    String identifier;
+                    if (module != null)
+                        identifier = module.getName().replaceAll("/", ".");
+                    else
+                        identifier = CommandSession.class.getName();
                     apply.set(new ELiteral(javaMethod), new Expression[] {
-                            new EExternalConstant(LoggerFactory.getLogger(module.getName().replaceAll("/", ".")), Logger),
+                            new EExternalConstant(LoggerFactory.getLogger(identifier), Logger),
                             apply.parameters[0]
                     });
                     return apply;
index 27f853e0283b3d714757f4d3369cab4379cf470d..386199d838d3cfd0e60cb1faea0375bb45791e21 100644 (file)
@@ -1,6 +1,7 @@
 package org.simantics.scl.compiler.internal.codegen.ssa.exits;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 
 import org.objectweb.asm.Label;
 import org.simantics.scl.compiler.common.exceptions.InternalCompilerError;
@@ -26,6 +27,8 @@ import org.simantics.scl.compiler.types.TVar;
 import org.simantics.scl.compiler.types.Type;
 import org.simantics.scl.compiler.types.Types;
 
+import gnu.trove.map.hash.TIntObjectHashMap;
+
 public class Switch extends SSAExit implements ValRefBinder {
 
     ValRef scrutinee;
@@ -60,14 +63,19 @@ public class Switch extends SSAExit implements ValRefBinder {
         int defaultId;
         for(defaultId=0;defaultId<branches.length-1&&branches[defaultId].constructor!=null;++defaultId);
         int[] values = new int[defaultId];
-        Label[] labels = new Label[defaultId];
         Cont[] continuations = new Cont[defaultId+1];
+        TIntObjectHashMap<Label> labelMap = new TIntObjectHashMap<Label>(defaultId); 
         for(int i=0;i<defaultId;++i) {
-            values[i] = ((IntegerConstant)branches[i].constructor).getValue();
+            int value = ((IntegerConstant)branches[i].constructor).getValue();
+            values[i] = value;
             Cont cont = branches[i].cont.getBinding();
-            labels[i] = mb.getLabel(cont);
+            labelMap.put(value,  mb.getLabel(cont));
             continuations[i] = cont;
         }
+        Arrays.sort(values);
+        Label[] labels = new Label[defaultId];
+        for(int i=0;i<defaultId;++i)
+            labels[i] = labelMap.get(values[i]);
         Label defaultLabel;
         {
             Cont cont = branches[defaultId].cont.getBinding();
index 4efd2a8d404e7037925fd7d005d782e1fa5c8d3f..70160dee2615b4e284e637134b1efcf7e03e84a5 100644 (file)
@@ -1,5 +1,6 @@
 package org.simantics.scl.compiler.internal.codegen.utils;
 
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 
 import org.simantics.scl.runtime.function.FunctionImpl1;
@@ -26,6 +27,8 @@ public class ValueFromMethod {
                 Object ret = method.invoke(null, p0);
                 return returnsVoid ? Tuple0.INSTANCE : ret;
             } catch (ReflectiveOperationException e) {
+                if (e instanceof InvocationTargetException)
+                    throw new RuntimeException(e.getCause());
                 throw new RuntimeException(e);
             }
         }
index 269e8f6af9f9e49692951110d9484acf5b290f2f..a9e08af884cc3df303f6040f436b5bbd7662199a 100644 (file)
@@ -75,7 +75,7 @@ public class CoverageUtils {
     }
 
     public static void resetCoverage(Collection<Module> modules) {
-        modules.forEach(module -> resetCoverage(module));
+        modules.forEach(CoverageUtils::resetCoverage);
     }
 
     public static void resetCoverage(Module module) {
index c1881fbca53acb2ffc20a21a01a4f4291ed77cb4..2b42bc7bab865c75d8873ba8150504eb6aa47cc6 100644 (file)
@@ -27,6 +27,7 @@ import org.simantics.scl.compiler.elaboration.expressions.block.Statement;
 import org.simantics.scl.compiler.elaboration.java.Builtins;
 import org.simantics.scl.compiler.environment.Environment;
 import org.simantics.scl.compiler.environment.LocalEnvironment;
+import org.simantics.scl.compiler.errors.CompilationError;
 import org.simantics.scl.compiler.errors.ErrorLog;
 import org.simantics.scl.compiler.internal.codegen.references.IVal;
 import org.simantics.scl.compiler.internal.codegen.ssa.SSAModule;
@@ -77,6 +78,7 @@ public class ExpressionEvaluator {
     private LocalStorage localStorage;
     private boolean interpretIfPossible = true;
     private ExpressionParseMode parseMode = ExpressionParseMode.EXPRESSION;
+    private boolean validateOnly;
     
     public ExpressionEvaluator(RuntimeEnvironment runtimeEnvironment,
             String expressionText) {
@@ -115,6 +117,11 @@ public class ExpressionEvaluator {
         return this;
     }
     
+    public ExpressionEvaluator validateOnly(boolean validateOnly) {
+        this.validateOnly = validateOnly;
+        return this;
+    }
+    
     /**
      * Sets a local environment that can arbitrarily modify the resolving of the expression.
      */
@@ -175,6 +182,16 @@ public class ExpressionEvaluator {
             return "store_" + name;
         }
     }
+    
+    public CompilationError[] validate() {
+        try {
+            validateOnly = true;
+            eval();
+            return CompilationError.EMPTY_ARRAY;
+        } catch(SCLExpressionCompilationException e) {
+            return e.getErrors();
+        }
+    }
 
     public Object eval() throws SCLExpressionCompilationException {
         fillDefaults();
@@ -243,6 +260,8 @@ public class ExpressionEvaluator {
                                     Types.functionE(type, Types.PROC, Types.UNIT)),
                                     new EVar(variableName)
                             )));
+                    if(validateOnly)
+                        localStorage.store(variableName, null, type);
                 }
             }
             if(!(block.getStatements().getLast() instanceof GuardStatement))
@@ -293,6 +312,9 @@ public class ExpressionEvaluator {
 
             if(localEnvironment != null)
                 expression = localEnvironment.postDecorateExpression(expression);
+            
+            if(validateOnly)
+                return null;
 
             Type type = expression.getType();
             type = type.convertMetaVarsToVars();
index f5b2632d13b397b627251f2fe17a3475a16d7461..a4cb30582cdafb68578be4cf6051c191f7e81bdf 100644 (file)
@@ -2,7 +2,7 @@ package org.simantics.scl.compiler.top;
 
 import org.simantics.scl.compiler.errors.CompilationError;
 
-public class SCLExpressionCompilationException extends Exception {
+public class SCLExpressionCompilationException extends RuntimeException {
 
     private static final long serialVersionUID = 970640318254433797L;
 
index 9deb81124e2e37b27a1bc79c65f8396c1e9460b2..59f8e5fd804616a59ac705a31563160404206f92 100644 (file)
@@ -1,5 +1,10 @@
 package org.simantics.scl.osgi;
 
+import java.util.ArrayList;
+
+import org.simantics.scl.compiler.errors.DoesNotExist;
+import org.simantics.scl.compiler.errors.Failable;
+import org.simantics.scl.compiler.module.Module;
 import org.simantics.scl.compiler.module.repository.ModuleRepository;
 import org.simantics.scl.compiler.source.repository.ModuleSourceRepository;
 import org.simantics.scl.compiler.testing.repository.TestRepository;
@@ -7,6 +12,8 @@ import org.simantics.scl.osgi.internal.Activator;
 import org.simantics.scl.osgi.internal.ServiceBasedModuleSourceRepository;
 import org.simantics.scl.osgi.internal.ServiceBasedTestRepository;
 
+import gnu.trove.procedure.TObjectProcedure;
+
 
 public class SCLOsgi {
 
@@ -16,4 +23,33 @@ public class SCLOsgi {
     public static ModuleRepository MODULE_REPOSITORY = new ModuleRepository(SOURCE_REPOSITORY);
     public static TestRepository TEST_REPOSITORY = new ServiceBasedTestRepository(Activator.getContext());
 
+    
+    public static String compileAllModules() {
+        ArrayList<String> modulesWithErrors = new ArrayList<String>(); 
+        SCLOsgi.SOURCE_REPOSITORY.forAllModules(new TObjectProcedure<String>() {
+            @Override
+            public boolean execute(String moduleName) {
+                System.out.print(moduleName);
+                System.out.print(" - ");
+                Failable<Module> module = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName);
+                if(module.didSucceed())
+                    System.out.println("succeeded");
+                else if(module == DoesNotExist.INSTANCE)
+                    System.out.println("does not exist"); // should not happen
+                else {
+                    System.out.println("error");
+                    modulesWithErrors.add(moduleName);
+                }
+                return true;
+            }
+        });
+        if(!modulesWithErrors.isEmpty()) {
+            StringBuilder b = new StringBuilder();
+            b.append("Some SCL modules failed to compile:");
+            for(String module : modulesWithErrors)
+                b.append(' ').append(module);
+            return b.toString();
+        }
+        return null;
+    }
 }
diff --git a/bundles/org.simantics.scl.runtime/scl/Junit/Assert.scl b/bundles/org.simantics.scl.runtime/scl/Junit/Assert.scl
new file mode 100644 (file)
index 0000000..6b0cd2d
--- /dev/null
@@ -0,0 +1,20 @@
+importJava "org.junit.Assert" where
+    @JavaName assertEquals
+    @private
+    assertDoublesEquals :: String -> Double -> Double -> Double -> <Proc> ()
+    @JavaName assertEquals
+    @private
+    assertLongsEquals :: String -> Long -> Long -> <Proc> ()
+    
+    assertTrue :: String -> Boolean -> <Proc> ()
+    assertFalse :: String -> Boolean -> <Proc> ()
+
+class AssertEquals a  where
+    assertEquals :: String -> a -> a -> <Proc> ()
+instance AssertEquals Long where
+    assertEquals = assertLongsEquals
+
+class AssertEqualsTolerance a where
+    assertEqualsTolerance :: String -> a -> a -> a -> <Proc> ()
+instance AssertEqualsTolerance Double where
+    assertEqualsTolerance = assertDoublesEquals
diff --git a/bundles/org.simantics.scl.ui.editor/.classpath b/bundles/org.simantics.scl.ui.editor/.classpath
deleted file mode 100644 (file)
index eca7bdb..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
-       <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
-       <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
-       <classpathentry kind="src" path="src"/>
-       <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/bundles/org.simantics.scl.ui.editor/.gitignore b/bundles/org.simantics.scl.ui.editor/.gitignore
deleted file mode 100644 (file)
index c5e82d7..0000000
+++ /dev/null
@@ -1 +0,0 @@
-bin
\ No newline at end of file
diff --git a/bundles/org.simantics.scl.ui.editor/.project b/bundles/org.simantics.scl.ui.editor/.project
deleted file mode 100644 (file)
index aef84f5..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
-       <name>org.simantics.scl.ui.editor</name>
-       <comment></comment>
-       <projects>
-       </projects>
-       <buildSpec>
-               <buildCommand>
-                       <name>org.eclipse.jdt.core.javabuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-               <buildCommand>
-                       <name>org.eclipse.pde.ManifestBuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-               <buildCommand>
-                       <name>org.eclipse.pde.SchemaBuilder</name>
-                       <arguments>
-                       </arguments>
-               </buildCommand>
-       </buildSpec>
-       <natures>
-               <nature>org.eclipse.pde.PluginNature</nature>
-               <nature>org.eclipse.jdt.core.javanature</nature>
-       </natures>
-</projectDescription>
diff --git a/bundles/org.simantics.scl.ui.editor/.settings/org.eclipse.jdt.core.prefs b/bundles/org.simantics.scl.ui.editor/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644 (file)
index 0c68a61..0000000
+++ /dev/null
@@ -1,7 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.8
diff --git a/bundles/org.simantics.scl.ui.editor/META-INF/MANIFEST.MF b/bundles/org.simantics.scl.ui.editor/META-INF/MANIFEST.MF
deleted file mode 100644 (file)
index 6dc71a6..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: SCL Workbench Editor
-Bundle-SymbolicName: org.simantics.scl.ui.editor
-Bundle-Version: 0.1.3
-Bundle-RequiredExecutionEnvironment: JavaSE-1.8
-Require-Bundle: org.eclipse.swt;bundle-version="3.104.0",
- gnu.trove3;bundle-version="3.0.3",
- org.simantics.scl.compiler.dummy;bundle-version="0.0.9",
- org.simantics.scl.runtime;bundle-version="0.0.9",
- org.eclipse.jface;bundle-version="3.11.0",
- org.eclipse.jface.text;bundle-version="3.6.0",
- org.eclipse.core.runtime;bundle-version="3.11.0",
- org.eclipse.ui.workbench.texteditor;bundle-version="3.6.0",
- org.eclipse.ui.editors;bundle-version="3.6.0"
-Export-Package: org.simantics.scl.ui.editor
-Bundle-Vendor: VTT Technical Research Centre of Finland
diff --git a/bundles/org.simantics.scl.ui.editor/build.properties b/bundles/org.simantics.scl.ui.editor/build.properties
deleted file mode 100644 (file)
index 34d2e4d..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
-               .
diff --git a/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLAnnotationAccess.java b/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLAnnotationAccess.java
deleted file mode 100644 (file)
index 5a300fb..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-package org.simantics.scl.ui.editor;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.IAnnotationAccess;
-import org.eclipse.jface.text.source.IAnnotationAccessExtension;
-import org.eclipse.jface.text.source.ImageUtilities;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-
-final class SCLAnnotationAccess implements IAnnotationAccess, IAnnotationAccessExtension {
-
-    ImageRegistry registry;
-    
-    public SCLAnnotationAccess(ImageRegistry registry) {
-        this.registry = registry;
-    }
-
-    @Override
-    public Object getType(Annotation annotation) {
-        return annotation.getType();
-    }
-
-    @Override
-    public boolean isMultiLine(Annotation annotation) {
-        return true;
-    }
-
-    @Override
-    public boolean isTemporary(Annotation annotation) {
-        return !annotation.isPersistent();
-    }
-
-    @Override
-    public String getTypeLabel(Annotation annotation) {
-        return annotation.getType();
-    }
-
-    @Override
-    public int getLayer(Annotation annotation) {
-        return 0;
-    }
-
-    @Override
-    public void paint(Annotation annotation, GC gc, Canvas canvas, Rectangle bounds) {
-        Image image = registry.get("error");
-        if(image == null) {
-            registry.put("error", ImageDescriptor.createFromFile(getClass(), "error_tsk.gif"));
-            image = registry.get("error");
-        }
-        ImageUtilities.drawImage(image, gc, canvas, bounds, SWT.CENTER, SWT.TOP);
-    }
-
-    @Override
-    public boolean isPaintable(Annotation annotation) {
-        return true;
-    }
-
-    @Override
-    public boolean isSubtype(Object annotationType, Object potentialSupertype) {
-        return annotationType.equals(potentialSupertype);
-    }
-
-    @Override
-    public Object[] getSupertypes(Object annotationType) {
-        return new Object[0];
-    }
-}
\ No newline at end of file
diff --git a/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLSourceViewerConfiguration.java b/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLSourceViewerConfiguration.java
deleted file mode 100644 (file)
index 0ceb9f6..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-package org.simantics.scl.ui.editor;
-
-import org.eclipse.jface.text.DefaultTextHover;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.TextAttribute;
-import org.eclipse.jface.text.presentation.IPresentationReconciler;
-import org.eclipse.jface.text.presentation.PresentationReconciler;
-import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
-import org.eclipse.jface.text.rules.IRule;
-import org.eclipse.jface.text.rules.ITokenScanner;
-import org.eclipse.jface.text.rules.IWordDetector;
-import org.eclipse.jface.text.rules.MultiLineRule;
-import org.eclipse.jface.text.rules.PatternRule;
-import org.eclipse.jface.text.rules.RuleBasedScanner;
-import org.eclipse.jface.text.rules.Token;
-import org.eclipse.jface.text.rules.WordRule;
-import org.eclipse.jface.text.source.DefaultAnnotationHover;
-import org.eclipse.jface.text.source.IAnnotationHover;
-import org.eclipse.jface.text.source.ISharedTextColors;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.SourceViewerConfiguration;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.RGB;
-
-public class SCLSourceViewerConfiguration extends SourceViewerConfiguration {
-
-    public static final char[] CONTENT_ASSIST_AUTO_CHARS = new char[] { '.' };
-    Device device;
-    
-    ISharedTextColors sharedTextColors;
-    
-    public SCLSourceViewerConfiguration(Device device,
-            ISharedTextColors sharedTextColors) {
-        this.device = device;
-        this.sharedTextColors = sharedTextColors;
-    }
-
-    public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
-        return new String[] {
-            IDocument.DEFAULT_CONTENT_TYPE
-        };
-    }
-    
-    public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
-        PresentationReconciler reconciler = new PresentationReconciler();
-        
-        DefaultDamagerRepairer dr = new DefaultDamagerRepairer(getSclTokenScanner());
-        
-        reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
-        reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
-        
-        return reconciler;
-    }
-    
-    ITokenScanner getSclTokenScanner() {
-        RuleBasedScanner scanner = new RuleBasedScanner();
-        
-        Font font = new Font(device, "Courier New", 10, SWT.NORMAL);
-        Font boldFont = new Font(device, "Courier New", 10, SWT.BOLD);
-
-        Token defaultToken = new Token(
-                new TextAttribute(
-                        sharedTextColors.getColor(new RGB(0, 0, 0)),
-                        null,
-                        0,
-                        font
-                ));
-        Token string = new Token(new TextAttribute(
-                sharedTextColors.getColor(new RGB(42, 0, 255)),
-                null,
-                0,
-                font
-                ));
-        Token reserved = new Token(
-                new TextAttribute(
-                        sharedTextColors.getColor(new RGB(127, 0, 85)),
-                        null,
-                        SWT.BOLD,
-                        boldFont
-                ));
-        Token comment = new Token(new TextAttribute(
-                sharedTextColors.getColor(new RGB(63, 127, 95)),
-                null,
-                0,
-                font
-                ));
-
-        WordRule reservedWord = new WordRule(new IWordDetector() {          
-            @Override
-            public boolean isWordStart(char c) {
-                return Character.isJavaIdentifierStart(c);
-            }
-            
-            @Override
-            public boolean isWordPart(char c) {
-                return Character.isJavaIdentifierPart(c) || c=='.';
-            }
-        });
-
-        reservedWord.addWord("if", reserved);
-        reservedWord.addWord("then", reserved);
-        reservedWord.addWord("else", reserved);
-        reservedWord.addWord("match", reserved);
-        reservedWord.addWord("with", reserved);
-        reservedWord.addWord("data", reserved);
-        reservedWord.addWord("type", reserved);
-        reservedWord.addWord("class", reserved);
-        
-        IRule[] rules = new IRule[] {
-            //new MultiLineRule("\"\"\"", "\"\"\"", string),
-            new PatternRule("\"", "\"", string, '\\', true),
-            new MultiLineRule("/*", "*/", comment),
-            new PatternRule("//", null, comment, '\0', true),
-            reservedWord
-        };
-        scanner.setRules(rules);
-        scanner.setDefaultReturnToken(defaultToken);
-        
-        return scanner;     
-    }
-    
-    @Override
-    public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
-        return new DefaultTextHover(sourceViewer);
-    }
-    
-    @Override
-    public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
-        return new DefaultAnnotationHover();
-    }
-}
diff --git a/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLTextEditor.java b/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SCLTextEditor.java
deleted file mode 100644 (file)
index ee081ff..0000000
+++ /dev/null
@@ -1,234 +0,0 @@
-package org.simantics.scl.ui.editor;
-
-
-import java.util.Collection;
-import java.util.Iterator;
-
-import org.eclipse.jface.resource.ImageRegistry;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.ITextListener;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.TextEvent;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.AnnotationModel;
-import org.eclipse.jface.text.source.AnnotationPainter;
-import org.eclipse.jface.text.source.IAnnotationModel;
-import org.eclipse.jface.text.source.ISharedTextColors;
-import org.eclipse.jface.text.source.OverviewRuler;
-import org.eclipse.jface.text.source.SourceViewer;
-import org.eclipse.jface.text.source.VerticalRuler;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.simantics.scl.compiler.ErrorMessage;
-import org.simantics.scl.compiler.InvalidInputException;
-import org.simantics.scl.compiler.SCLCompiler;
-import org.simantics.scl.compiler.SCLCompilerConfiguration;
-
-public class SCLTextEditor extends Composite {
-
-    private static final int DELAY_BEFORE_COMPILATION = 500 /*ms*/;
-    
-    SCLCompilerConfiguration configuration;
-    
-    SourceViewer viewer;
-    ImageRegistry imageRegistry;
-    SCLAnnotationAccess annotationAccess;
-    ISharedTextColors sharedTextColors;
-    IAnnotationModel annotationModel;    
-    
-    public SCLTextEditor(Composite parent, int style, SCLCompilerConfiguration configuration) {
-        super(parent, style);
-        setLayout(new FillLayout());
-        
-        this.configuration = configuration;
-        
-        imageRegistry = new ImageRegistry(parent.getDisplay());
-        annotationAccess = new SCLAnnotationAccess(imageRegistry);
-        sharedTextColors = new SharedTextColors(getDisplay());
-        annotationModel = new AnnotationModel();
-        
-        VerticalRuler leftRuler = new VerticalRuler(12, annotationAccess);
-        leftRuler.setModel(annotationModel);
-        
-        OverviewRuler rightRuler = 
-            new OverviewRuler(annotationAccess, 12, sharedTextColors);
-        rightRuler.setModel(annotationModel);
-        rightRuler.addAnnotationType("error");
-        rightRuler.setAnnotationTypeLayer("error", 0);
-        rightRuler.setAnnotationTypeColor("error", sharedTextColors.getColor(new RGB(255,0,128)));
-        
-        viewer = new SourceViewer(this, 
-                leftRuler, rightRuler,
-                true,
-                SWT.H_SCROLL | SWT.V_SCROLL);
-        Document document = new Document();
-        viewer.setDocument(document, annotationModel);
-        viewer.setEditable(true);
-        viewer.configure(new SCLSourceViewerConfiguration(
-                getDisplay(), sharedTextColors));
-        
-        // Annotations to text area
-        AnnotationPainter annotationPainter = 
-            new AnnotationPainter(viewer, annotationAccess);
-        annotationPainter.addAnnotationType("error");
-        annotationPainter.setAnnotationTypeColor("error", sharedTextColors.getColor(new RGB(255,0,128)));
-        viewer.addPainter(annotationPainter);
-        annotationModel.addAnnotationModelListener(annotationPainter);
-        
-        // Undo support (maybe not needed in workbench?)
-        viewer.getTextWidget().addKeyListener(new KeyAdapter() {
-            @Override
-            public void keyReleased(KeyEvent e) {
-            }
-            @Override
-            public void keyPressed(KeyEvent e) {
-                if(e.keyCode=='z'&& e.stateMask == SWT.CTRL) {
-                    viewer.getUndoManager().undo();
-                }
-                else if(e.keyCode=='y'&& e.stateMask == SWT.CTRL) {
-                    viewer.getUndoManager().redo();
-                }
-            }
-        });        
-        
-        // Automatic compilation when text changes
-        viewer.addTextListener(new ITextListener() {            
-            @Override
-            public void textChanged(TextEvent event) {
-                scheduleCompilation();                
-            }
-        });
-    }
-    
-    @Override
-    public void dispose() {
-        super.dispose();
-        sharedTextColors.dispose();
-    }    
-    
-    @SuppressWarnings("unchecked")
-    private void removeAnnotations() {
-        Iterator<Annotation> it = annotationModel.getAnnotationIterator();
-        while(it.hasNext()) {
-            Annotation annotation = it.next();
-            annotationModel.removeAnnotation(annotation);
-        }
-    }
-    
-    private void setAnnotations(Collection<ErrorMessage> messages) {
-        removeAnnotations();
-        for(ErrorMessage message : messages) {
-            annotationModel.addAnnotation(
-                    new Annotation("error", true, message.getMessage()), 
-                    new Position(message.getStart(), message.getStop()-message.getStart()+1));   
-        }
-    }
-    
-    /**
-     * Tries to compile current 
-     */
-    private void compileSync(String code) {
-        try {            
-            SCLCompiler.compileExpression(configuration, code);
-            getDisplay().asyncExec(new Runnable() {
-                @Override
-                public void run() {
-                    removeAnnotations();                    
-                }
-            });            
-        } catch (final InvalidInputException e) {
-            getDisplay().asyncExec(new Runnable() {
-                @Override
-                public void run() {
-                    setAnnotations(e.getErrors());                    
-                }
-            });            
-        } catch(Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    Object compilationLock = new Object();
-    String codeToBeCompiled;
-    
-    private synchronized void scheduleCompilation() {
-        synchronized(compilationLock) {
-            if(codeToBeCompiled == null) {
-                new Thread("SCLTextEditor compilation") {
-                    public void run() {                        
-                        while(true) {     
-                            String code;
-                            // Waits until code has remained unmodified for
-                            // time specified by DELAY_BEFORE_COMPILATION. 
-                            synchronized(compilationLock) {
-                                do {
-                                    code = codeToBeCompiled;  
-                                    try {
-                                        compilationLock.wait(DELAY_BEFORE_COMPILATION);
-                                    } catch (InterruptedException e) {
-                                    }
-                                } while(!code.equals(codeToBeCompiled));
-                            }
-                            
-                            // Does the actual compilation and updates
-                            // annotations.
-                            compileSync(code);
-                            
-                            // If code was not modified during compilation,
-                            // exits the compilation thread and sets
-                            // codeToBeCompiled null to signal inactivity.
-                            synchronized(compilationLock) {
-                                if(code.equals(codeToBeCompiled)) {
-                                    codeToBeCompiled = null;
-                                    return;
-                                }
-                            }
-                        }                        
-                    }
-                }.start();            
-            }
-            codeToBeCompiled = viewer.getDocument().get();
-            compilationLock.notify();
-        }
-    }
-    
-    public String getContent() {
-        final String[] result = new String[1];
-        getDisplay().syncExec(new Runnable() {
-            @Override
-            public void run() {
-                result[0] = viewer.getDocument().get();
-            }
-        });
-        return result[0];
-    }
-    
-    public void setContent(final String content) {
-        getDisplay().asyncExec(new Runnable() {
-            @Override
-            public void run() {
-                if (viewer.getTextWidget().isDisposed()) return;
-                viewer.getDocument().set(content);
-            }
-        });
-    }
-
-    private Point storedSelectedRange;
-
-    public void storeSelectedRange() {
-        storedSelectedRange = viewer.getSelectedRange();
-    }
-
-    public void restoreSelectedRange() {
-        if (storedSelectedRange != null) {
-            viewer.setSelectedRange(storedSelectedRange.x, storedSelectedRange.y);
-            storedSelectedRange = null;
-        }
-    }
-
-}
diff --git a/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SharedTextColors.java b/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/SharedTextColors.java
deleted file mode 100644 (file)
index f5c71dc..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-package org.simantics.scl.ui.editor;
-
-import gnu.trove.map.hash.THashMap;
-
-import org.eclipse.jface.text.source.ISharedTextColors;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
-
-final class SharedTextColors implements ISharedTextColors {
-
-    Display display;
-    THashMap<RGB,Color> map = new THashMap<RGB,Color>();
-    
-    public SharedTextColors(Display display) {
-        this.display = display;
-    }
-
-    @Override
-    public Color getColor(RGB rgb) {
-        Color color = map.get(rgb);
-        if(color == null) {
-            color = new Color(display, rgb);
-            map.put(rgb, color);
-        }
-        return color;
-    }
-
-    @Override
-    public void dispose() {
-        for(Color color : map.values())
-            color.dispose();
-        map.clear();
-    }
-}
\ No newline at end of file
diff --git a/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/TestTextEditor.java b/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/TestTextEditor.java
deleted file mode 100644 (file)
index 7f29fbb..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-package org.simantics.scl.ui.editor;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.simantics.scl.compiler.SCLCompiler;
-import org.simantics.scl.compiler.StandardSCLCompilerConfiguration;
-
-public class TestTextEditor {
-
-    public static void main(String[] args) {
-        Display display = new Display();
-        final Shell shell = new Shell(display);
-        shell.setText("SCL text widget example");
-        shell.setLayout(new FillLayout());
-        
-        SashForm sashForm = new SashForm(shell, SWT.VERTICAL);        
-        
-        final SCLTextEditor editor = new SCLTextEditor(sashForm, 0, StandardSCLCompilerConfiguration.INSTANCE);
-        editor.setContent(
-             "// Difficulty: 0\n" +
-             "// Expected: [2.0, 3.0, 5.0, 7.0, 11.0, 13.0, 17.0, 19.0]\n\n" +
-             "// and : [Boolean] -> Boolean\n" +
-             "and = fold (&&) True\n\n" +
-             "// isPrime : Integer -> Boolean\n" +
-             "isPrime p = and (\n" +
-             "    d <- [2 .. sqrt p]\n" +
-             "    [p % d > 0]\n" +
-             ")\n\n" +
-             "x <- [2 .. 20]\n" +
-             "isPrime x\n" +
-             "[x]"
-          );
-        
-        final Text resultArea = new Text(sashForm, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
-        resultArea.setText("Ctrl-S executes the code.");
-        resultArea.setEditable(false);
-        resultArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255));
-        resultArea.setFont(new Font(shell.getDisplay(), "Courier New", 10, SWT.NORMAL));
-        
-        sashForm.setWeights(new int[] {5, 1});
-        
-        display.addFilter(SWT.KeyDown, new Listener() {
-            @Override
-            public void handleEvent(Event event) {
-                if(event.keyCode == 's' && event.stateMask == SWT.CTRL) {
-                    final String code = editor.getContent();
-                    new Thread() {
-                        public void run() {
-                            try {
-                                final String result = SCLCompiler.compileExpression(StandardSCLCompilerConfiguration.INSTANCE, code).execute().toString();
-                                shell.getDisplay().asyncExec(new Runnable() {
-                                    public void run() {
-                                        resultArea.setText(result);    
-                                    }                                                
-                                });
-                            } catch (Exception e) {
-                            }
-                        }
-                    }.start();
-                    event.doit = false;
-                }
-            }
-        });
-        shell.addKeyListener(new KeyAdapter() {
-            @Override
-            public void keyPressed(KeyEvent e) {
-                System.out.println(e);
-            }
-        });
-        
-        shell.open();
-        while (!shell.isDisposed ()) {
-            if (!display.readAndDispatch ()) display.sleep ();
-        }
-        display.dispose ();
-    }
-    
-}
diff --git a/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/error_tsk.gif b/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/error_tsk.gif
deleted file mode 100644 (file)
index 9b048d6..0000000
Binary files a/bundles/org.simantics.scl.ui.editor/src/org/simantics/scl/ui/editor/error_tsk.gif and /dev/null differ
index 1398f2c07a5423510f058aab0b122d8469e4a141..100f49e252f68fe6cc8e42b795b12acc0c9bf3b3 100644 (file)
@@ -15,7 +15,7 @@ import org.simantics.scl.ui.editor.completion.SCLTextEditorEnvironment;
 
 public class SCLModuleEditor2 extends TextEditor {
     private boolean disposed = false;
-    ResourceManager resourceManager;
+    protected ResourceManager resourceManager;
 
     public SCLModuleEditor2() {
         super();
index a819ef8ed915462da196d5e120ceee3a6a070021..ecf7f0a9ae82ee8d42cce99e67c996dbab2ed446 100644 (file)
@@ -136,17 +136,19 @@ public final class ExperimentUtil {
                 protected IStatus run(final IProgressMonitor monitor) {
                     try {
                         experiment.shutdown(monitor);
-                        if (callback != null)
-                            callback.accept(null);
                         return Status.OK_STATUS;
                     } finally {
                         monitor.done();
+                        if (callback != null)
+                            callback.accept(null);
                     }
                 }
             };
             job.setProperty(IProgressConstants2.SHOW_IN_TASKBAR_ICON_PROPERTY, Boolean.TRUE);
             job.setUser(true);
             job.schedule();
+        } else {
+            callback.accept(null);
         }
     }
 
index 08fdd9180b498205454594de8b8a619b90322ce5..8ecef199d819ff57e72b3dabf1079e6acdbb7612 100644 (file)
@@ -11,7 +11,6 @@ Require-Bundle: org.simantics.layer0.utils,
  org.simantics.diagram.ontology;bundle-version="1.0.0",
  org.simantics.structural.ontology;bundle-version="1.0.0",
  org.simantics.basicexpression;bundle-version="1.0.0",
- org.simantics.scl.compiler.dummy;bundle-version="0.1.2",
  org.simantics.db.layer0;bundle-version="1.1.0",
  org.simantics.scl.db;bundle-version="0.1.2",
  org.simantics.scl.runtime;bundle-version="0.1.2",
index 66d1bc3342353589f2740aac50bb3db45ff3f6cc..3d0a8ef9c07ede0860b1110b73ebb49568d9f6bd 100644 (file)
@@ -3,7 +3,9 @@ Bundle-ManifestVersion: 2
 Bundle-Name: http://www.simantics.org/Tests
 Bundle-SymbolicName: org.simantics.tests.modelled.ontology
 Bundle-Version: 1.0.0.qualifier
-Require-Bundle: org.simantics.layer0
+Require-Bundle: org.simantics.layer0,
+ org.simantics.selectionview.ontology;bundle-version="1.2.0",
+ org.simantics.modeling.ontology;bundle-version="1.2.0"
 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
 Export-Package: org.simantics.tests.modelled.ontology
 Bundle-Vendor: Semantum Oy
index 11b93d2d4a7632e93c3f2180f201e1067880e323..8364abd1875c6cec0b9a99f27345a80d983a78e4 100644 (file)
@@ -1,5 +1,6 @@
 L0 = <http://www.simantics.org/Layer0-1.1>
-
+SEL = <http://www.simantics.org/SelectionView-1.2>
+MOD = <http://www.simantics.org/Modeling-1.2>
 
 TESTS = <http://www.simantics.org/Tests-1.0> : L0.Ontology
     @L0.new
@@ -9,12 +10,35 @@ TESTS.SCLMain : L0.SCLModule
     L0.SCLModule.definition _ : L0.String 
       @L0.loadString "scl/SCLMain.scl" 
 
+TESTS.STSTest.definition <R L0.HasProperty : L0.TotalFunction : SEL.GenericParameterType
+    L0.HasRange L0.String
+    L0.HasLabel "Test definition"
+
+TESTS.STSTest.executionPriority <R L0.HasProperty : L0.TotalFunction : SEL.GenericParameterType
+    L0.HasRange L0.Integer
+    L0.HasLabel "Execution priority" 
+
+TESTS.ignore <R L0.HasProperty : L0.TotalFunction : SEL.GenericParameterType
+    L0.HasRange L0.Boolean
+    L0.HasLabel "Ignore"
+
+TESTS.ignoreReason <R L0.HasProperty : L0.TotalFunction : SEL.GenericParameterType
+    L0.HasRange L0.String
+    L0.HasLabel "Ignore reason"
+
 TESTS.STSTest <T L0.Entity
-    >-- TESTS.STSTest.definition --> L0.String <R L0.HasProperty : L0.TotalFunction
-    >-- TESTS.STSTest.executionPriority --> L0.Integer <R L0.HasProperty : L0.TotalFunction
     @L0.assert TESTS.STSTest.definition ""
     @L0.assert TESTS.STSTest.executionPriority -1
+    @L0.assert TESTS.ignore false
+    @L0.assert TESTS.ignoreReason ""
+
+TESTS.STSTest : MOD.TypeWithChangeInformation 
+TESTS.STSTest : L0.TypeWithIdentifier
 
 TESTS.STSSuite <T L0.Entity
-    >-- TESTS.STSSuite.moduleNameFilter --> L0.String <R L0.HasProperty : L0.TotalFunction
-    @L0.assert TESTS.STSSuite.moduleNameFilter ""
\ No newline at end of file
+    >-- TESTS.STSSuite.moduleNameFilter --> L0.String <R L0.HasProperty : L0.TotalFunction : SEL.GenericParameterType
+    @L0.assert TESTS.STSSuite.moduleNameFilter ""
+    @L0.assert TESTS.ignore false
+
+TESTS.STSSuite : MOD.TypeWithChangeInformation 
+TESTS.STSSuite : L0.TypeWithIdentifier
\ No newline at end of file
index 4cf2070eb0a243f3a6787768a52f422a398121f7..a279041ed2f7c8497efa0e8d2802159dca3b2c92 100644 (file)
@@ -12,3 +12,4 @@ Require-Bundle: org.simantics.layer0,
  org.simantics.image2.ontology;bundle-version="1.2.0"
 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
 Bundle-Vendor: Semantum Oy
+Export-Package: org.simantics.tests.modelled.ui.ontology
index ecebcf8fa3d5524a25146fded17dd874ef9b4750..f92524b797ae40dd43dee90286f60a2e01c8db5f 100644 (file)
@@ -17,21 +17,25 @@ TestsUI.SCLMain : L0.SCLModule
 TestsUI.testImage : IMAGE.PngImage
   @L0.loadBytes "images/test.png"
 
+TestsUI.testIgnoredImage : IMAGE.PngImage
+  @L0.loadBytes "images/testignored.gif"
+
 TestsUI.testSuiteImage : IMAGE.PngImage
   @L0.loadBytes "images/tsuite.png"
 
 // Library containing all testing viewpoint contributions
 TestsUI.Contributions : L0.Library
 
-
 MBC = TestsUI.BrowseContext : VP.BrowseContext
     VP.BrowseContext.IsIncludedIn PROJECT.ProjectBrowseContext
 
+MBC.TestImageRule : VP.ImageRule
+
 MBC
-    @VP.namedRelationChildRule           TestsUI.Contributions.STSSuites L0.Entity   L0.ConsistsOf TESTS.STSSuite
-    @VP.namedConstantImageRule           TestsUI.Contributions.SuiteImage           TESTS.STSSuite                         TestsUI.testSuiteImage
-    @VP.namedRelationChildRule           TestsUI.Contributions.STSTests L0.Entity   L0.ConsistsOf TESTS.STSTest
-    @VP.namedConstantImageRule           TestsUI.Contributions.TestImage           TESTS.STSTest                         TestsUI.testImage
+    @VP.namedRelationChildRule    TestsUI.Contributions.STSSuites           L0.Entity                              L0.ConsistsOf TESTS.STSSuite
+    @VP.namedConstantImageRule    TestsUI.Contributions.SuiteImage          TESTS.STSSuite                         TestsUI.testSuiteImage
+    @VP.namedRelationChildRule    TestsUI.Contributions.STSTests            L0.Entity                              L0.ConsistsOf TESTS.STSTest
+    @VP.customImageRule           TESTS.STSTest                             MBC.TestImageRule
 
 MBC
     VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution
diff --git a/bundles/org.simantics.tests.modelled.ui.ontology/graph/images/testignored.gif b/bundles/org.simantics.tests.modelled.ui.ontology/graph/images/testignored.gif
new file mode 100644 (file)
index 0000000..450515f
Binary files /dev/null and b/bundles/org.simantics.tests.modelled.ui.ontology/graph/images/testignored.gif differ
index 776eea39ef2df99d34f5e3eba561233ce2c539c3..cd48cdc86b40ec8fac8a53c7fc3ade56b8953a7e 100644 (file)
@@ -16,7 +16,8 @@ Require-Bundle: org.eclipse.ui,
  org.simantics.tests.modelled;bundle-version="1.0.0",
  org.eclipse.e4.ui.model.workbench,
  org.simantics.scl.osgi,
- org.simantics.browsing.ui.model
+ org.simantics.browsing.ui.model,
+ org.slf4j.api
 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
 Bundle-ActivationPolicy: lazy
 Bundle-Vendor: Semantum Oy
index 4827e6cc05376188c7e54cdf493139616280410f..1dc8f8561a9fccf78b39871a2e6b83c94f0727eb 100644 (file)
@@ -1,10 +1,13 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <adapters>
-       <target interface="org.simantics.browsing.ui.model.visuals.VisualsRule">
-               <resource
-                       uri="http://www.simantics.org/TestsUI-0.0/BrowseContext/STSSuiteSorterRule"
-                       class="org.simantics.tests.modelled.ui.STSSuiteSorterRule" />
-       </target>
-
+    <target interface="org.simantics.browsing.ui.model.visuals.VisualsRule">
+        <resource
+            uri="http://www.simantics.org/TestsUI-0.0/BrowseContext/STSSuiteSorterRule"
+            class="org.simantics.tests.modelled.ui.STSSuiteSorterRule" />
+        <resource
+            uri="http://www.simantics.org/TestsUI-0.0/BrowseContext/TestImageRule"
+            class="org.simantics.tests.modelled.ui.rules.TestImageRule">
+            <graph/>
+        </resource>
+    </target>
 </adapters>
\ No newline at end of file
index 883af2f9eaaeb01aec601f8d5ddaba00139945eb..150c2939cae1a1a25d10e10b90fc5124d27ffc7c 100644 (file)
    </extension>
    <extension
          point="org.simantics.ui.resourceEditorAdapter">
-       <adapter
-            label="STS Test Editor"
-            priority="1"
-            editorId="org.simantics.tests.ui.stsTestEditor"
-            type_uris="http://www.simantics.org/Tests-1.0/STSTest">
-      </adapter>
+      <adapterClass
+            class="org.simantics.tests.modelled.ui.STSEditorAdapter"
+            id="org.simantics.tests.ui.stsTestEditor"
+            priority="10">
+      </adapterClass>
+   </extension>
+   <extension
+         point="org.eclipse.ui.elementFactories">
+      <factory
+            class="org.simantics.tests.modelled.ui.STSEditorInputFactory"
+            id="org.simantics.tests.modelled.ui.stseditor.inputFactory">
+      </factory>
    </extension>
    <extension
          point="org.eclipse.ui.views">
index b3d8fc9d87db3646f204d6c88164909be5c36d14..8cae1510bca8b3b7aa59f4cd959c680f682b199d 100644 (file)
@@ -6,6 +6,7 @@ import java.util.List;
 
 import org.eclipse.jface.resource.ImageDescriptor;
 import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Resource;
 import org.eclipse.ui.plugin.AbstractUIPlugin;
 import org.osgi.framework.BundleContext;
 
@@ -41,8 +42,7 @@ public class Activator extends AbstractUIPlugin {
         */
        public void stop(BundleContext context) throws Exception {
                plugin = null;
-               for (Image image : imagesToDispose)
-                   image.dispose();
+               imagesToDispose.forEach(Resource::dispose);
                super.stop(context);
        }
 
diff --git a/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSEditorAdapter.java b/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSEditorAdapter.java
new file mode 100644 (file)
index 0000000..363087f
--- /dev/null
@@ -0,0 +1,68 @@
+package org.simantics.tests.modelled.ui;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.tests.modelled.ontology.TestsResource;
+import org.simantics.ui.workbench.editor.AbstractResourceEditorAdapter;
+import org.simantics.ui.workbench.editor.EditorAdapter;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class STSEditorAdapter extends AbstractResourceEditorAdapter implements EditorAdapter {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(STSEditorAdapter.class);
+    
+    public STSEditorAdapter() {
+        super("SCL Module Editor", null, 20);
+    }
+    
+    @Override
+    public boolean canHandle(ReadGraph g, Object input)
+            throws DatabaseException {
+        if(input instanceof IStructuredSelection)
+            input = ((IStructuredSelection)input).getFirstElement();
+        if(!(input instanceof Resource)) {
+            if(input instanceof IAdaptable) {
+                input = ((IAdaptable)input).getAdapter(Resource.class);
+                if(input == null)
+                    return false;
+            }
+            else
+                return false;
+        }
+        Resource resource = (Resource)input;
+        return g.isInstanceOf(resource, TestsResource.getInstance(g).STSTest);
+    }
+    
+    protected void openEditor(Resource input) throws Exception {
+        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
+        if(page == null)
+            return;
+        Simantics.getSession().asyncRequest(new ReadRequest() {
+            @Override
+            public void run(ReadGraph graph) throws DatabaseException {
+                String uri = graph.getURI(input);
+                PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+                    @Override
+                    public void run() {
+                        try {
+                            WorkbenchUtils.openEditor("org.simantics.tests.ui.stsTestEditor", new STSTestEditorInput(uri));
+                        } catch (PartInitException e) {
+                            LOGGER.error("Could not initialize part", e);
+                        }
+                    }
+                });
+            }
+        });
+    }
+
+}
diff --git a/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSEditorInputFactory.java b/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSEditorInputFactory.java
new file mode 100644 (file)
index 0000000..58d05b0
--- /dev/null
@@ -0,0 +1,14 @@
+package org.simantics.tests.modelled.ui;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.ui.IElementFactory;
+import org.eclipse.ui.IMemento;
+
+public class STSEditorInputFactory implements IElementFactory {
+
+    @Override
+    public IAdaptable createElement(IMemento memento) {
+        return new STSTestEditorInput(memento.getTextData());
+    }
+
+}
index cf8fd9c56884e2195e9ed2f36e3a51326a4d8696..21bb5e4d7011bd87b1d6efefb13112cae22623de 100644 (file)
@@ -1,17 +1,8 @@
 package org.simantics.tests.modelled.ui;
 
-import org.simantics.modeling.ui.componentTypeEditor.SCLModuleEditor;
-import org.simantics.scl.ui.editor.SCLSourceViewerConfigurationNew;
+import org.simantics.scl.ui.editor2.SCLModuleEditor2;
+
+public class STSTestEditor extends SCLModuleEditor2 {
 
-public class STSTestEditor extends SCLModuleEditor {
-    
-    
-    
-    @Override
-    protected void preInitialize() {
-        SCLSourceViewerConfigurationNew sourceViewerConfiguration = new SCLSourceViewerConfigurationNew(resourceManager);
-        setDocumentProvider(new STSTestEditorDocumentProvider(sourceViewerConfiguration));
-        setSourceViewerConfiguration(sourceViewerConfiguration);
-    }
 
 }
index 10d7fb21bceccf83a059c64ec79f9b4ce63aaec3..0c6dbc934f5c3456adf29ac8b8853bc4d3447012 100644 (file)
@@ -7,7 +7,6 @@ import org.eclipse.core.runtime.CoreException;
 import org.eclipse.core.runtime.IProgressMonitor;
 import org.eclipse.jface.text.Document;
 import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.source.IAnnotationModel;
 import org.simantics.Simantics;
 import org.simantics.databoard.Bindings;
 import org.simantics.db.ReadGraph;
@@ -23,21 +22,13 @@ import org.simantics.tests.modelled.ontology.TestsResource;
 import org.simantics.ui.workbench.ResourceEditorInput;
 import org.simantics.utils.logging.TimeLogger;
 
+@Deprecated
 public class STSTestEditorDocumentProvider extends SCLModuleEditorDocumentProvider {
 
     public STSTestEditorDocumentProvider(SCLSourceViewerConfigurationNew sourceViewer) {
         super(sourceViewer);
     }
     
-    @Override
-    protected IAnnotationModel createAnnotationModel(Object element) throws CoreException {
-        return null;
-    }
-    
-    @Override
-    protected void updateAnnotations() {
-    }
-    
     @Override
     protected IDocument createDocument(Object element) throws CoreException {
         ResourceEditorInput input = (ResourceEditorInput)element;
diff --git a/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSTestEditorInput.java b/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/STSTestEditorInput.java
new file mode 100644 (file)
index 0000000..d057dac
--- /dev/null
@@ -0,0 +1,134 @@
+package org.simantics.tests.modelled.ui;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+
+import org.eclipse.ui.IPersistableElement;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.UnaryRead;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.scl.compiler.errors.Failable;
+import org.simantics.scl.compiler.module.Module;
+import org.simantics.scl.compiler.module.options.ModuleCompilationOptions;
+import org.simantics.scl.compiler.module.repository.ModuleRepository;
+import org.simantics.scl.compiler.module.repository.UpdateListener;
+import org.simantics.scl.compiler.source.ModuleSource;
+import org.simantics.scl.compiler.source.TextualModuleSource;
+import org.simantics.scl.ui.editor2.StandardSCLModuleEditorInput;
+import org.simantics.tests.modelled.ontology.TestsResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class STSTestEditorInput extends StandardSCLModuleEditorInput  {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(STSTestEditorInput.class);
+    
+    public STSTestEditorInput(String moduleName) {
+        super(moduleName);
+    }
+    
+    @Override
+    public boolean exists() {
+        return true;
+    }
+    
+    @SuppressWarnings("unchecked")
+    @Override
+    public <T> T getAdapter(Class<T> adapter) {
+        if(adapter.equals(ModuleSource.class))
+            try {
+                return (T) Simantics.getSession().syncRequest(new ReadSTSModuleSource(getModuleName()));
+            } catch (DatabaseException e) {
+                e.printStackTrace();
+            }
+        if(adapter.equals(IPersistableElement.class))
+            return (T)this;
+        return null;
+    }
+    
+    
+    private static class STSTextualModuleSource extends TextualModuleSource {
+
+        private String moduleText;
+
+        public STSTextualModuleSource(String stsModuleURI, String moduleText) {
+            super(stsModuleURI);
+            this.moduleText = moduleText;
+        }
+
+        @Override
+        public void update(String newSourceText) {
+            try {
+                Simantics.getSession().syncRequest(new WriteSTSModuleSource(getModuleName(), newSourceText));
+            } catch (DatabaseException e) {
+                LOGGER.error("", e);
+            }
+        }
+        
+        @Override
+        public Failable<Module> compileModule(ModuleRepository environment, UpdateListener listener, ModuleCompilationOptions options) {
+            return super.compileModule(environment, listener, options);
+        }
+        
+        @Override
+        public boolean isUpdateable() {
+            return true;
+        }
+
+        @Override
+        protected Reader getSourceReader(UpdateListener listener) throws IOException {
+            return new StringReader(moduleText);
+        }
+    }
+    
+    static class ReadSTSModuleSource extends UnaryRead<String, ModuleSource> {
+        
+        public ReadSTSModuleSource(String moduleName) {
+            super(moduleName);
+        }
+
+        @Override
+        public ModuleSource perform(ReadGraph graph) throws DatabaseException {
+            Resource moduleResource = graph.getPossibleResource(parameter);
+            if(moduleResource == null)
+                return null;
+            TestsResource TESTS = TestsResource.getInstance(graph);
+            if(!graph.isInstanceOf(moduleResource, TESTS.STSTest))
+                return null;
+            String text = graph.getRelatedValue(moduleResource, TESTS.STSTest_definition);
+            return new STSTextualModuleSource(parameter, text);
+        }
+    }
+    
+    static class WriteSTSModuleSource extends WriteRequest {
+        private final String moduleURI;
+        private final String sourceText;
+        
+        public WriteSTSModuleSource(String moduleURI, String sourceText) {
+            this.moduleURI = moduleURI;
+            this.sourceText = sourceText;
+        }
+
+        @Override
+        public void perform(WriteGraph graph) throws DatabaseException {
+            Resource moduleResource = graph.getPossibleResource(moduleURI);
+            if(moduleResource == null)
+                return;
+            TestsResource TESTS = TestsResource.getInstance(graph);
+            if(!graph.isInstanceOf(moduleResource, TESTS.STSTest))
+                return;
+            graph.claimLiteral(moduleResource, TESTS.STSTest_definition, sourceText);
+        }
+    }
+    
+    @Override
+    public String getFactoryId() {
+        return "org.simantics.tests.modelled.ui.stseditor.inputFactory";
+    }
+
+}
index 569f6fbdc7a6d8df1d11fb63876624cf79f97175..976efa2c2d2a0aab10b40125ed664672c2b4f9d9 100644 (file)
@@ -3,15 +3,13 @@ package org.simantics.tests.modelled.ui;
 import java.io.BufferedReader;
 import java.io.StringReader;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
+import java.util.stream.Collectors;
 
 import org.eclipse.swt.graphics.Image;
 import org.simantics.Simantics;
-import org.simantics.databoard.Bindings;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
 import org.simantics.db.common.request.ReadRequest;
@@ -19,57 +17,49 @@ import org.simantics.db.exception.DatabaseException;
 import org.simantics.layer0.Layer0;
 import org.simantics.scl.compiler.commands.CommandSession;
 import org.simantics.scl.compiler.commands.TestScriptExecutor;
-import org.simantics.scl.compiler.module.Module;
 import org.simantics.scl.compiler.module.coverage.CombinedCoverage;
-import org.simantics.scl.compiler.module.coverage.CoverageBuilder;
-import org.simantics.scl.compiler.module.coverage.CoverageUtils;
 import org.simantics.scl.compiler.module.options.ModuleCompilationOptions;
 import org.simantics.scl.compiler.module.options.ModuleCompilationOptionsAdvisor;
 import org.simantics.scl.compiler.module.repository.ModuleRepository;
-import org.simantics.scl.compiler.runtime.RuntimeModule;
 import org.simantics.scl.osgi.SCLOsgi;
 import org.simantics.scl.runtime.reporting.AbstractSCLReportingHandler;
 import org.simantics.tests.modelled.ontology.TestsResource;
-import org.simantics.utils.strings.AlphanumComparator;
+import org.simantics.tests.modelled.utils.ModelledSTSSuite;
+import org.simantics.tests.modelled.utils.ModelledSTSTest;
+import org.simantics.tests.modelled.utils.STSSuiteTestCollector;
 
 public class STSTestSuiteModel {
 
     static class STSTest {
         
-        private final Resource test;
+        private final ModelledSTSTest test;
+        
         private final STSSuite parent;
-        private final String definition;
-        private final String name;
         private boolean executed = false;
         private long duration;
         private boolean failed = false;
         private boolean isRunning = false;
         private List<String> output = new ArrayList<>();
-        private CombinedCoverage coverage;
-        private int priority;
         
-        public STSTest(Resource test, STSSuite parent, String definition, String name, int executionPrioprity) {
+        public STSTest(ModelledSTSTest test, STSSuite parent) {
             this.test = test;
             this.parent = parent;
-            this.definition = definition;
-            this.name = name;
-            this.priority = executionPrioprity;
         }
         
         public String getName() {
-            return name;
+            return test.getName();
         }
         
         public String getLabel() {
             StringBuilder sb = new StringBuilder();
-            sb.append(name);
+            sb.append(getName());
             if (executed || failed)
                 sb.append(" (").append(duration).append(" ms)");
             return sb.toString();
         }
         
         public String getDefinition() {
-            return definition;
+            return test.getCode();
         }
 
         public STSSuite getParent() {
@@ -79,7 +69,7 @@ public class STSTestSuiteModel {
         public void execute(CommandSession session) {
             isRunning = true;
             
-            TestScriptExecutor executor = new TestScriptExecutor(session, new BufferedReader(new StringReader(definition)), new AbstractSCLReportingHandler() {
+            TestScriptExecutor executor = new TestScriptExecutor(session, new BufferedReader(new StringReader(getDefinition())), new AbstractSCLReportingHandler() {
                 
                 @Override
                 public void print(String text) {
@@ -95,7 +85,7 @@ public class STSTestSuiteModel {
                 public void printError(String error) {
                     appendOutput(error + "\n");
                 }
-            });
+            }, true);
             long start = System.currentTimeMillis();
             try {
                 if (parent != null)
@@ -124,61 +114,56 @@ public class STSTestSuiteModel {
         }
 
         public void setCoverage(CombinedCoverage coverage) {
-            this.coverage = coverage;
+            test.setCoverage(coverage);
         }
         
         public CombinedCoverage getCoverage() {
-            return coverage;
+            return test.getCoverage();
         }
-        
+
+        public int getPriority() {
+            return test.getPriority();
+        }
+
         @Override
         public String toString() {
-            return name + " [priority=" + priority + ", executed=" + executed + ", duration=" + duration + "]";
+            return getName() + " [priority=" + getPriority() + ", executed=" + executed + ", duration=" + duration + "]";
+        }
+
+        public boolean isIgnored() {
+            return test.isIgnored();
         }
     }
 
     static class STSSuite {
-        
-        private List<Pattern> moduleNameFilterPatterns = new ArrayList<>();
-        private final Resource suite;
-        private final String name;
+
+        private ModelledSTSSuite suite;
         private STSTest[] children;
         private int startedCount;
         private int errorCount;
         private int failureCount;
-        private CoverageBuilder coverageBuilder;
+        public int ignoredCount;
         
-        public STSSuite(Resource suite, String name, String moduleNameFilter) {
+        public STSSuite(ModelledSTSSuite suite) {
             this.suite = suite;
-            this.name = name;
-            for (String s : moduleNameFilter.split(",")) {
-                try {
-                    s = s.trim().replaceAll("\\*", "\\\\w*").toLowerCase();
-                    moduleNameFilterPatterns.add(Pattern.compile(s));
-                } catch (PatternSyntaxException e) {
-                    e.printStackTrace();
-                }
-            }
-        }
-
-        public void children(STSTest[] children) {
-            this.children = children;
         }
 
         public STSTest[] getChildren() {
+            if (children == null)
+                children = suite.getSortedChildren().stream().map(modelledTest  -> new STSTest(modelledTest, this)).collect(Collectors.toList()).toArray(new STSTest[suite.getChildren().size()]);
             return children;
         }
 
         public String getName() {
-            return name;
+            return suite.getName();
         }
 
         public String getLabel() {
             StringBuilder sb = new StringBuilder();
-            sb.append(name);
+            sb.append(getName());
             long totalTime = 0; 
-            if (children != null) {
-                for (STSTest test : children) {
+            if (getChildren() != null) {
+                for (STSTest test : getChildren()) {
                     if (test.executed || test.failed) {
                         totalTime += test.duration;
                     }
@@ -190,56 +175,40 @@ public class STSTestSuiteModel {
         }
 
         public boolean isRunning() {
-            boolean running = false;
-            if (children != null) {
-                for (STSTest test: children) {
+            if (getChildren() != null) {
+                for (STSTest test: getChildren()) {
                     if (test.isRunning) {
-                        running = true;
-                        break;
+                        return true;
                     }
                 }
             }
-            return running;
+            return false;
         }
 
         public boolean executed() {
-            boolean executed = true;
-            if (children != null) {
-                for (STSTest test: children) {
+            if (getChildren() != null) {
+                for (STSTest test: getChildren()) {
                     if (!test.executed) {
-                        executed = false;
-                        break;
+                        return false;
                     }
                 }
             }
-            return executed;
+            return true;
         }
 
         public boolean failed() {
-            boolean failed = false;
-            if (children != null) {
-                for (STSTest test: children) {
+            if (getChildren() != null) {
+                for (STSTest test: getChildren()) {
                     if (test.failed) {
-                        failed = true;
-                        break;
+                        return true;
                     }
                 }
             }
-            return failed;
-        }
-        
-        public void addCoverage(List<Module> modules) {
-            if (coverageBuilder == null) {
-                coverageBuilder = new CoverageBuilder();
-            }
-            for (Module module : modules)
-                coverageBuilder.addCoverage(module, true);
+            return false;
         }
 
         public CombinedCoverage getCoverage() {
-            if (coverageBuilder == null)
-                return null;
-            return coverageBuilder.getCoverage();
+            return suite.getCoverage();
         }
     }
 
@@ -276,7 +245,7 @@ public class STSTestSuiteModel {
                 @Override
                 public ModuleCompilationOptions getOptions(String moduleName) {
                     boolean coverage = false;
-                    for (Pattern p : suite.moduleNameFilterPatterns) {
+                    for (Pattern p : suite.suite.getModuleNameFilterPatterns()) {
                         if (p.matcher(moduleName.toLowerCase()).find()) {
                             coverage = true;
                             break;
@@ -301,45 +270,23 @@ public class STSTestSuiteModel {
     }
     
     private void executeSuite(CommandSession session) {
-        
         for (STSTest test : suite.getChildren()) {
-            test.execute(session);
-            
-            Collection<RuntimeModule> runtimeModules = session.getRuntimeEnvironment().getRuntimeModules();
-            List<Module> modules = new ArrayList<>(runtimeModules.size());
-            for (RuntimeModule module : runtimeModules) {
-                for (Pattern p : suite.moduleNameFilterPatterns) {
-                    if (p.matcher(module.getModule().getName().toLowerCase()).find()) {
-                        modules.add(module.getModule());
-                    }
-                }
+            if (test.isIgnored()) {
+                testExecuted();
+                test.getParent().ignoredCount++;
+                continue;
             }
-            test.setCoverage(CoverageUtils.getCoverage(modules));
-            suite.addCoverage(modules);
-            
-            CoverageUtils.resetCoverage(modules);
-            
+            test.execute(session);
+            STSSuiteTestCollector.setSuiteCoverage(test.test, suite.suite, session);
             testExecuted();
         }
-
     }
-    
+
     private void executeTest(CommandSession session) {
-        
         test.execute(session);
         testExecuted();
-        
-        Collection<RuntimeModule> runtimeModules = session.getRuntimeEnvironment().getRuntimeModules();
-        List<Module> modules = new ArrayList<>(runtimeModules.size());
-        for (RuntimeModule module : runtimeModules) {
-            modules.add(module.getModule());
-        }
-        test.setCoverage(CoverageUtils.getCoverage(modules));
-        
-        CoverageUtils.resetCoverage(modules);
-
+        STSSuiteTestCollector.setTestCoverage(test.test, session);
     }
-    
 
     public boolean hasChildren(Object element) {
         if (element instanceof STSTest) {
@@ -418,29 +365,13 @@ public class STSTestSuiteModel {
                     Layer0 L0 = Layer0.getInstance(graph);
                     TestsResource TESTS = TestsResource.getInstance(graph);
                     if (graph.isInstanceOf(root, TESTS.STSTest)) {
-                        String testName = graph.getRelatedValue2(root, L0.HasName, Bindings.STRING);
-                        String definition = graph.getRelatedValue2(root, TESTS.STSTest_definition, Bindings.STRING);
-                        Integer executionPrioprity = graph.getRelatedValue2(root, TESTS.STSTest_executionPriority, Bindings.INTEGER);
-                        test = new STSTest(root, null, definition, testName, executionPrioprity);
+                        test = new STSTest(STSSuiteTestCollector.toModelledTest(graph, root), null);
                     } else if (graph.isInstanceOf(root, TESTS.STSSuite)) {
-                        String suiteName = graph.getRelatedValue2(root, L0.HasName, Bindings.STRING);
-                        String moduleNameFilter = graph.getPossibleRelatedValue2(root, TESTS.STSSuite_moduleNameFilter, Bindings.STRING);
-                        suite = new STSSuite(root, suiteName, moduleNameFilter);
-                        List<STSTest> tests = new ArrayList<>();
-                        for (Resource test : graph.getObjects(root, L0.ConsistsOf)) {
-                            String testName = graph.getRelatedValue2(test, L0.HasName, Bindings.STRING);
-                            String definition = graph.getRelatedValue2(test, TESTS.STSTest_definition, Bindings.STRING);
-                            Integer executionPrioprity = graph.getRelatedValue2(test, TESTS.STSTest_executionPriority, Bindings.INTEGER);
-                            tests.add(new STSTest(test, suite, definition, testName, executionPrioprity));
-                        }
-                        Collections.sort(tests, (o1, o2) -> {
-                            if (o1.priority < o2.priority)
-                                return -1;
-                            else if (o1.priority > o2.priority)
-                                return 1;
-                            else return AlphanumComparator.COMPARATOR.compare(o1.name, o2.name);
-                        });
-                        suite.children(tests.toArray(new STSTest[tests.size()]));
+                        List<ModelledSTSTest> tests = new ArrayList<>();
+                        for (Resource test : graph.getObjects(root, L0.ConsistsOf))
+                            tests.add(STSSuiteTestCollector.toModelledTest(graph, test));
+                        
+                        suite = new STSSuite(STSSuiteTestCollector.toModelledSuite(graph, root, tests));
                     } else {
                         throw new IllegalArgumentException(root.toString());
                     }
@@ -467,6 +398,8 @@ public class STSTestSuiteModel {
     }
 
     public int getIgnoredCount() {
+        if (suite != null)
+            return suite.ignoredCount;
         return 0;
     }
 
diff --git a/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/adapters/IsTestIgnored.java b/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/adapters/IsTestIgnored.java
new file mode 100644 (file)
index 0000000..a58f3b3
--- /dev/null
@@ -0,0 +1,44 @@
+package org.simantics.tests.modelled.ui.adapters;
+
+import java.util.Map;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.simantics.browsing.ui.model.images.ImageRule;
+import org.simantics.browsing.ui.model.tests.Test;
+import org.simantics.browsing.ui.model.visuals.VisualsRule;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.tests.modelled.ontology.TestsResource;
+
+public enum IsTestIgnored implements Test, VisualsRule, ImageRule {
+
+    INSTANCE;
+
+    public static IsTestIgnored get() {
+        return INSTANCE;
+    }
+
+    @Override
+    public boolean isCompatible(Class<?> contentType) {
+        return Resource.class.equals(contentType);
+    }
+
+    @Override
+    public boolean test(ReadGraph graph, Object content) throws DatabaseException {
+        if (content instanceof Resource) {
+            Resource resource = (Resource) content;
+            TestsResource TESTS = TestsResource.getInstance(graph);
+            return graph.getPossibleRelatedValue2(resource, TESTS.ignore, Bindings.BOOLEAN);
+        }
+        return false;
+    }
+
+    @Override
+    public Map<String, ImageDescriptor> getImage(ReadGraph graph, Object content) throws DatabaseException {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+}
diff --git a/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/rules/TestImageRule.java b/bundles/org.simantics.tests.modelled.ui/src/org/simantics/tests/modelled/ui/rules/TestImageRule.java
new file mode 100644 (file)
index 0000000..a405ad5
--- /dev/null
@@ -0,0 +1,42 @@
+package org.simantics.tests.modelled.ui.rules;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.simantics.browsing.ui.common.ColumnKeys;
+import org.simantics.browsing.ui.model.images.ImageRule;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.tests.modelled.ontology.TestsResource;
+import org.simantics.tests.modelled.ui.ontology.TestsUIResource;
+
+public class TestImageRule implements ImageRule {
+
+    private ImageDescriptor testImage;
+    private ImageDescriptor testIgnoredImage;
+
+    public TestImageRule(ReadGraph graph) throws DatabaseException {
+        TestsUIResource TESTS = TestsUIResource.getInstance(graph);
+        testImage = graph.adapt(TESTS.testImage, ImageDescriptor.class);
+        testIgnoredImage = graph.adapt(TESTS.testIgnoredImage, ImageDescriptor.class);
+    }
+
+    @Override
+    public boolean isCompatible(Class<?> contentType) {
+        return Resource.class.equals(contentType);
+    }
+
+    @Override
+    public Map<String, ImageDescriptor> getImage(ReadGraph graph, Object content) throws DatabaseException {
+        Resource resource = (Resource) content;
+        Boolean ignored = graph.getPossibleRelatedValue2(resource, TestsResource.getInstance(graph).ignore,
+                Bindings.BOOLEAN);
+        if (ignored != null && ignored)
+            return Collections.singletonMap(ColumnKeys.SINGLE, testIgnoredImage);
+        return Collections.singletonMap(ColumnKeys.SINGLE, testImage);
+    }
+
+}
index 042896151d58bcaeca3173384a42776eb85f8931..8f182947930bb09a6d637bf373bc9e0bdc1d8fc3 100644 (file)
@@ -8,9 +8,13 @@ Require-Bundle: org.simantics.tests.modelled.ontology,
  org.simantics.scl.osgi,
  org.simantics,
  org.junit,
- org.simantics.modeling;bundle-version="1.1.1"
+ org.simantics.modeling;bundle-version="1.1.1",
+ org.slf4j.api,
+ org.simantics.db.testing
 Bundle-RequiredExecutionEnvironment: JavaSE-1.8
 Bundle-ActivationPolicy: lazy
 Export-Package: org.simantics.tests.modelled,
- org.simantics.tests.modelled.junit
+ org.simantics.tests.modelled.junit,
+ org.simantics.tests.modelled.junit.v2,
+ org.simantics.tests.modelled.utils
 Bundle-Vendor: Semantum Oy
diff --git a/bundles/org.simantics.tests.modelled/adapters.xml b/bundles/org.simantics.tests.modelled/adapters.xml
new file mode 100644 (file)
index 0000000..5db4149
--- /dev/null
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+    Copyright (c) 2007, 2010 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 - issue #4190
+ -->
+<adapters>
+       <target
+               interface="org.simantics.db.layer0.adapter.PasteHandler">
+               <type
+                       uri="http://www.simantics.org/Tests-1.0/STSTest"
+                       class="org.simantics.db.layer0.adapter.impl.DefaultPasteHandler">
+                       <this />
+               </type>
+               <type
+                       uri="http://www.simantics.org/Tests-1.0/STSSuite"
+                       class="org.simantics.db.layer0.adapter.impl.DefaultPasteHandler">
+                       <this />
+               </type>
+       </target>
+</adapters>
index d7919bc506f1e662d06eda4b7a99d0f234efeedd..5b7d10cf2bd9c26bd216208986d9094a12677612 100644 (file)
@@ -2,5 +2,6 @@ source.. = src/
 output.. = bin/
 bin.includes = META-INF/,\
                .,\
-               scl/
+               scl/,\
+               adapters.xml
 src.includes = scl/
index 2311409f8f236699b47834d57d83d1f9ccf598dc..fe7d82f69795cce58f85d862b4f4d60fd93fc5b2 100644 (file)
@@ -8,6 +8,7 @@ import org.junit.runner.notification.RunListener;
 import org.junit.runner.notification.RunNotifier;
 import org.junit.runners.ParentRunner;
 
+@Deprecated
 public abstract class RuntimeSTSRunner<T extends Runner> extends ParentRunner<T> {
 
     public RuntimeSTSRunner(Class<?> testClass) throws Exception {
index 2acc58a794b818242234b6e4ad61c9cd0706ba5f..90abe0e1661d2ef29fe441a09088c2eb8b02baf4 100644 (file)
@@ -8,6 +8,7 @@ import org.junit.runner.Description;
 import org.simantics.scl.compiler.commands.CommandSession;
 import org.simantics.scl.osgi.SCLOsgi;
 
+@Deprecated
 public class RuntimeSTSSuiteRunner extends RuntimeSTSRunner<RuntimeSTSTestRunner> {
 
     private final List<RuntimeSTSTestRunner> children = new ArrayList<>();
@@ -35,6 +36,12 @@ public class RuntimeSTSSuiteRunner extends RuntimeSTSRunner<RuntimeSTSTestRunner
         testChildren.forEach(c -> c.setCommandSession(session));
         children.addAll(testChildren);
     }
+    
+    @Override
+    protected boolean isIgnored(RuntimeSTSTestRunner child) {
+        // TODO Auto-generated method stub
+        return super.isIgnored(child);
+    }
 
     @Override
     public List<RuntimeSTSTestRunner> getChildren() {
@@ -44,7 +51,7 @@ public class RuntimeSTSSuiteRunner extends RuntimeSTSRunner<RuntimeSTSTestRunner
     @Override
     public void initialize() throws Exception {
     }
-
+    
     @Override
     public void deinitialize() throws Exception {
     }
index 48c3f4fe7929b1a663cfab4f8518522622181194..a30462d3f4725d769bee3deb0d3992bae10c81d2 100644 (file)
@@ -13,6 +13,7 @@ import org.simantics.scl.osgi.SCLOsgi;
 import org.simantics.scl.runtime.SCLContext;
 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
 
+@Deprecated
 public class RuntimeSTSTestRunner extends Runner {
     
     private final String name;
index 3cdc981b767bf6762eefaf45e98b95be0d05780d..733cea952025c0ad2122dbf4621f25891d77a85d 100644 (file)
@@ -19,9 +19,13 @@ import org.simantics.modeling.ModelingUtils;
 import org.simantics.scl.runtime.tuple.Tuple0;
 import org.simantics.tests.modelled.ontology.TestsResource;
 import org.simantics.utils.strings.AlphanumComparator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
+@Deprecated
 public class RuntimeTestCollector {
 
+    private static final Logger LOGGER = LoggerFactory.getLogger(RuntimeTestCollector.class);
     
     /**
      * TODO: The idea of this class was to collect all the tests from shared libraries and construct
@@ -36,11 +40,14 @@ public class RuntimeTestCollector {
                 public Collection<RuntimeSTSSuiteRunner> perform(ReadGraph graph) throws DatabaseException {
                     
                     List<Resource> sharedOntologies = Simantics.applySCL("Simantics/SharedOntologies", "getSharedOntologies", graph, Tuple0.INSTANCE);
-
+                    if (LOGGER.isInfoEnabled())
+                        LOGGER.info("Found {} shared ontologies from graph",  sharedOntologies.size());
                     Set<RuntimeSTSSuiteRunner> suites = new HashSet<>();
                     TestsResource TESTS = TestsResource.getInstance(graph);
                     Layer0 L0 = Layer0.getInstance(graph);
                     for (Resource sharedOntology : sharedOntologies) {
+                        if (LOGGER.isInfoEnabled())
+                            LOGGER.info("Searching {} for modelled tests", graph.getURI(sharedOntology));
                         List<Resource> stsSuites = ModelingUtils.searchByType(graph, sharedOntology, TESTS.STSSuite);
                         for (Resource stsSuite : stsSuites) {
                             try {
diff --git a/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSRunner.java b/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSRunner.java
new file mode 100644 (file)
index 0000000..c74f6ef
--- /dev/null
@@ -0,0 +1,81 @@
+package org.simantics.tests.modelled.junit.v2;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.junit.runner.Description;
+import org.junit.runner.Result;
+import org.junit.runner.notification.RunListener;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.ParentRunner;
+import org.junit.runners.model.InitializationError;
+import org.simantics.Simantics;
+import org.simantics.db.testing.common.AcornTests;
+import org.simantics.scl.compiler.commands.CommandSession;
+import org.simantics.scl.osgi.SCLOsgi;
+import org.simantics.tests.modelled.utils.STSSuiteTestCollector;
+
+public class ModelledSTSRunner extends ParentRunner<ModelledSTSSuiteRunner> {
+
+    private CommandSession commandSession;
+
+    public ModelledSTSRunner(Class<?> testClass) throws Exception {
+        super(testClass);
+        initialize0();
+    }
+
+    @Override
+    protected List<ModelledSTSSuiteRunner> getChildren() {
+        return STSSuiteTestCollector.collectTests().stream().map(suite -> {
+            try {
+                return new ModelledSTSSuiteRunner(suite);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }).collect(Collectors.toList());
+    }
+
+    @Override
+    protected Description describeChild(ModelledSTSSuiteRunner child) {
+        return child.getDescription();
+    }
+
+    @Override
+    public void run(RunNotifier notifier) {
+        notifier.addListener(new RunListener() {
+
+            @Override
+            public void testRunFinished(Result result) throws Exception {
+                deinitialize0();
+            }
+        });
+        super.run(notifier);
+    }
+
+    @Override
+    protected void runChild(ModelledSTSSuiteRunner child, RunNotifier notifier) {
+        child.setCommandSesssion(commandSession);
+        child.run(notifier);
+        // TODO: Add coverage reporting to ModelledSTSRunner
+//        CombinedCoverage cover = child.getCoverage();
+//        CoverageBuilder b = new CoverageBuilder();
+    }
+
+    public void initialize() throws InitializationError {
+    }
+
+    public void deinitialize() throws Exception {
+    }
+
+    private void initialize0() throws Exception {
+        AcornTests.newSimanticsWorkspace(null, null);
+        this.commandSession = new CommandSession(SCLOsgi.MODULE_REPOSITORY, null);
+        initialize();
+    }
+
+    private void deinitialize0() throws Exception {
+        deinitialize();
+        Simantics.shutdown(new NullProgressMonitor());
+    }
+}
diff --git a/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSSuiteRunner.java b/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSSuiteRunner.java
new file mode 100644 (file)
index 0000000..a568976
--- /dev/null
@@ -0,0 +1,77 @@
+package org.simantics.tests.modelled.junit.v2;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.junit.runner.Description;
+import org.junit.runner.notification.Failure;
+import org.junit.runner.notification.RunNotifier;
+import org.junit.runners.ParentRunner;
+import org.simantics.scl.compiler.commands.CommandSession;
+import org.simantics.scl.compiler.module.coverage.CombinedCoverage;
+import org.simantics.scl.osgi.SCLOsgi;
+import org.simantics.tests.modelled.utils.ModelledSTSSuite;
+import org.simantics.tests.modelled.utils.STSSuiteTestCollector;
+
+public class ModelledSTSSuiteRunner extends ParentRunner<ModelledSTSTestRunner> {
+
+    private final ModelledSTSSuite suite;
+    private CommandSession commandSession;
+
+    public ModelledSTSSuiteRunner(ModelledSTSSuite suite) throws Exception {
+        super(ModelledSTSSuiteRunner.class);
+        this.suite = suite;
+    }
+
+    @Override
+    protected String getName() {
+        return suite.getName();
+    }
+
+    @Override
+    protected List<ModelledSTSTestRunner> getChildren() {
+        return suite.getChildren().stream().map(test -> new ModelledSTSTestRunner(test)).collect(Collectors.toList());
+    }
+
+    @Override
+    protected Description describeChild(ModelledSTSTestRunner child) {
+        return child.getDescription();
+    }
+
+    @Override
+    protected void runChild(ModelledSTSTestRunner child, RunNotifier notifier) {
+        Description description = describeChild(child);
+        if (isIgnored(child)) {
+            notifier.fireTestIgnored(description);
+        } else {
+            notifier.fireTestStarted(description);
+            try {
+                child.run(getCommandSession());
+                notifier.fireTestFinished(description);
+                STSSuiteTestCollector.setSuiteCoverage(child.getTest(), suite, getCommandSession());
+            } catch (Throwable e) {
+                notifier.fireTestFailure(new Failure(description, e));
+            }
+        }
+    }
+
+    @Override
+    protected boolean isIgnored(ModelledSTSTestRunner child) {
+        return child.isIgnored();
+    }
+
+    public void setCommandSesssion(CommandSession commandSession) {
+        this.commandSession = commandSession;
+    }
+
+    public CommandSession getCommandSession() {
+        if (commandSession == null)
+            commandSession = new CommandSession(SCLOsgi.MODULE_REPOSITORY, null);
+        return commandSession;
+    }
+
+    public CombinedCoverage getCoverage() {
+        return suite.getCoverage();
+    }
+
+}
diff --git a/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSTestRunner.java b/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/junit/v2/ModelledSTSTestRunner.java
new file mode 100644 (file)
index 0000000..a2acbfc
--- /dev/null
@@ -0,0 +1,74 @@
+package org.simantics.tests.modelled.junit.v2;
+
+import java.io.BufferedReader;
+import java.io.StringReader;
+
+import org.junit.runner.Description;
+import org.junit.runner.Runner;
+import org.junit.runner.notification.RunNotifier;
+import org.simantics.scl.compiler.commands.CommandSession;
+import org.simantics.scl.compiler.commands.TestScriptExecutor;
+import org.simantics.scl.osgi.SCLOsgi;
+import org.simantics.scl.runtime.SCLContext;
+import org.simantics.scl.runtime.reporting.SCLReportingHandler;
+import org.simantics.tests.modelled.utils.ModelledSTSTest;
+import org.simantics.tests.modelled.utils.STSSuiteTestCollector;
+
+public class ModelledSTSTestRunner extends Runner {
+
+    private Description description;
+    private ModelledSTSTest test;
+
+    public ModelledSTSTestRunner(ModelledSTSTest test) {
+        this.test = test;
+    }
+
+    public String getName() {
+        return test.getName();
+    }
+
+    @Override
+    public Description getDescription() {
+        if (description == null)
+            description = Description.createTestDescription(ModelledSTSTestRunner.class, getName());
+        return description;
+    }
+
+    /**
+     * This method is called from ModelledSTSSuite (ParentRunner) with the same
+     * CommandSession
+     * 
+     * @param session
+     */
+    public void run(CommandSession session) {
+        try (BufferedReader reader = new BufferedReader(new StringReader(test.getCode()))) {
+            SCLReportingHandler handler = (SCLReportingHandler) SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
+            new TestScriptExecutor(session, reader, handler, true).execute();
+            STSSuiteTestCollector.setTestCoverage(test, session);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public void run(RunNotifier notifier) {
+        notifier.fireTestStarted(getDescription());
+        try {
+            run(new CommandSession(SCLOsgi.MODULE_REPOSITORY, null));
+        } finally {
+            notifier.fireTestFinished(getDescription());
+        }
+    }
+
+    public boolean isIgnored() {
+        return test.isIgnored();
+    }
+
+    public int getPriority() {
+        return test.getPriority();
+    }
+
+    public ModelledSTSTest getTest() {
+        return test;
+    }
+}
diff --git a/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/ModelledSTSSuite.java b/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/ModelledSTSSuite.java
new file mode 100644 (file)
index 0000000..b856787
--- /dev/null
@@ -0,0 +1,79 @@
+package org.simantics.tests.modelled.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+import java.util.stream.Collectors;
+
+import org.simantics.scl.compiler.module.Module;
+import org.simantics.scl.compiler.module.coverage.CombinedCoverage;
+import org.simantics.scl.compiler.module.coverage.CoverageBuilder;
+import org.simantics.utils.strings.AlphanumComparator;
+
+public class ModelledSTSSuite {
+
+    private String name;
+    private List<ModelledSTSTest> children;
+    private String moduleNameFilter;
+    private List<Pattern> moduleNameFilterPatterns = new ArrayList<>();
+
+    private CoverageBuilder coverageBuilder;
+
+    ModelledSTSSuite(String name, List<ModelledSTSTest> children, String moduleNameFilter) {
+        this.name = name;
+        this.children = children;
+        this.moduleNameFilter = moduleNameFilter;
+        for (String s : moduleNameFilter.split(",")) {
+            try {
+                s = s.trim().replaceAll("\\*", "\\\\w*").toLowerCase();
+                getModuleNameFilterPatterns().add(Pattern.compile(s));
+            } catch (PatternSyntaxException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public List<ModelledSTSTest> getChildren() {
+        return children;
+    }
+
+    public List<ModelledSTSTest> getSortedChildren() {
+        return new ArrayList<>(children).stream().sorted(ModelledSTSSuite::compareTests).collect(Collectors.toList());
+    }
+
+    private static int compareTests(ModelledSTSTest test1, ModelledSTSTest test2) {
+        if (test1.getPriority() < test2.getPriority())
+            return -1;
+        else if (test1.getPriority() > test2.getPriority())
+            return 1;
+        else
+            return AlphanumComparator.COMPARATOR.compare(test1.getName(), test2.getName());
+    }
+
+    public String getModuleNameFilter() {
+        return moduleNameFilter;
+    }
+
+    public void addCoverage(List<Module> modules) {
+        if (coverageBuilder == null)
+            coverageBuilder = new CoverageBuilder();
+        for (Module module : modules)
+            coverageBuilder.addCoverage(module, true);
+    }
+
+    public CombinedCoverage getCoverage() {
+        if (coverageBuilder == null)
+            return null;
+        return coverageBuilder.getCoverage();
+    }
+
+    public List<Pattern> getModuleNameFilterPatterns() {
+        return moduleNameFilterPatterns;
+    }
+
+}
diff --git a/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/ModelledSTSTest.java b/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/ModelledSTSTest.java
new file mode 100644 (file)
index 0000000..00d825d
--- /dev/null
@@ -0,0 +1,44 @@
+package org.simantics.tests.modelled.utils;
+
+import org.simantics.scl.compiler.module.coverage.CombinedCoverage;
+
+public class ModelledSTSTest {
+
+    private final String name;
+    private final String code;
+    private final int priority;
+    private final boolean ignored;
+
+    private CombinedCoverage coverage;
+
+    ModelledSTSTest(String name, String code, int priority, boolean ignored) {
+        this.name = name;
+        this.code = code;
+        this.priority = priority;
+        this.ignored = ignored;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public int getPriority() {
+        return priority;
+    }
+
+    public boolean isIgnored() {
+        return ignored;
+    }
+
+    public void setCoverage(CombinedCoverage coverage) {
+        this.coverage = coverage;
+    }
+
+    public CombinedCoverage getCoverage() {
+        return coverage;
+    }
+}
diff --git a/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/STSSuiteTestCollector.java b/bundles/org.simantics.tests.modelled/src/org/simantics/tests/modelled/utils/STSSuiteTestCollector.java
new file mode 100644 (file)
index 0000000..10530e1
--- /dev/null
@@ -0,0 +1,125 @@
+package org.simantics.tests.modelled.utils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.request.UniqueRead;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingUtils;
+import org.simantics.scl.compiler.commands.CommandSession;
+import org.simantics.scl.compiler.module.Module;
+import org.simantics.scl.compiler.module.coverage.CoverageUtils;
+import org.simantics.scl.compiler.runtime.RuntimeModule;
+import org.simantics.scl.runtime.tuple.Tuple0;
+import org.simantics.tests.modelled.ontology.TestsResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class STSSuiteTestCollector {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(STSSuiteTestCollector.class);
+    
+    /**
+     * TODO: The idea of this class was to collect all the tests from shared libraries and construct
+     * JUnit tests out of them programmatically and then run them with JUnit to get results
+     * 
+     */
+    private static Collection<ModelledSTSSuite> collectTestsFromGraph() {
+        try {
+            Collection<ModelledSTSSuite> suitess = Simantics.getSession().syncRequest(new UniqueRead<Collection<ModelledSTSSuite>>() {
+
+                @Override
+                public Collection<ModelledSTSSuite> perform(ReadGraph graph) throws DatabaseException {
+                    
+                    List<Resource> sharedOntologies = Simantics.applySCL("Simantics/SharedOntologies", "getSharedOntologies", graph, Tuple0.INSTANCE);
+                    if (LOGGER.isInfoEnabled())
+                        LOGGER.info("Found {} shared ontologies from graph",  sharedOntologies.size());
+                    Collection<ModelledSTSSuite> suites = new HashSet<>();
+                    TestsResource TESTS = TestsResource.getInstance(graph);
+                    Layer0 L0 = Layer0.getInstance(graph);
+                    for (Resource sharedOntology : sharedOntologies) {
+                        if (LOGGER.isInfoEnabled())
+                            LOGGER.info("Searching {} for modelled tests", graph.getURI(sharedOntology));
+                        List<Resource> stsSuites = ModelingUtils.searchByType(graph, sharedOntology, TESTS.STSSuite);
+                        for (Resource stsSuite : stsSuites) {
+                            try {
+                                Collection<Resource> tests = graph.syncRequest(new ObjectsWithType(stsSuite, L0.ConsistsOf, TESTS.STSTest));
+                                if (tests.isEmpty())
+                                    continue;
+    
+                                List<ModelledSTSTest> testRunners = new ArrayList<>(tests.size());
+                                for (Resource test : tests)
+                                    testRunners.add(toModelledTest(graph, test));
+
+                                suites.add(toModelledSuite(graph, stsSuite, testRunners));
+                            } catch (Exception e) {
+                                LOGGER.error("", e);
+                            }
+                        }
+                    }
+                    return suites;
+                }
+            });
+            return suitess;
+        } catch (DatabaseException e) {
+            LOGGER.error("Could not find modelled tests", e);
+            return Collections.emptyList();
+        }
+    }
+    
+
+    public static ModelledSTSTest toModelledTest(ReadGraph graph, Resource test) throws DatabaseException {
+        TestsResource TESTS = TestsResource.getInstance(graph);
+        String testName = graph.getRelatedValue(test, Layer0.getInstance(graph).HasName, Bindings.STRING);
+        String code = graph.getRelatedValue(test, TESTS.STSTest_definition, Bindings.STRING);
+        Integer priority = graph.getPossibleRelatedValue(test, TESTS.STSTest_executionPriority, Bindings.INTEGER);
+        Boolean ignored = graph.getPossibleRelatedValue(test, TESTS.ignore, Bindings.BOOLEAN);
+        return new ModelledSTSTest(testName, code, priority != null ? priority : -1, ignored != null ? ignored : false);
+    }
+
+    public static ModelledSTSSuite toModelledSuite(ReadGraph graph, Resource suite, List<ModelledSTSTest> children) throws DatabaseException {
+        TestsResource TESTS = TestsResource.getInstance(graph);
+        String suiteName = graph.getURI(suite);
+        String moduleNameFilter = graph.getPossibleRelatedValue2(suite, TESTS.STSSuite_moduleNameFilter, Bindings.STRING);
+        return new ModelledSTSSuite(suiteName, children, moduleNameFilter);
+    }
+
+    public static void setTestCoverage(ModelledSTSTest test, CommandSession session) {
+        Collection<RuntimeModule> runtimeModules = session.getRuntimeEnvironment().getRuntimeModules();
+        List<Module> modules = new ArrayList<>(runtimeModules.size());
+        for (RuntimeModule module : runtimeModules)
+            modules.add(module.getModule());
+        test.setCoverage(CoverageUtils.getCoverage(modules));
+        CoverageUtils.resetCoverage(modules);
+    }
+    
+    public static List<ModelledSTSSuite> collectTests() {
+        return new ArrayList<>(collectTestsFromGraph());
+    }
+
+
+    public static void setSuiteCoverage(ModelledSTSTest test, ModelledSTSSuite suite, CommandSession session) {
+        Collection<RuntimeModule> runtimeModules = session.getRuntimeEnvironment().getRuntimeModules();
+        List<Module> modules = new ArrayList<>(runtimeModules.size());
+        for (RuntimeModule module : runtimeModules) {
+            for (Pattern p : suite.getModuleNameFilterPatterns()) {
+                if (p.matcher(module.getModule().getName().toLowerCase()).find()) {
+                    modules.add(module.getModule());
+                }
+            }
+        }
+        test.setCoverage(CoverageUtils.getCoverage(modules));
+        suite.addCoverage(modules);
+        CoverageUtils.resetCoverage(modules);
+    }
+}
index beafd6ec71f61ea68e172b949025d296be6cb474..bc89d553cc37edc4e20dab908884eec8c43d03b2 100644 (file)
                <module>org.simantics.scenegraph.ui</module>
                <module>org.simantics.scl.commands</module>
                <module>org.simantics.scl.compiler</module>
-               <module>org.simantics.scl.compiler.dummy</module>
                <module>org.simantics.scl.data</module>
                <module>org.simantics.scl.db</module>
                <module>org.simantics.scl.expressions</module>
                <module>org.simantics.scl.reflection</module>
                <module>org.simantics.scl.runtime</module>
                <module>org.simantics.scl.ui</module>
-               <module>org.simantics.scl.ui.editor</module>
                <module>org.simantics.selectionview</module>
                <module>org.simantics.selectionview.ontology</module>
                <module>org.simantics.selectionview.ui.ontology</module>
index 39291c7d6a2ee2361412190f8a988d7524b201b8..bedbde323266e2b4af27c608f0e260bab47f0871 100644 (file)
@@ -160,11 +160,4 @@ This Agreement is governed by the laws of the State of New York and the intellec
          version="0.0.0"
          unpack="false"/>
 
-   <plugin
-         id="org.simantics.scl.ui.editor"
-         download-size="0"
-         install-size="0"
-         version="0.0.0"
-         unpack="false"/>
-
 </feature>
index 1ddb061405163c96262a047cefb98a335290adce..5c8f6fd1d9d236980f96d055fb245ae923a56d7c 100644 (file)
@@ -143,20 +143,6 @@ This Agreement is governed by the laws of the State of New York and the intellec
          version="0.0.0"
          unpack="false"/>
 
-   <plugin
-         id="org.simantics.scl.compiler.dummy"
-         download-size="0"
-         install-size="0"
-         version="0.0.0"
-         unpack="false"/>
-
-   <plugin
-         id="org.simantics.scl.ui.editor"
-         download-size="0"
-         install-size="0"
-         version="0.0.0"
-         unpack="false"/>
-
    <plugin
          id="org.simantics.scl.db"
          download-size="0"
index bb8f0a8d856976079e09ad34e249d1720d771600..6c8e61413792675497b4d46bbc4771270d99b1b9 100644 (file)
          version="0.0.0"
          unpack="false"/>
 
+   <plugin
+         id="org.slf4j.api"
+         download-size="0"
+         install-size="0"
+         version="0.0.0"
+         unpack="false"/>
+
+   <plugin
+         id="ch.qos.logback.classic"
+         download-size="0"
+         install-size="0"
+         version="0.0.0"
+         unpack="false"/>
+
+   <plugin
+         id="org.simantics.db.testing"
+         download-size="0"
+         install-size="0"
+         version="0.0.0"
+         unpack="false"/>
+
 </feature>
index b8d6a714fdbbc7e13a4576976caa0cb01a6f1042..50989e45f24989b9b3655b770e4007a5f152a6fd 100644 (file)
                                     <id>com.koloboke:koloboke-impl-common-jdk8:1.0.0</id>
                                     <source>true</source>
                                 </artifact>
+                                <artifact>
+                                    <id>com.esotericsoftware:kryo:4.0.0</id>
+                                    <source>true</source>
+                                </artifact>
                             </artifacts>
                         </configuration>
                     </execution>
index d8425c09e52b2372f2887bd73cb14d3f2a724dd3..db7cb6e76df752e941c8f3852ce7df71a1a92401 100644 (file)
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<?pde version="3.8"?><target name="Eclipse Mars.2" sequenceNumber="224">
+<?pde version="3.8"?><target name="Eclipse Mars.2" sequenceNumber="228">
 <locations>
 <location includeAllPlatforms="true" includeConfigurePhase="false" includeMode="slicer" includeSource="true" type="InstallableUnit">
 <unit id="org.objectweb.asm.xml.source" version="5.0.1.v201404251740"/>
 <unit id="ch.qos.logback.classic.source" version="1.1.7"/>
 <unit id="ch.qos.logback.core" version="1.1.7"/>
 <unit id="ch.qos.logback.core.source" version="1.1.7"/>
+<unit id="com.esotericsoftware.kryo" version="4.0.0"/>
+<unit id="com.esotericsoftware.kryo.source" version="4.0.0"/>
+<unit id="com.esotericsoftware.minlog" version="1.3.0"/>
+<unit id="com.esotericsoftware.minlog.source" version="1.3.0"/>
+<unit id="com.esotericsoftware.reflectasm" version="1.11.3"/>
+<unit id="com.esotericsoftware.reflectasm.source" version="1.11.3"/>
 <unit id="com.fasterxml.jackson.core.jackson-annotations" version="2.8.0"/>
 <unit id="com.fasterxml.jackson.core.jackson-annotations.source" version="2.8.0"/>
 <unit id="com.fasterxml.jackson.core.jackson-core" version="2.8.5"/>
 <unit id="org.jfree.jcommon.source" version="1.0.23"/>
 <unit id="org.mozilla.rhino" version="1.7.7.1"/>
 <unit id="org.mozilla.rhino.source" version="1.7.7.1"/>
+<unit id="org.objenesis" version="2.2.0"/>
+<unit id="org.objenesis.source" version="2.2.0"/>
 <unit id="org.supercsv" version="2.4.0"/>
 <unit id="org.supercsv.source" version="2.4.0"/>
 <unit id="bouncycastle.bcprov-jdk14" version="138.0.0"/>
index ca20f0fb9986fa044688161397e06b7a182e20de..455222dea48b81d38a3ad71e2cc55f4826421765 100644 (file)
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <?pde version="3.8"?>
-<target name="Simantics 1.29.0" sequenceNumber="16">
+<target name="Simantics 1.29.0" sequenceNumber="18">
 <locations>
 <location includeAllPlatforms="true" includeConfigurePhase="false" includeMode="slicer" includeSource="true" type="InstallableUnit">
 <unit id="org.simantics.sdk.feature.group" version="1.29.0"/>
 <unit id="ch.qos.logback.classic.source" version="1.1.7"/>
 <unit id="ch.qos.logback.core" version="1.1.7"/>
 <unit id="ch.qos.logback.core.source" version="1.1.7"/>
+<unit id="com.esotericsoftware.kryo" version="4.0.0"/>
+<unit id="com.esotericsoftware.kryo.source" version="4.0.0"/>
+<unit id="com.esotericsoftware.minlog" version="1.3.0"/>
+<unit id="com.esotericsoftware.minlog.source" version="1.3.0"/>
+<unit id="com.esotericsoftware.reflectasm" version="1.11.3"/>
+<unit id="com.esotericsoftware.reflectasm.source" version="1.11.3"/>
 <unit id="com.fasterxml.jackson.core.jackson-annotations" version="2.8.0"/>
 <unit id="com.fasterxml.jackson.core.jackson-annotations.source" version="2.8.0"/>
 <unit id="com.fasterxml.jackson.core.jackson-core" version="2.8.5"/>
 <unit id="org.jfree.jcommon.source" version="1.0.23"/>
 <unit id="org.mozilla.rhino" version="1.7.7.1"/>
 <unit id="org.mozilla.rhino.source" version="1.7.7.1"/>
+<unit id="org.objenesis" version="2.2.0"/>
+<unit id="org.objenesis.source" version="2.2.0"/>
 <unit id="org.supercsv" version="2.4.0"/>
 <unit id="org.supercsv.source" version="2.4.0"/>
 <unit id="bouncycastle.bcprov-jdk14" version="138.0.0"/>
index 4701e2586e961465e9a9a6c95085b984eb8111a2..dc2c775241574595b88c5f36ccdf75e8610782c6 100644 (file)
@@ -147,6 +147,7 @@ public class ModuleRegressionTests extends TestBase {
     @Test public void Matching2() { test(); }
     @Test public void Matching4() { test(); }
     @Test public void Matching5() { test(); }
+    @Test public void Matching6() { test(); }
     @Test public void MatchingWithMissingParameter() { test(); }
     @Test public void MatchingWithoutTypeAnnotations() { test(); }
     @Test public void MaximumBy() { test(); }
index 4a9bffd093c0b0737804008a4f7f148e63e3c058..784a80b4c6072383d659786d57bd9e0eb48fd1ec 100644 (file)
@@ -1,12 +1,16 @@
 package org.simantics.scl.compiler.tests;
 
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.simantics.scl.compiler.commands.CommandSession;
+import org.simantics.scl.compiler.errors.CompilationError;
+import org.simantics.scl.compiler.errors.CompilationErrorFormatter;
 import org.simantics.scl.compiler.module.repository.ModuleRepository;
 import org.simantics.scl.runtime.reporting.AbstractSCLReportingHandler;
 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
 
+
 public class TestCommandSession {
 
     ModuleRepository moduleRepository;
@@ -72,5 +76,33 @@ public class TestCommandSession {
         session.execute("iter (\\i -> print i) [1,2,3]");
         session.execute("iter (\\i -> print i) [(),(),()]");
     }
+    
+    @Test
+    public void testValidation() {
+        {
+            CompilationError[] errors = CommandSession.validate(moduleRepository, "1+1");
+            Assert.assertEquals(0, errors.length);
+        }
+        {
+            CompilationError[] errors = CommandSession.validate(moduleRepository, "\"a\"+1");
+            Assert.assertEquals(1, errors.length);
+        }
+        {
+            CompilationError[] errors = CommandSession.validate(moduleRepository,
+                    "a = 1\n" +
+                    "b = 2\n" +
+                    "a + b");
+            Assert.assertEquals(0, errors.length);
+        }
+        {
+            String source = 
+                    "a = 1\n" +
+                    "b = 2.0\n" +
+                    "a + b"; 
+            CompilationError[] errors = CommandSession.validate(moduleRepository, source);
+            //System.out.println(CompilationErrorFormatter.toString(source, errors));
+            Assert.assertEquals(1, errors.length);
+        }
+    }
 
 }
diff --git a/tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Matching6.scl b/tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Matching6.scl
new file mode 100644 (file)
index 0000000..f4f7cc4
--- /dev/null
@@ -0,0 +1,9 @@
+import "Prelude"
+
+main = do 
+    match 1+1 :: Integer with
+        2 -> 2
+        0 -> 0
+        1 -> 1
+--
+2
\ No newline at end of file
index 4554294272ae1b0b07f356477cb44a5d92e06183..8daf95832ecb354e4c1bb0862fed0cfd31d83982 100644 (file)
@@ -1,8 +1,5 @@
 package org.simantics.scl.osgi.tests;
 
-import java.util.ArrayList;
-import java.util.concurrent.atomic.AtomicInteger;
-
 import org.eclipse.core.runtime.IProgressMonitor;
 import org.eclipse.core.runtime.NullProgressMonitor;
 import org.junit.AfterClass;
@@ -15,14 +12,8 @@ import org.simantics.application.arguments.Arguments;
 import org.simantics.application.arguments.IArgumentFactory;
 import org.simantics.application.arguments.IArguments;
 import org.simantics.application.arguments.SimanticsArguments;
-import org.simantics.scl.compiler.errors.DoesNotExist;
-import org.simantics.scl.compiler.errors.Failable;
-import org.simantics.scl.compiler.module.Module;
 import org.simantics.scl.osgi.SCLOsgi;
 
-import gnu.trove.procedure.TObjectProcedure;
-
-
 public class TestSCLOsgi {
     private static IProgressMonitor progress = new NullProgressMonitor();
     
@@ -47,30 +38,9 @@ public class TestSCLOsgi {
     
     @Test
     public void testDataJsonExists() {
-        ArrayList<String> modulesWithErrors = new ArrayList<String>(); 
-        SCLOsgi.SOURCE_REPOSITORY.forAllModules(new TObjectProcedure<String>() {
-            @Override
-            public boolean execute(String moduleName) {
-                System.out.print(moduleName);
-                System.out.print(" - ");
-                Failable<Module> module = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName);
-                if(module.didSucceed())
-                    System.out.println("succeeded");
-                else if(module == DoesNotExist.INSTANCE)
-                    System.out.println("does not exist"); // should not happen
-                else {
-                    System.out.println("error");
-                    modulesWithErrors.add(moduleName);
-                }
-                return true;
-            }
-        });
-        if(!modulesWithErrors.isEmpty()) {
-            StringBuilder b = new StringBuilder();
-            b.append("Some SCL modules failed to compile:");
-            for(String module : modulesWithErrors)
-                b.append(' ').append(module);
-            Assert.fail(b.toString());
+        String possibleError = SCLOsgi.compileAllModules();
+        if(possibleError != null) {
+            Assert.fail(possibleError);
         }
     }
 }