From: Hannu Niemistö Date: Wed, 17 May 2017 10:53:26 +0000 (+0300) Subject: Merge "(refs #6878) Don't validate SCL expressions in console input area" X-Git-Tag: v1.29.0~42 X-Git-Url: https://gerrit.simantics.org/r/gitweb?p=simantics%2Fplatform.git;a=commitdiff_plain;h=06ee0c4c71cd9e372969da1570e7fcac2c4397a5;hp=4ae2c9f1590b39ec61dcf2a1f27529fcefaf6f8e Merge "(refs #6878) Don't validate SCL expressions in console input area" --- diff --git a/bundles/org.simantics.acorn/src/org/simantics/acorn/lru/LRU.java b/bundles/org.simantics.acorn/src/org/simantics/acorn/lru/LRU.java index 80fec7032..690ba426f 100644 --- a/bundles/org.simantics.acorn/src/org/simantics/acorn/lru/LRU.java +++ b/bundles/org.simantics.acorn/src/org/simantics/acorn/lru/LRU.java @@ -556,14 +556,18 @@ public class LRU> { 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++; } } diff --git a/bundles/org.simantics.browsing.ui.swt/META-INF/MANIFEST.MF b/bundles/org.simantics.browsing.ui.swt/META-INF/MANIFEST.MF index 37466aeda..4eaa04be3 100644 --- a/bundles/org.simantics.browsing.ui.swt/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.browsing.ui.swt/META-INF/MANIFEST.MF @@ -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 index 109d84084..000000000 --- a/bundles/org.simantics.browsing.ui.swt/src/org/simantics/browsing/ui/swt/widgets/SCLEditor.java +++ /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 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 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() { - - 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(); - } - -} diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/service/ServiceActivityMonitorImpl.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/service/ServiceActivityMonitorImpl.java index 1858e87dd..541380dc5 100644 --- a/bundles/org.simantics.db.common/src/org/simantics/db/common/service/ServiceActivityMonitorImpl.java +++ b/bundles/org.simantics.db.common/src/org/simantics/db/common/service/ServiceActivityMonitorImpl.java @@ -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); + } } } diff --git a/bundles/org.simantics.db.layer0/adapters.xml b/bundles/org.simantics.db.layer0/adapters.xml index 13fbd87b2..5586b5fd1 100644 --- a/bundles/org.simantics.db.layer0/adapters.xml +++ b/bundles/org.simantics.db.layer0/adapters.xml @@ -140,6 +140,11 @@ class="org.simantics.db.layer0.adapter.impl.SharedOntologyCopyHandler"> + + + 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) { diff --git a/bundles/org.simantics.debug.ui/plugin.xml b/bundles/org.simantics.debug.ui/plugin.xml index 6ed0b55c2..abceb0952 100644 --- a/bundles/org.simantics.debug.ui/plugin.xml +++ b/bundles/org.simantics.debug.ui/plugin.xml @@ -83,6 +83,11 @@ id="org.simantics.debug.adapter2" priority="-1"> + + sgProvider = new AtomicReference(); final ISessionContext sessionContext = Simantics.getSessionContext(); final DataContainer result = new DataContainer(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 sgProvider = new AtomicReference(); + final DataContainer result = new DataContainer(null); + final DataContainer exception = new DataContainer(null); + + try { + + final ISessionContext sessionContext = Simantics.getSessionContext(); + + Pair modelAndRVI = sessionContext.getSession().syncRequest(new UniqueRead>() { + @Override + public Pair perform(ReadGraph graph) throws DatabaseException { + return new Pair( 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(); + + } + } diff --git a/bundles/org.simantics.diagram/src/org/simantics/diagram/adapter/FlagClassFactory.java b/bundles/org.simantics.diagram/src/org/simantics/diagram/adapter/FlagClassFactory.java index 30efa54f0..56c2ceef4 100644 --- a/bundles/org.simantics.diagram/src/org/simantics/diagram/adapter/FlagClassFactory.java +++ b/bundles/org.simantics.diagram/src/org/simantics/diagram/adapter/FlagClassFactory.java @@ -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) { diff --git a/bundles/org.simantics.diagram/src/org/simantics/diagram/flag/IFlagType.java b/bundles/org.simantics.diagram/src/org/simantics/diagram/flag/IFlagType.java index 8176d1e79..0c5974a8f 100644 --- a/bundles/org.simantics.diagram/src/org/simantics/diagram/flag/IFlagType.java +++ b/bundles/org.simantics.diagram/src/org/simantics/diagram/flag/IFlagType.java @@ -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); + } } diff --git a/bundles/org.simantics.diagram/src/org/simantics/diagram/handler/Paster.java b/bundles/org.simantics.diagram/src/org/simantics/diagram/handler/Paster.java index c8995f4c1..667259907 100644 --- a/bundles/org.simantics.diagram/src/org/simantics/diagram/handler/Paster.java +++ b/bundles/org.simantics.diagram/src/org/simantics/diagram/handler/Paster.java @@ -1364,4 +1364,8 @@ public class Paster { protected PasteOperation getOperation() { return op; } + + public WriteGraph getGraph() { + return graph; + } } diff --git a/bundles/org.simantics.diagram/src/org/simantics/diagram/profile/StyleBase.java b/bundles/org.simantics.diagram/src/org/simantics/diagram/profile/StyleBase.java index 5aed90b48..ee203616d 100644 --- a/bundles/org.simantics.diagram/src/org/simantics/diagram/profile/StyleBase.java +++ b/bundles/org.simantics.diagram/src/org/simantics/diagram/profile/StyleBase.java @@ -457,7 +457,11 @@ public abstract class StyleBase 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() { diff --git a/bundles/org.simantics.document.server.io/src/org/simantics/document/server/io/CommandContextImpl.java b/bundles/org.simantics.document.server.io/src/org/simantics/document/server/io/CommandContextImpl.java index 3277bbd1e..5b49810fa 100644 --- a/bundles/org.simantics.document.server.io/src/org/simantics/document/server/io/CommandContextImpl.java +++ b/bundles/org.simantics.document.server.io/src/org/simantics/document/server/io/CommandContextImpl.java @@ -80,11 +80,24 @@ public class CommandContextImpl implements CommandContextMutable { @Override public String toString() { StringBuilder sb = new StringBuilder(); + sb.append("CommandContext:\n"); for (Map.Entry>> 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> value = entry.getValue(); + if(value.size() == 1) { + List t = (List)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(); } diff --git a/bundles/org.simantics.document.server/scl/Document/All.scl b/bundles/org.simantics.document.server/scl/Document/All.scl index fa83a224a..7781cfdb3 100644 --- a/bundles/org.simantics.document.server/scl/Document/All.scl +++ b/bundles/org.simantics.document.server/scl/Document/All.scl @@ -85,6 +85,9 @@ instance Coercible CommandContextMutable CommandContext where cloneCommandContext :: CommandContext -> 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 -> String displayValue0 var = propertyValue var "HasDisplayValue" -consoleLog :: Variable -> String -> () -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 -> IDocument contextDocument ctx = justValue ctx "__document__" diff --git a/bundles/org.simantics.document.server/src/org/simantics/document/server/Functions.java b/bundles/org.simantics.document.server/src/org/simantics/document/server/Functions.java index 25bec0c91..20fa2a71b 100644 --- a/bundles/org.simantics.document.server/src/org/simantics/document/server/Functions.java +++ b/bundles/org.simantics.document.server/src/org/simantics/document/server/Functions.java @@ -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 diff --git a/bundles/org.simantics.g2d/src/org/simantics/g2d/canvas/Hints.java b/bundles/org.simantics.g2d/src/org/simantics/g2d/canvas/Hints.java index cf5f70610..3fd43f0f0 100644 --- a/bundles/org.simantics.g2d/src/org/simantics/g2d/canvas/Hints.java +++ b/bundles/org.simantics.g2d/src/org/simantics/g2d/canvas/Hints.java @@ -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 true 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 {} /** diff --git a/bundles/org.simantics.graph.db/META-INF/MANIFEST.MF b/bundles/org.simantics.graph.db/META-INF/MANIFEST.MF index f21b3e776..165a104ed 100644 --- a/bundles/org.simantics.graph.db/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.graph.db/META-INF/MANIFEST.MF @@ -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 index 7ca83f318..000000000 --- a/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldMissingDependencyException.java +++ /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 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 index 6a69e8d92..000000000 --- a/bundles/org.simantics.graph.db/src/org/simantics/graph/db/old/OldTransferableGraphImportProcess1.java +++ /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 missingExternals = new HashSet(); - - // 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 removals = new HashSet(); - 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>()) - .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= 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 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); - - } - -} diff --git a/bundles/org.simantics.graph/META-INF/MANIFEST.MF b/bundles/org.simantics.graph/META-INF/MANIFEST.MF index 5f4404acc..6ae6e86fe 100644 --- a/bundles/org.simantics.graph/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.graph/META-INF/MANIFEST.MF @@ -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 diff --git a/bundles/org.simantics.graph/src/org/simantics/graph/query/TransferableGraphConversion.java b/bundles/org.simantics.graph/src/org/simantics/graph/query/TransferableGraphConversion.java index 850c47d85..9c96f834d 100644 --- a/bundles/org.simantics.graph/src/org/simantics/graph/query/TransferableGraphConversion.java +++ b/bundles/org.simantics.graph/src/org/simantics/graph/query/TransferableGraphConversion.java @@ -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); diff --git a/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/GraphRefactoringUtils.java b/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/GraphRefactoringUtils.java index 9882048b7..9f8eca398 100644 --- a/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/GraphRefactoringUtils.java +++ b/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/GraphRefactoringUtils.java @@ -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 newIdentities = new ArrayList(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= 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 index d98069227..000000000 --- a/bundles/org.simantics.graph/src/org/simantics/graph/refactoring/PrintReferencesTool.java +++ /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 map = idStore.getChildMap(cur); - if(map == null) - return; - ArrayList names = new ArrayList(map.keySet()); - Collections.sort(names); - for(String name : names) { - ConsistsOf co = map.get(name); - if(!idStore.isNewResource(co.child)) { - for(int i=0;i rules = new ArrayList(); - 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); - } - -} diff --git a/bundles/org.simantics.graph/src/org/simantics/graph/representation/PrettyPrintTG.java b/bundles/org.simantics.graph/src/org/simantics/graph/representation/PrettyPrintTG.java index 5968b6822..3243b82bd 100644 --- a/bundles/org.simantics.graph/src/org/simantics/graph/representation/PrettyPrintTG.java +++ b/bundles/org.simantics.graph/src/org/simantics/graph/representation/PrettyPrintTG.java @@ -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 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> statements, String predicate, String object) { + List objects = statements.get(predicate); + if(objects == null) { + objects = new ArrayList(); + 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=\n"); - } else { - output.append(info.name + "\n"); - } - if(info.newResource) - output.append(" @L0.new\n"); + + Map> statements = new HashMap<>(); + Identity consistsOf = findExternal(graph, "http://www.simantics.org/Layer0-1.1/ConsistsOf"); TLongHashSet processed = new TLongHashSet(); for(int i=0;i"); + } else if (info.aliasURI != null) { + output.append(info.name + " = <" + info.aliasURI + ">"); + } else { + output.append(info.name); + } + + List instanceOfs = statements.get("L0.InstanceOf"); + if(instanceOfs != null) { + for(String instanceOf : instanceOfs) { + output.append(" : " + instanceOf); } } + + List subrelationOfs = statements.get("L0.SubrelationOf"); + if(subrelationOfs != null) { + for(String subrelationOf : subrelationOfs) { + output.append(" inherits = statements.get("L0.Inherits"); + if(inherits != null) { + for(String inherit : inherits) { + output.append(" > 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 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 = \n"); this.output.append("G2D = \n"); this.output.append("SEL = \n"); + this.output.append("VP = \n"); this.output.append("IMAGE2 = \n"); this.output.append("GRAPHFILE = \n"); this.output.append("APROS_OPER = \n"); @@ -276,15 +395,15 @@ public class PrettyPrintTG extends TransferableGraphUtils { this.output.append("SIMUPEDIA_WB = \n"); this.output.append("SIMUPEDIA_STD = \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 index b68bea31e..000000000 --- a/bundles/org.simantics.graph/src/org/simantics/graph/representation/old/OldTransferableGraph1.java +++ /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 specification. - * @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 extensions; - - public OldTransferableGraph1() {} - - public OldTransferableGraph1(int resourceCount, Identity[] identities, - int[] statements, OldValue1[] values) { - this(resourceCount, identities, statements, values, - new TreeMap()); - } - - public OldTransferableGraph1(int resourceCount, Identity[] identities, - int[] statements, OldValue1[] values, TreeMap 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 inputFiles = new ArrayList(); - List outputFiles = new ArrayList(); - 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 index d85d332c2..000000000 --- a/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/mappingSpec.txt +++ /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 index d005eb22c..000000000 Binary files a/bundles/org.simantics.graph/tests/org/simantics/graph/tests/refactoring/xor5.aprosSymbol and /dev/null differ diff --git a/bundles/org.simantics.modeling.ui/META-INF/MANIFEST.MF b/bundles/org.simantics.modeling.ui/META-INF/MANIFEST.MF index 525c8da52..a426ba5c9 100644 --- a/bundles/org.simantics.modeling.ui/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.modeling.ui/META-INF/MANIFEST.MF @@ -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, diff --git a/bundles/org.simantics.modeling.ui/scl/Simantics/Testing/BrowseContext.scl b/bundles/org.simantics.modeling.ui/scl/Simantics/Testing/BrowseContext.scl index cd4e9755d..a662f57f4 100644 --- a/bundles/org.simantics.modeling.ui/scl/Simantics/Testing/BrowseContext.scl +++ b/bundles/org.simantics.modeling.ui/scl/Simantics/Testing/BrowseContext.scl @@ -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 null if there was no value for the key """ - getConstant :: NodeContext -> ConstantKey -> a + getConstant :: NodeContext -> BuiltinKeys.ConstantKey -> a importJava "org.eclipse.jface.resource.ImageDescriptor" where data ImageDescriptor diff --git a/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/componentTypeEditor/PGraphEditorDocumentProvider.java b/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/componentTypeEditor/PGraphEditorDocumentProvider.java index 69449fd8f..ad247b6bd 100644 --- a/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/componentTypeEditor/PGraphEditorDocumentProvider.java +++ b/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/componentTypeEditor/PGraphEditorDocumentProvider.java @@ -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) { diff --git a/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/pdf/PDFPainter.java b/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/pdf/PDFPainter.java index 1adcf25c2..bec1e5408 100644 --- a/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/pdf/PDFPainter.java +++ b/bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/pdf/PDFPainter.java @@ -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); diff --git a/bundles/org.simantics.modeling/scl/Simantics/All.scl b/bundles/org.simantics.modeling/scl/Simantics/All.scl index 00d6980cf..85d42e103 100644 --- a/bundles/org.simantics.modeling/scl/Simantics/All.scl +++ b/bundles/org.simantics.modeling/scl/Simantics/All.scl @@ -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 diff --git a/bundles/org.simantics.modeling/scl/Simantics/Misc.scl b/bundles/org.simantics.modeling/scl/Simantics/Misc.scl index e3c797715..c00c564e8 100644 --- a/bundles/org.simantics.modeling/scl/Simantics/Misc.scl +++ b/bundles/org.simantics.modeling/scl/Simantics/Misc.scl @@ -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 diff --git a/bundles/org.simantics.modeling/src/org/simantics/modeling/CompilePGraphs.java b/bundles/org.simantics.modeling/src/org/simantics/modeling/CompilePGraphs.java index 9b620c2f7..10e23c65b 100644 --- a/bundles/org.simantics.modeling/src/org/simantics/modeling/CompilePGraphs.java +++ b/bundles/org.simantics.modeling/src/org/simantics/modeling/CompilePGraphs.java @@ -89,21 +89,10 @@ public class CompilePGraphs { final Collection sources = new ArrayList<>(); Collection 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() { + final Pair thisOntology = Simantics.sync(new UniqueRead>() { @Override - public TransferableGraph1 perform(ReadGraph graph) throws DatabaseException { + public Pair 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 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 diff --git a/bundles/org.simantics.modeling/src/org/simantics/modeling/ModelingUtils.java b/bundles/org.simantics.modeling/src/org/simantics/modeling/ModelingUtils.java index 3b4806c7c..8a5b92228 100644 --- a/bundles/org.simantics.modeling/src/org/simantics/modeling/ModelingUtils.java +++ b/bundles/org.simantics.modeling/src/org/simantics/modeling/ModelingUtils.java @@ -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 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); } diff --git a/bundles/org.simantics.modeling/src/org/simantics/modeling/scl/GraphModuleSourceRepository.java b/bundles/org.simantics.modeling/src/org/simantics/modeling/scl/GraphModuleSourceRepository.java index c75f7a941..09f7694dd 100644 --- a/bundles/org.simantics.modeling/src/org/simantics/modeling/scl/GraphModuleSourceRepository.java +++ b/bundles/org.simantics.modeling/src/org/simantics/modeling/scl/GraphModuleSourceRepository.java @@ -71,7 +71,7 @@ public enum GraphModuleSourceRepository implements ModuleSourceRepository { } @Override public void removeListener(UpdateListener listener) { - listener = null; + this.listener = null; } @Override public boolean isDisposed() { diff --git a/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/SVGNode.java b/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/SVGNode.java index cdd6a2645..2dd285fd8 100644 --- a/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/SVGNode.java +++ b/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/SVGNode.java @@ -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(); diff --git a/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/connection/RouteGraphNode.java b/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/connection/RouteGraphNode.java index 4650d2e13..084c0d658 100644 --- a/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/connection/RouteGraphNode.java +++ b/bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/nodes/connection/RouteGraphNode.java @@ -215,7 +215,7 @@ public class RouteGraphNode extends G2DNode implements ISelectionPainterNode, In if(dynamicColor != null || dynamicStroke != null) { BasicConnectionStyle baseStyle = (BasicConnectionStyle)tryGetStyle(baseRenderer); try { - Constructor c = baseStyle.getClass().getConstructor(Color.class, Color.class, double.class, Stroke.class, Stroke.class, double.class); + Constructor 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 index eca7bdba8..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.simantics.scl.compiler.dummy/.project b/bundles/org.simantics.scl.compiler.dummy/.project deleted file mode 100644 index 62879b7cf..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - org.simantics.scl.compiler.dummy - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - 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 index 0c68a61dc..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/.settings/org.eclipse.jdt.core.prefs +++ /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 index da14e1372..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/META-INF/MANIFEST.MF +++ /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 index 34d2e4d2d..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/build.properties +++ /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 index 958fd1204..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/ErrorMessage.java +++ /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 index 7a61c27f0..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/InvalidInputException.java +++ /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 errors; - - public InvalidInputException(Collection errors) { - this.errors = errors; - } - - public Collection 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 index b552c707b..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompiler.java +++ /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 index de0461ff1..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/SCLCompilerConfiguration.java +++ /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 index e86be850d..000000000 --- a/bundles/org.simantics.scl.compiler.dummy/src/org/simantics/scl/compiler/StandardSCLCompilerConfiguration.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.simantics.scl.compiler; - - -public class StandardSCLCompilerConfiguration implements SCLCompilerConfiguration { - - public static final SCLCompilerConfiguration INSTANCE = new StandardSCLCompilerConfiguration(); - -} diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/CommandSession.java b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/CommandSession.java index 82d615ca8..1cf6d0de9 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/CommandSession.java +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/CommandSession.java @@ -76,7 +76,12 @@ public class CommandSession { THashMap variableTypes = new THashMap(); 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)); + } + } diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/TestScriptExecutor.java b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/TestScriptExecutor.java index ab39d538a..4afeef91c 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/TestScriptExecutor.java +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/commands/TestScriptExecutor.java @@ -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 diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/common/names/Names.java b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/common/names/Names.java index 1737a0d7d..1c4255b46 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/common/names/Names.java +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/common/names/Names.java @@ -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"); diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/expressions/EApply.java b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/expressions/EApply.java index fd5822743..501c7f95d 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/expressions/EApply.java +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/expressions/EApply.java @@ -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)); diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/java/LoggingModule.java b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/java/LoggingModule.java index fa5059626..45596c570 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/java/LoggingModule.java +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/java/LoggingModule.java @@ -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; diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/internal/codegen/ssa/exits/Switch.java b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/internal/codegen/ssa/exits/Switch.java index 27f853e02..386199d83 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/internal/codegen/ssa/exits/Switch.java +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/internal/codegen/ssa/exits/Switch.java @@ -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 labelMap = new TIntObjectHashMap