-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart;\r
-\r
-import java.util.ArrayList;\r
-import java.util.LinkedHashMap;\r
-\r
-import org.eclipse.jface.dialogs.IDialogSettings;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.ScrolledComposite;\r
-import org.eclipse.swt.dnd.DND;\r
-import org.eclipse.swt.dnd.DropTarget;\r
-import org.eclipse.swt.dnd.DropTargetAdapter;\r
-import org.eclipse.swt.dnd.DropTargetEvent;\r
-import org.eclipse.swt.dnd.Transfer;\r
-import org.eclipse.swt.graphics.Color;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.graphics.Rectangle;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.ui.IMemento;\r
-import org.eclipse.ui.IViewSite;\r
-import org.eclipse.ui.PartInitException;\r
-import org.eclipse.ui.part.ViewPart;\r
-import org.simantics.db.AsyncReadGraph;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.AsyncListener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.internal.Activator;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.dnd.LocalObjectTransfer;\r
-import org.simantics.utils.RunnableWithObject;\r
-\r
-/**\r
- * Chart panel displays multiple charts in a single view. The view can be oriented \r
- * vertically or horizontally, the default is vertical. Charts can be added, removed \r
- * minimized or expanded. The order of the charts can be changed by dragging the charts.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ChartPanel extends ViewPart {\r
-\r
- private Composite body;\r
- private ScrolledComposite sc;\r
-\r
- private IDialogSettings settings;\r
- private LinkedHashMap<Resource, ChartPanelElement> charts;\r
- private ArrayList<Resource> minimizedResources;\r
-\r
- private ArrayList<ChartPanelElement> chartElements;\r
-\r
- public static final String CHART_PANEL_SETTINGS = "CHART_PANEL_SETTINGS";\r
- public static final String CHARTS = "CHART_PANEL_CHARTS";\r
- public static final String MINIMIZED_CHARTS = "CHART_PANEL_MINIMIZED_CHARTS";\r
- public static final String CHART_PANEL_ORIENTATION = "CHART_PANEL_ORIENTATION";\r
-\r
- public static final String CHART_PANEL_VERTICAL = "CHART_PANEL_ORIENTATION_VERTICAL";\r
- public static final String CHART_PANEL_HORIZONTAL = "CHART_PANEL_ORIENTATION_HORIZONTAL";\r
-\r
- private boolean vertical = true;\r
-\r
- /**\r
- * Initialize the view. Load charts that have previously been open (if there are any).\r
- */\r
- @Override\r
- public void init(IViewSite site, IMemento memento) throws PartInitException {\r
- super.init(site, memento);\r
-\r
- minimizedResources = new ArrayList<Resource>();\r
-\r
- settings = Activator.getDefault().getDialogSettings().getSection(CHART_PANEL_SETTINGS);\r
-\r
- // Initialize settings if there are no settings\r
- if (settings == null) {\r
- settings = Activator.getDefault().getDialogSettings().addNewSection(CHART_PANEL_SETTINGS);\r
- }\r
-\r
- if(settings.getArray(CHARTS) == null) {\r
- String[] chartUris = new String[] {};\r
- settings.put(CHARTS, chartUris);\r
- }\r
-\r
- if(settings.getArray(MINIMIZED_CHARTS) == null) {\r
- String[] minimizedChartUris = new String[] {};\r
- settings.put(MINIMIZED_CHARTS, minimizedChartUris);\r
- }\r
-\r
- // initialize chart lists\r
- charts = new LinkedHashMap<Resource, ChartPanelElement>();\r
-\r
- // add chart resources to chart lists from settings\r
- try {\r
- SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Resource chart = null;\r
- String[] chartURIs = settings.getArray(CHARTS);\r
- for(String uri : chartURIs) {\r
- chart = graph.getPossibleResource(uri);\r
- if(chart != null && graph.isInstanceOf(chart, jfree.Chart)) {\r
- charts.put(chart, null);\r
- setChartExistingListener(chart);\r
- }\r
- }\r
-\r
- String[] minimizedUris = settings.getArray(MINIMIZED_CHARTS);\r
- for(String uri : minimizedUris) {\r
- chart = graph.getPossibleResource(uri);\r
- if(chart != null && graph.isInstanceOf(chart, jfree.Chart)) {\r
- minimizedResources.add(chart);\r
- } \r
- }\r
- }\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
-\r
- // set the orientation of the panel\r
- String orientation = settings.get(CHART_PANEL_ORIENTATION);\r
- if(CHART_PANEL_VERTICAL.equals(orientation))\r
- this.vertical = true;\r
- else if(CHART_PANEL_HORIZONTAL.equals(orientation))\r
- this.vertical = false;\r
-\r
- }\r
-\r
- /**\r
- * Create a scrolled composite that will contain all the charts, then call the actual \r
- * content creator.\r
- */\r
- @Override\r
- public void createPartControl(Composite parent) {\r
- sc = new ScrolledComposite(parent, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);\r
- GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(sc);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);\r
- sc.setExpandHorizontal(true);\r
- sc.setExpandVertical(true);\r
- sc.getVerticalBar().setIncrement(sc.getVerticalBar().getIncrement()*3);\r
- sc.getHorizontalBar().setIncrement(sc.getHorizontalBar().getIncrement()*3);\r
-\r
- body = new Composite(sc, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().margins(3, 0).spacing(0, 0).applyTo(body);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(body);\r
-\r
- sc.setContent(body);\r
- createContents();\r
- \r
- setupDropTarget();\r
-\r
- }\r
- \r
- /**\r
- * Creates the contents of this chart panel.\r
- * Removes all old contents before creating new content\r
- */\r
- private void createContents() {\r
- chartElements = new ArrayList<ChartPanelElement>();\r
-\r
- for(Control child : body.getChildren()) {\r
- child.dispose();\r
- }\r
- \r
- // Set the initial layout\r
- ElementContainer elementHolder;\r
- for(Resource e : charts.keySet()) {\r
- elementHolder = new ElementContainer(body, SWT.NONE);\r
- elementHolder.setBackground(new Color(elementHolder.getDisplay(), 255, 0, 0));\r
- ChartPanelElement element = new ChartPanelElement(elementHolder, this, e, SWT.NONE);\r
- elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)element.getLayout()));\r
- chartElements.add(element);\r
- charts.put(e, element);\r
- if(minimizedResources.contains(e)) {\r
- element.toggleMinimize();\r
- }\r
- }\r
-\r
- elementHolder = new ElementContainer(body, SWT.NONE);\r
- elementHolder.setBackground(new Color(elementHolder.getDisplay(), 0, 255, 0));\r
- ChartPanelElement element = new ChartPanelElement(elementHolder, this, null, SWT.NONE); // Last element is empty -> only the separator\r
- elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)element.getLayout()));\r
- chartElements.add(element);\r
-\r
- layout();\r
- saveState();\r
-\r
- }\r
-\r
- /**\r
- * Lays out this panel (the body composite)\r
- */\r
- public void layout() {\r
- if(vertical) {\r
- GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(body);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(body);\r
- } else {\r
- // Need to calculate horizontal elements for gridLayout\r
- int chartPanels = chartElements.size();\r
- GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(chartPanels).applyTo(body);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(body);\r
- }\r
- body.layout();\r
- sc.setMinSize(body.computeSize(SWT.DEFAULT, SWT.DEFAULT));\r
- }\r
-\r
- @Override\r
- public void setFocus() {\r
- if(!sc.isDisposed())\r
- sc.setFocus();\r
- }\r
-\r
- @Override\r
- public void saveState(IMemento memento) {\r
- super.saveState(memento);\r
- saveState();\r
- }\r
-\r
- /**\r
- * Save the current state of the view to IDialogSettings \r
- */\r
- public void saveState() {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- if (settings != null) {\r
- String[] uris = new String[chartElements.size() - 1];\r
- ArrayList<String> minimized = new ArrayList<String>();\r
- minimizedResources.clear();\r
- for(int i = 0; i < uris.length; i++) {\r
- ChartPanelElement e = chartElements.get(i);\r
- Resource r = e.getResource();\r
- if(r != null) {\r
- uris[i] = graph.getURI(r);\r
- if(e.isMinimized()) {\r
- minimized.add(uris[i]);\r
- minimizedResources.add(r);\r
- }\r
- } else {\r
- uris[i] = "";\r
- }\r
- }\r
- settings.put(CHARTS, uris);\r
- if(!minimized.isEmpty())\r
- settings.put(MINIMIZED_CHARTS, minimized.toArray(new String[minimized.size()]));\r
- else\r
- settings.put(MINIMIZED_CHARTS, new String[0]);\r
-\r
- if(vertical)\r
- settings.put(CHART_PANEL_ORIENTATION, CHART_PANEL_VERTICAL);\r
- else\r
- settings.put(CHART_PANEL_ORIENTATION, CHART_PANEL_HORIZONTAL);\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- /**\r
- * Set the orientation for this chart panel.\r
- * \r
- * @param orientation Orientation (ChartPanel.CHART_PANEL_VERTICAL or ChartPanel.CHART_PANEL_HORIZONTAL)\r
- */\r
- public void setOrientation(String orientation) {\r
- if(CHART_PANEL_VERTICAL.equals(orientation))\r
- this.vertical = true;\r
- else {\r
- this.vertical = false;\r
- }\r
- createContents();\r
- }\r
-\r
- /**\r
- * Removes a chart from this panel\r
- * \r
- * @param chart The chart to be removed\r
- */\r
- public void removeChart(Resource chart) {\r
- ChartPanelElement element = charts.get(chart);\r
- chartElements.remove(element);\r
- element.getParent().dispose();\r
- charts.remove(chart);\r
- minimizedResources.remove(chart);\r
- saveState();\r
- layout();\r
- }\r
-\r
- /**\r
- * Sets up drag-scrolling for a scrolled composite \r
- * \r
- * @param control\r
- */\r
- protected void setupDropTarget() {\r
- DropTarget target = new DropTarget(sc, DND.DROP_MOVE);\r
- target.setTransfer(new Transfer[] { LocalObjectTransfer.getTransfer() });\r
-\r
- target.addDropListener(new DropTargetAdapter() {\r
-\r
- private int activeMargin = 20;\r
- private int moveAmount = 1;\r
-\r
- @Override\r
- public void dragOver(DropTargetEvent event) { \r
- Point original = sc.getOrigin();\r
- Point origin = sc.getOrigin();\r
- Point pointer = sc.toControl(event.x, event.y);\r
- Rectangle bounds = sc.getBounds();\r
-\r
- if(pointer.y < activeMargin)\r
- origin.y = origin.y - moveAmount;\r
- else if(bounds.height - pointer.y < activeMargin)\r
- origin.y = origin.y + moveAmount;\r
- if(pointer.x < activeMargin)\r
- origin.x = origin.x - moveAmount;\r
- else if(bounds.width - pointer.x < activeMargin)\r
- origin.x = origin.x + moveAmount;\r
-\r
- if(origin != original) {\r
- sc.setOrigin (origin.x, origin.y);\r
- sc.redraw();\r
- }\r
- }\r
-\r
- });\r
- \r
- DropTarget target2 = new DropTarget(body, DND.DROP_COPY | DND.DROP_MOVE);\r
- target2.setTransfer(new Transfer[] { LocalObjectTransfer.getTransfer() });\r
- target2.addDropListener(new ChartDropTarget(body, null, this));\r
-\r
- }\r
-\r
- /**\r
- * Is the panel vertically oriented\r
- * @return Is the panel vertically oriented\r
- */\r
- public boolean isVertical() {\r
- return vertical;\r
- }\r
- \r
- /**\r
- * Adds chart after given element. If element == null, adds chart to the top.\r
- * \r
- * @param element To which place the chart will be placed. (null allowed)\r
- */\r
- public void addChart(Resource chartResource, ChartPanelElement element) {\r
- addChart(chartResource, element, true);\r
- }\r
-\r
- /**\r
- * Adds chart after given element. If element == null, adds chart to the top.\r
- * \r
- * @param element To which place the chart will be placed. (null allowed)\r
- * @param layout refresh layout. use with vertical layout. \r
- */\r
- public void addChart(Resource chartResource, ChartPanelElement element, boolean layout) {\r
- if(element == null)\r
- element = chartElements.get(chartElements.size() - 1);\r
- int index = chartElements.indexOf(element);\r
- if(index >= 0) {\r
- ChartPanelElement e = chartElements.get(index);\r
- ChartPanelElement newElement;\r
-\r
- if(charts.containsKey(chartResource)) {\r
- // Old element being moved to a new place\r
- newElement = charts.get(chartResource);\r
- int oldIndex = chartElements.indexOf(newElement);\r
- if(newElement.equals(element) || oldIndex == index - 1)\r
- return; // Not moving anywhere, do nothing\r
- Composite oldParent = newElement.getParent();\r
- newElement.setParent(e.getParent());\r
- oldParent.dispose();\r
- if(oldIndex < index)\r
- index--;\r
- chartElements.remove(newElement);\r
- } else {\r
- newElement = new ChartPanelElement(e.getParent(), this, chartResource, SWT.NONE);\r
- }\r
-\r
- // Add a new chart element to the location of the old element\r
- chartElements.add(index, newElement);\r
- charts.put(chartResource, newElement);\r
-\r
- ElementContainer elementHolder;\r
- // Move elements back after index\r
- for(int i = index + 1 /*indexes after the new element*/; i < chartElements.size(); i++) {\r
- e = chartElements.get(i);\r
- if(i == chartElements.size() - 1) {\r
- // last element (the empty element) element to a new container\r
- elementHolder = new ElementContainer(body, SWT.NONE);\r
- elementHolder.setBackground(new Color(elementHolder.getDisplay(), 0, 0, 255));\r
- elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)e.getLayout()));\r
- e.setParent(elementHolder);\r
- } else {\r
- // element to the next elements container\r
- elementHolder = (ElementContainer)chartElements.get(i + 1).getParent();\r
- e.setParent(elementHolder);\r
- }\r
- }\r
- \r
- layout();\r
- saveState();\r
- }\r
- }\r
-\r
- /**\r
- * Set a listener to listen if the chart resource has been removed.\r
- * If the resource has been removed, close also the chart element in this panel.\r
- * \r
- * @param chart Listened chart resource\r
- */\r
- private void setChartExistingListener(final Resource chart) {\r
- SimanticsUI.getSession().asyncRequest(new Read<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- return graph.hasStatement(chart);\r
- }\r
- }, new AsyncListener<Boolean>() {\r
-\r
- boolean disposed = false;\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph, Boolean result) {\r
- if(result != null && result == false && body != null && !body.isDisposed()) {\r
- body.getDisplay().asyncExec(new RunnableWithObject(chart){\r
- public void run() {\r
- removeChart((Resource)getObject());\r
- }\r
- }) ;\r
- disposed = true;\r
- }\r
- }\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph, Throwable throwable) {\r
- throwable.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return !disposed && !charts.containsKey(chart);\r
- }\r
- });\r
- }\r
-\r
- public ArrayList<ChartPanelElement> getElements() {\r
- return chartElements;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+
+import org.eclipse.jface.dialogs.IDialogSettings;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DropTarget;
+import org.eclipse.swt.dnd.DropTargetAdapter;
+import org.eclipse.swt.dnd.DropTargetEvent;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.IViewSite;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.part.ViewPart;
+import org.simantics.Simantics;
+import org.simantics.db.AsyncReadGraph;
+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.db.procedure.AsyncListener;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.internal.Activator;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.ui.dnd.LocalObjectTransfer;
+import org.simantics.utils.RunnableWithObject;
+
+/**
+ * Chart panel displays multiple charts in a single view. The view can be oriented
+ * vertically or horizontally, the default is vertical. Charts can be added, removed
+ * minimized or expanded. The order of the charts can be changed by dragging the charts.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ChartPanel extends ViewPart {
+
+ private Composite body;
+ private ScrolledComposite sc;
+
+ private IDialogSettings settings;
+ private LinkedHashMap<Resource, ChartPanelElement> charts;
+ private ArrayList<Resource> minimizedResources;
+
+ private ArrayList<ChartPanelElement> chartElements;
+
+ public static final String CHART_PANEL_SETTINGS = "CHART_PANEL_SETTINGS";
+ public static final String CHARTS = "CHART_PANEL_CHARTS";
+ public static final String MINIMIZED_CHARTS = "CHART_PANEL_MINIMIZED_CHARTS";
+ public static final String CHART_PANEL_ORIENTATION = "CHART_PANEL_ORIENTATION";
+
+ public static final String CHART_PANEL_VERTICAL = "CHART_PANEL_ORIENTATION_VERTICAL";
+ public static final String CHART_PANEL_HORIZONTAL = "CHART_PANEL_ORIENTATION_HORIZONTAL";
+
+ private boolean vertical = true;
+
+ /**
+ * Initialize the view. Load charts that have previously been open (if there are any).
+ */
+ @Override
+ public void init(IViewSite site, IMemento memento) throws PartInitException {
+ super.init(site, memento);
+
+ minimizedResources = new ArrayList<Resource>();
+
+ settings = Activator.getDefault().getDialogSettings().getSection(CHART_PANEL_SETTINGS);
+
+ // Initialize settings if there are no settings
+ if (settings == null) {
+ settings = Activator.getDefault().getDialogSettings().addNewSection(CHART_PANEL_SETTINGS);
+ }
+
+ if(settings.getArray(CHARTS) == null) {
+ String[] chartUris = new String[] {};
+ settings.put(CHARTS, chartUris);
+ }
+
+ if(settings.getArray(MINIMIZED_CHARTS) == null) {
+ String[] minimizedChartUris = new String[] {};
+ settings.put(MINIMIZED_CHARTS, minimizedChartUris);
+ }
+
+ // initialize chart lists
+ charts = new LinkedHashMap<Resource, ChartPanelElement>();
+
+ // add chart resources to chart lists from settings
+ try {
+ Simantics.getSession().syncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Resource chart = null;
+ String[] chartURIs = settings.getArray(CHARTS);
+ for(String uri : chartURIs) {
+ chart = graph.getPossibleResource(uri);
+ if(chart != null && graph.isInstanceOf(chart, jfree.Chart)) {
+ charts.put(chart, null);
+ setChartExistingListener(chart);
+ }
+ }
+
+ String[] minimizedUris = settings.getArray(MINIMIZED_CHARTS);
+ for(String uri : minimizedUris) {
+ chart = graph.getPossibleResource(uri);
+ if(chart != null && graph.isInstanceOf(chart, jfree.Chart)) {
+ minimizedResources.add(chart);
+ }
+ }
+ }
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+
+ // set the orientation of the panel
+ String orientation = settings.get(CHART_PANEL_ORIENTATION);
+ if(CHART_PANEL_VERTICAL.equals(orientation))
+ this.vertical = true;
+ else if(CHART_PANEL_HORIZONTAL.equals(orientation))
+ this.vertical = false;
+
+ }
+
+ /**
+ * Create a scrolled composite that will contain all the charts, then call the actual
+ * content creator.
+ */
+ @Override
+ public void createPartControl(Composite parent) {
+ sc = new ScrolledComposite(parent, SWT.NONE | SWT.H_SCROLL | SWT.V_SCROLL);
+ GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(sc);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(sc);
+ sc.setExpandHorizontal(true);
+ sc.setExpandVertical(true);
+ sc.getVerticalBar().setIncrement(sc.getVerticalBar().getIncrement()*3);
+ sc.getHorizontalBar().setIncrement(sc.getHorizontalBar().getIncrement()*3);
+
+ body = new Composite(sc, SWT.NONE);
+ GridLayoutFactory.fillDefaults().margins(3, 0).spacing(0, 0).applyTo(body);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(body);
+
+ sc.setContent(body);
+ createContents();
+
+ setupDropTarget();
+
+ }
+
+ /**
+ * Creates the contents of this chart panel.
+ * Removes all old contents before creating new content
+ */
+ private void createContents() {
+ chartElements = new ArrayList<ChartPanelElement>();
+
+ for(Control child : body.getChildren()) {
+ child.dispose();
+ }
+
+ // Set the initial layout
+ ElementContainer elementHolder;
+ for(Resource e : charts.keySet()) {
+ elementHolder = new ElementContainer(body, SWT.NONE);
+ elementHolder.setBackground(new Color(elementHolder.getDisplay(), 255, 0, 0));
+ ChartPanelElement element = new ChartPanelElement(elementHolder, this, e, SWT.NONE);
+ elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)element.getLayout()));
+ chartElements.add(element);
+ charts.put(e, element);
+ if(minimizedResources.contains(e)) {
+ element.toggleMinimize();
+ }
+ }
+
+ elementHolder = new ElementContainer(body, SWT.NONE);
+ elementHolder.setBackground(new Color(elementHolder.getDisplay(), 0, 255, 0));
+ ChartPanelElement element = new ChartPanelElement(elementHolder, this, null, SWT.NONE); // Last element is empty -> only the separator
+ elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)element.getLayout()));
+ chartElements.add(element);
+
+ layout();
+ saveState();
+
+ }
+
+ /**
+ * Lays out this panel (the body composite)
+ */
+ public void layout() {
+ if(vertical) {
+ GridLayoutFactory.fillDefaults().spacing(0, 0).applyTo(body);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(body);
+ } else {
+ // Need to calculate horizontal elements for gridLayout
+ int chartPanels = chartElements.size();
+ GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(chartPanels).applyTo(body);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(body);
+ }
+ body.layout();
+ sc.setMinSize(body.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ }
+
+ @Override
+ public void setFocus() {
+ if(!sc.isDisposed())
+ sc.setFocus();
+ }
+
+ @Override
+ public void saveState(IMemento memento) {
+ super.saveState(memento);
+ saveState();
+ }
+
+ /**
+ * Save the current state of the view to IDialogSettings
+ */
+ public void saveState() {
+ try {
+ Simantics.getSession().syncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ if (settings != null) {
+ String[] uris = new String[chartElements.size() - 1];
+ ArrayList<String> minimized = new ArrayList<String>();
+ minimizedResources.clear();
+ for(int i = 0; i < uris.length; i++) {
+ ChartPanelElement e = chartElements.get(i);
+ Resource r = e.getResource();
+ if(r != null) {
+ uris[i] = graph.getURI(r);
+ if(e.isMinimized()) {
+ minimized.add(uris[i]);
+ minimizedResources.add(r);
+ }
+ } else {
+ uris[i] = "";
+ }
+ }
+ settings.put(CHARTS, uris);
+ if(!minimized.isEmpty())
+ settings.put(MINIMIZED_CHARTS, minimized.toArray(new String[minimized.size()]));
+ else
+ settings.put(MINIMIZED_CHARTS, new String[0]);
+
+ if(vertical)
+ settings.put(CHART_PANEL_ORIENTATION, CHART_PANEL_VERTICAL);
+ else
+ settings.put(CHART_PANEL_ORIENTATION, CHART_PANEL_HORIZONTAL);
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Set the orientation for this chart panel.
+ *
+ * @param orientation Orientation (ChartPanel.CHART_PANEL_VERTICAL or ChartPanel.CHART_PANEL_HORIZONTAL)
+ */
+ public void setOrientation(String orientation) {
+ if(CHART_PANEL_VERTICAL.equals(orientation))
+ this.vertical = true;
+ else {
+ this.vertical = false;
+ }
+ createContents();
+ }
+
+ /**
+ * Removes a chart from this panel
+ *
+ * @param chart The chart to be removed
+ */
+ public void removeChart(Resource chart) {
+ ChartPanelElement element = charts.get(chart);
+ chartElements.remove(element);
+ element.getParent().dispose();
+ charts.remove(chart);
+ minimizedResources.remove(chart);
+ saveState();
+ layout();
+ }
+
+ /**
+ * Sets up drag-scrolling for a scrolled composite
+ *
+ * @param control
+ */
+ protected void setupDropTarget() {
+ DropTarget target = new DropTarget(sc, DND.DROP_MOVE);
+ target.setTransfer(new Transfer[] { LocalObjectTransfer.getTransfer() });
+
+ target.addDropListener(new DropTargetAdapter() {
+
+ private int activeMargin = 20;
+ private int moveAmount = 1;
+
+ @Override
+ public void dragOver(DropTargetEvent event) {
+ Point original = sc.getOrigin();
+ Point origin = sc.getOrigin();
+ Point pointer = sc.toControl(event.x, event.y);
+ Rectangle bounds = sc.getBounds();
+
+ if(pointer.y < activeMargin)
+ origin.y = origin.y - moveAmount;
+ else if(bounds.height - pointer.y < activeMargin)
+ origin.y = origin.y + moveAmount;
+ if(pointer.x < activeMargin)
+ origin.x = origin.x - moveAmount;
+ else if(bounds.width - pointer.x < activeMargin)
+ origin.x = origin.x + moveAmount;
+
+ if(origin != original) {
+ sc.setOrigin (origin.x, origin.y);
+ sc.redraw();
+ }
+ }
+
+ });
+
+ DropTarget target2 = new DropTarget(body, DND.DROP_COPY | DND.DROP_MOVE);
+ target2.setTransfer(new Transfer[] { LocalObjectTransfer.getTransfer() });
+ target2.addDropListener(new ChartDropTarget(body, null, this));
+
+ }
+
+ /**
+ * Is the panel vertically oriented
+ * @return Is the panel vertically oriented
+ */
+ public boolean isVertical() {
+ return vertical;
+ }
+
+ /**
+ * Adds chart after given element. If element == null, adds chart to the top.
+ *
+ * @param element To which place the chart will be placed. (null allowed)
+ */
+ public void addChart(Resource chartResource, ChartPanelElement element) {
+ addChart(chartResource, element, true);
+ }
+
+ /**
+ * Adds chart after given element. If element == null, adds chart to the top.
+ *
+ * @param element To which place the chart will be placed. (null allowed)
+ * @param layout refresh layout. use with vertical layout.
+ */
+ public void addChart(Resource chartResource, ChartPanelElement element, boolean layout) {
+ if(element == null)
+ element = chartElements.get(chartElements.size() - 1);
+ int index = chartElements.indexOf(element);
+ if(index >= 0) {
+ ChartPanelElement e = chartElements.get(index);
+ ChartPanelElement newElement;
+
+ if(charts.containsKey(chartResource)) {
+ // Old element being moved to a new place
+ newElement = charts.get(chartResource);
+ int oldIndex = chartElements.indexOf(newElement);
+ if(newElement.equals(element) || oldIndex == index - 1)
+ return; // Not moving anywhere, do nothing
+ Composite oldParent = newElement.getParent();
+ newElement.setParent(e.getParent());
+ oldParent.dispose();
+ if(oldIndex < index)
+ index--;
+ chartElements.remove(newElement);
+ } else {
+ newElement = new ChartPanelElement(e.getParent(), this, chartResource, SWT.NONE);
+ }
+
+ // Add a new chart element to the location of the old element
+ chartElements.add(index, newElement);
+ charts.put(chartResource, newElement);
+
+ ElementContainer elementHolder;
+ // Move elements back after index
+ for(int i = index + 1 /*indexes after the new element*/; i < chartElements.size(); i++) {
+ e = chartElements.get(i);
+ if(i == chartElements.size() - 1) {
+ // last element (the empty element) element to a new container
+ elementHolder = new ElementContainer(body, SWT.NONE);
+ elementHolder.setBackground(new Color(elementHolder.getDisplay(), 0, 0, 255));
+ elementHolder.setLayout(GridLayoutFactory.copyLayout((GridLayout)e.getLayout()));
+ e.setParent(elementHolder);
+ } else {
+ // element to the next elements container
+ elementHolder = (ElementContainer)chartElements.get(i + 1).getParent();
+ e.setParent(elementHolder);
+ }
+ }
+
+ layout();
+ saveState();
+ }
+ }
+
+ /**
+ * Set a listener to listen if the chart resource has been removed.
+ * If the resource has been removed, close also the chart element in this panel.
+ *
+ * @param chart Listened chart resource
+ */
+ private void setChartExistingListener(final Resource chart) {
+ Simantics.getSession().asyncRequest(new Read<Boolean>() {
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ return graph.hasStatement(chart);
+ }
+ }, new AsyncListener<Boolean>() {
+
+ boolean disposed = false;
+
+ @Override
+ public void execute(AsyncReadGraph graph, Boolean result) {
+ if(result != null && result == false && body != null && !body.isDisposed()) {
+ body.getDisplay().asyncExec(new RunnableWithObject(chart){
+ public void run() {
+ removeChart((Resource)getObject());
+ }
+ }) ;
+ disposed = true;
+ }
+ }
+
+ @Override
+ public void exception(AsyncReadGraph graph, Throwable throwable) {
+ throwable.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return !disposed && !charts.containsKey(chart);
+ }
+ });
+ }
+
+ public ArrayList<ChartPanelElement> getElements() {
+ return chartElements;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.jface.viewers.StructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.dnd.DND;\r
-import org.eclipse.swt.dnd.DragSource;\r
-import org.eclipse.swt.dnd.DragSourceEvent;\r
-import org.eclipse.swt.dnd.DragSourceListener;\r
-import org.eclipse.swt.dnd.Transfer;\r
-import org.eclipse.swt.events.DisposeEvent;\r
-import org.eclipse.swt.events.DisposeListener;\r
-import org.eclipse.swt.events.PaintEvent;\r
-import org.eclipse.swt.events.PaintListener;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.graphics.Color;\r
-import org.eclipse.swt.graphics.GC;\r
-import org.eclipse.swt.graphics.Image;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Canvas;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Event;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.ToolBar;\r
-import org.eclipse.swt.widgets.ToolItem;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.internal.Activator;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.dnd.LocalObjectTransfer;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-/**\r
- * Header of a chart element in {@link ChartPanel}. Only this header is\r
- * shown if a chart is minimized. If a chart is expanded, this header is added\r
- * to the charts {@link ChartPanelElement}. \r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ChartPanelHeader extends Composite {\r
-\r
- public static int HEADER_MINIMUM_WIDTH = 250;\r
- private ChartPanelElement element;\r
- private Resource resource;\r
- private Label name;\r
- private Canvas iconCanvas;\r
- private Image icon;\r
- private ToolItem minimize, remove;\r
- private Color defaultColor, darker, evenDarker;\r
- private Image gradientBackgroundImage, borderImage;\r
-\r
- private static ImageDescriptor closeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/close.gif"));\r
- private static Image closeImage = closeDescriptor.createImage();\r
-\r
- private static ImageDescriptor minimizeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/minimize.gif"));\r
- private static Image minimizeImage = minimizeDescriptor.createImage();\r
-\r
- private static ImageDescriptor maximizeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/maximize.gif"));\r
- private static Image maximizeImage = maximizeDescriptor.createImage();\r
-\r
- private static ImageDescriptor lineChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_line_light.png"));\r
- private static Image lineChartImage = lineChartDescriptor.createImage();\r
-\r
- private static ImageDescriptor barChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar_light.png"));\r
- private static Image barChartImage = barChartDescriptor.createImage();\r
-\r
- private static ImageDescriptor pieChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_pie_light.png"));\r
- private static Image pieChartImage = pieChartDescriptor.createImage();\r
-\r
-\r
- /**\r
- * Chart panel header with minimize and close buttons.\r
- * \r
- * @param parent The composite where the header is added\r
- * @param panel The {@link ChartPanel} containing the header\r
- * @param name The name of the chart\r
- * @param style he Style of the created chart element\r
- */\r
- public ChartPanelHeader(Composite c, ChartPanelElement element, Resource chartResource, int style) {\r
- super(c, style);\r
- this.resource = chartResource;\r
- this.element = element;\r
-\r
- GridLayoutFactory.fillDefaults().margins(3, 0).numColumns(3).applyTo(this);\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(this);\r
-\r
- // Colors\r
-\r
- // Chart icon\r
- iconCanvas = new Canvas (this, SWT.NONE);\r
- GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).hint(16, 16).applyTo(iconCanvas);\r
- iconCanvas.addPaintListener (new PaintListener() {\r
-\r
- @Override\r
- public void paintControl(PaintEvent e) {\r
- if(icon != null)\r
- e.gc.drawImage (icon, 0, 0); \r
- }\r
- });\r
-\r
- // Label for the chart name (also minimize/expand)\r
- name = new Label(this, SWT.NONE);\r
-\r
- try {\r
- // name updater\r
- Pair<String, Image> result = SimanticsUI.getSession().syncRequest(new Read<Pair<String, Image>>() {\r
-\r
- @Override\r
- public Pair<String, Image> perform(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- String label = graph.getPossibleRelatedValue(resource, l0.HasLabel);\r
- Image image = null;\r
- Resource plot = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, jfree.Plot));\r
- if(plot != null) {\r
- if(graph.isInstanceOf(plot, jfree.CategoryPlot))\r
- image = barChartImage;\r
- else if(graph.isInstanceOf(plot, jfree.PiePlot))\r
- image = pieChartImage;\r
- else\r
- image = lineChartImage;\r
- }\r
- return new Pair<String, Image>(label, image);\r
- }\r
-\r
- }, new Listener<Pair<String, Image>>() {\r
-\r
- @Override\r
- public void execute(final Pair<String, Image> result) {\r
- if(result == null)\r
- return;\r
-\r
- name.getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- if(!name.isDisposed() && result.first != null)\r
- name.setText(result.first);\r
-\r
- if(!iconCanvas.isDisposed() && result.second != null) {\r
- icon = result.second;\r
- iconCanvas.redraw();\r
- ChartPanelHeader.this.layout();\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return name.isDisposed();\r
- }\r
-\r
- });\r
- name.setText(result.first);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- name.setText("No label");\r
- }\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(name);\r
-\r
- ToolBar toolbar = new ToolBar(this, SWT.FLAT);\r
- // item for minimizing/expanding chart\r
- minimize = new ToolItem(toolbar, SWT.PUSH);\r
- minimize.addSelectionListener(new MinimizeListener());\r
- if(isMinimized()) {\r
- minimize.setToolTipText("Expand");\r
- minimize.setImage(maximizeImage);\r
- } else {\r
- minimize.setToolTipText("Minimize");\r
- minimize.setImage(minimizeImage);\r
- }\r
-\r
- // item for closing/removing the chart\r
- remove = new ToolItem(toolbar, SWT.PUSH);\r
- remove.setImage(closeImage);\r
- remove.addSelectionListener(new RemoveChartListener());\r
- remove.setToolTipText("Remove");\r
-\r
-\r
- /* ********************************\r
- * DnD \r
- * ********************************/\r
-\r
- // Allow data to be copied or moved from the drag source\r
- int operations = DND.DROP_MOVE;\r
- source = new DragSource(name, operations);\r
-\r
- // Provide data in Text format\r
- Transfer[] types = new Transfer[] { LocalObjectTransfer.getTransfer() };\r
- source.setTransfer(types);\r
- dragSourceListener = new DragSourceListener() {\r
-\r
- @Override\r
- public void dragStart(DragSourceEvent event) {\r
- if(name.isDisposed())\r
- event.doit = false;\r
- event.detail = DND.DROP_LINK;\r
-\r
- }\r
-\r
- @Override\r
- public void dragSetData(DragSourceEvent event) {\r
- event.data = new StructuredSelection(resource);\r
- }\r
-\r
- @Override\r
- public void dragFinished(DragSourceEvent event) {\r
- }\r
- }; \r
- source.addDragListener(dragSourceListener);\r
-\r
- name.addDisposeListener(new DisposeListener() {\r
-\r
- @Override\r
- public void widgetDisposed(DisposeEvent e) {\r
- if(dragSourceListener != null && source != null && !source.isDisposed()) {\r
- source.removeDragListener(dragSourceListener);\r
- } \r
- }\r
- });\r
- this.setBackgroundImage(getGradientBackgroundImage());\r
- this.setBackgroundMode(SWT.INHERIT_FORCE);\r
-\r
- this.addListener(SWT.MouseEnter, new EnterListener());\r
- this.addListener(SWT.MouseExit, new ExitListener());\r
-\r
- for(Control child : this.getChildren()) {\r
- child.addListener(SWT.MouseEnter, new EnterListener());\r
- child.addListener(SWT.MouseExit, new ExitListener());\r
-\r
- }\r
- }\r
-\r
- private class EnterListener implements org.eclipse.swt.widgets.Listener {\r
- public void handleEvent(Event event) {\r
- ChartPanelHeader.this.setBackgroundImage(getHighlightedGradientBackgroundImage());\r
- }\r
- }\r
-\r
- private class ExitListener implements org.eclipse.swt.widgets.Listener {\r
- public void handleEvent(Event event) {\r
- ChartPanelHeader.this.setBackgroundImage(getGradientBackgroundImage());\r
- }\r
- }\r
-\r
- private void createColors() {\r
- if(defaultColor == null) {\r
- defaultColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);\r
- try {\r
- defaultColor = new Color(getDisplay(), defaultColor.getRed() + 500, defaultColor.getGreen() + 10, defaultColor.getBlue() + 10);\r
- } catch (IllegalArgumentException e) {\r
- // Do nothing, use the default color\r
- }\r
- }\r
-\r
- if(darker == null) {\r
- try {\r
- darker = new Color(getDisplay(), defaultColor.getRed() - 30, defaultColor.getGreen() - 30, defaultColor.getBlue() - 30);\r
- } catch (IllegalArgumentException e) {\r
- // Do nothing, use the default color\r
- darker = defaultColor;\r
- }\r
- }\r
- \r
- if(evenDarker == null) {\r
- try {\r
- evenDarker = new Color(getDisplay(), defaultColor.getRed() - 50, defaultColor.getGreen() - 50, defaultColor.getBlue() - 50);\r
- } catch (IllegalArgumentException e) {\r
- // Do nothing, use the default color\r
- evenDarker = defaultColor;\r
- }\r
- }\r
-\r
- }\r
-\r
- private Image getHighlightedGradientBackgroundImage() {\r
- createColors();\r
- this.layout();\r
- Point size = this.getSize();\r
-\r
- borderImage = new Image(this.getDisplay(), 1, Math.max(1, size.y));\r
- GC gc = new GC(borderImage);\r
- gc.setForeground(defaultColor);\r
- gc.setBackground(evenDarker);\r
- gc.fillGradientRectangle(0, 0, 1, size.y, true);\r
- gc.dispose();\r
-\r
- return borderImage;\r
- }\r
-\r
- private Image getGradientBackgroundImage() {\r
- createColors();\r
- this.layout();\r
- Point size = this.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- if(gradientBackgroundImage == null) {\r
- gradientBackgroundImage = new Image(this.getDisplay(), 1, Math.max(1, size.y));\r
- GC gc = new GC(gradientBackgroundImage);\r
- gc.setForeground(defaultColor);\r
- gc.setBackground(darker);\r
- gc.fillGradientRectangle(0, 0, 1, size.y, true);\r
- gc.dispose();\r
- }\r
-\r
- return gradientBackgroundImage;\r
- }\r
-\r
- private DragSourceListener dragSourceListener;\r
- private DragSource source;\r
-\r
- /**\r
- * Return true if this element is minimized, false if expanded\r
- * @return true if this element is minimized, false if expanded\r
- */\r
- private boolean isMinimized() {\r
- return element.isMinimized();\r
- }\r
-\r
- /**\r
- * Listener to minimize chart button. Expands and minimizes \r
- * the chart of this header.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class MinimizeListener implements SelectionListener {\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- if(ChartPanelHeader.this.isDisposed())\r
- return;\r
-\r
- element.toggleMinimize(true);\r
-\r
- if(!name.isDisposed() && !minimize.isDisposed()) {\r
- if(isMinimized()) {\r
- minimize.setToolTipText("Expand");\r
- } else {\r
- minimize.setToolTipText("Minimize");\r
- }\r
- } \r
- }\r
-\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- widgetSelected(e);\r
- }\r
-\r
- }\r
-\r
- /**\r
- * Listener for removing this chart from the chart panel.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class RemoveChartListener implements SelectionListener {\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- if(!ChartPanelHeader.this.isDisposed()) {\r
- element.remove();\r
- }\r
- }\r
-\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- widgetSelected(e);\r
- }\r
-\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.dnd.DND;
+import org.eclipse.swt.dnd.DragSource;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.swt.dnd.DragSourceListener;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.PaintEvent;
+import org.eclipse.swt.events.PaintListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.GC;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Canvas;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.ToolBar;
+import org.eclipse.swt.widgets.ToolItem;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.PossibleObjectWithType;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.internal.Activator;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.ui.dnd.LocalObjectTransfer;
+import org.simantics.utils.datastructures.Pair;
+
+/**
+ * Header of a chart element in {@link ChartPanel}. Only this header is
+ * shown if a chart is minimized. If a chart is expanded, this header is added
+ * to the charts {@link ChartPanelElement}.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ChartPanelHeader extends Composite {
+
+ public static int HEADER_MINIMUM_WIDTH = 250;
+ private ChartPanelElement element;
+ private Resource resource;
+ private Label name;
+ private Canvas iconCanvas;
+ private Image icon;
+ private ToolItem minimize, remove;
+ private Color defaultColor, darker, evenDarker;
+ private Image gradientBackgroundImage, borderImage;
+
+ private static ImageDescriptor closeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/close.gif"));
+ private static Image closeImage = closeDescriptor.createImage();
+
+ private static ImageDescriptor minimizeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/minimize.gif"));
+ private static Image minimizeImage = minimizeDescriptor.createImage();
+
+ private static ImageDescriptor maximizeDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/maximize.gif"));
+ private static Image maximizeImage = maximizeDescriptor.createImage();
+
+ private static ImageDescriptor lineChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_line_light.png"));
+ private static Image lineChartImage = lineChartDescriptor.createImage();
+
+ private static ImageDescriptor barChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_bar_light.png"));
+ private static Image barChartImage = barChartDescriptor.createImage();
+
+ private static ImageDescriptor pieChartDescriptor = ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/chart_pie_light.png"));
+ private static Image pieChartImage = pieChartDescriptor.createImage();
+
+
+ /**
+ * Chart panel header with minimize and close buttons.
+ *
+ * @param parent The composite where the header is added
+ * @param panel The {@link ChartPanel} containing the header
+ * @param name The name of the chart
+ * @param style he Style of the created chart element
+ */
+ public ChartPanelHeader(Composite c, ChartPanelElement element, Resource chartResource, int style) {
+ super(c, style);
+ this.resource = chartResource;
+ this.element = element;
+
+ GridLayoutFactory.fillDefaults().margins(3, 0).numColumns(3).applyTo(this);
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(this);
+
+ // Colors
+
+ // Chart icon
+ iconCanvas = new Canvas (this, SWT.NONE);
+ GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).hint(16, 16).applyTo(iconCanvas);
+ iconCanvas.addPaintListener (new PaintListener() {
+
+ @Override
+ public void paintControl(PaintEvent e) {
+ if(icon != null)
+ e.gc.drawImage (icon, 0, 0);
+ }
+ });
+
+ // Label for the chart name (also minimize/expand)
+ name = new Label(this, SWT.NONE);
+
+ try {
+ // name updater
+ Pair<String, Image> result = Simantics.getSession().syncRequest(new Read<Pair<String, Image>>() {
+
+ @Override
+ public Pair<String, Image> perform(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ String label = graph.getPossibleRelatedValue(resource, l0.HasLabel);
+ Image image = null;
+ Resource plot = graph.syncRequest(new PossibleObjectWithType(resource, l0.ConsistsOf, jfree.Plot));
+ if(plot != null) {
+ if(graph.isInstanceOf(plot, jfree.CategoryPlot))
+ image = barChartImage;
+ else if(graph.isInstanceOf(plot, jfree.PiePlot))
+ image = pieChartImage;
+ else
+ image = lineChartImage;
+ }
+ return new Pair<String, Image>(label, image);
+ }
+
+ }, new Listener<Pair<String, Image>>() {
+
+ @Override
+ public void execute(final Pair<String, Image> result) {
+ if(result == null)
+ return;
+
+ name.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if(!name.isDisposed() && result.first != null)
+ name.setText(result.first);
+
+ if(!iconCanvas.isDisposed() && result.second != null) {
+ icon = result.second;
+ iconCanvas.redraw();
+ ChartPanelHeader.this.layout();
+ }
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return name.isDisposed();
+ }
+
+ });
+ name.setText(result.first);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ name.setText("No label");
+ }
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(name);
+
+ ToolBar toolbar = new ToolBar(this, SWT.FLAT);
+ // item for minimizing/expanding chart
+ minimize = new ToolItem(toolbar, SWT.PUSH);
+ minimize.addSelectionListener(new MinimizeListener());
+ if(isMinimized()) {
+ minimize.setToolTipText("Expand");
+ minimize.setImage(maximizeImage);
+ } else {
+ minimize.setToolTipText("Minimize");
+ minimize.setImage(minimizeImage);
+ }
+
+ // item for closing/removing the chart
+ remove = new ToolItem(toolbar, SWT.PUSH);
+ remove.setImage(closeImage);
+ remove.addSelectionListener(new RemoveChartListener());
+ remove.setToolTipText("Remove");
+
+
+ /* ********************************
+ * DnD
+ * ********************************/
+
+ // Allow data to be copied or moved from the drag source
+ int operations = DND.DROP_MOVE;
+ source = new DragSource(name, operations);
+
+ // Provide data in Text format
+ Transfer[] types = new Transfer[] { LocalObjectTransfer.getTransfer() };
+ source.setTransfer(types);
+ dragSourceListener = new DragSourceListener() {
+
+ @Override
+ public void dragStart(DragSourceEvent event) {
+ if(name.isDisposed())
+ event.doit = false;
+ event.detail = DND.DROP_LINK;
+
+ }
+
+ @Override
+ public void dragSetData(DragSourceEvent event) {
+ event.data = new StructuredSelection(resource);
+ }
+
+ @Override
+ public void dragFinished(DragSourceEvent event) {
+ }
+ };
+ source.addDragListener(dragSourceListener);
+
+ name.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(DisposeEvent e) {
+ if(dragSourceListener != null && source != null && !source.isDisposed()) {
+ source.removeDragListener(dragSourceListener);
+ }
+ }
+ });
+ this.setBackgroundImage(getGradientBackgroundImage());
+ this.setBackgroundMode(SWT.INHERIT_FORCE);
+
+ this.addListener(SWT.MouseEnter, new EnterListener());
+ this.addListener(SWT.MouseExit, new ExitListener());
+
+ for(Control child : this.getChildren()) {
+ child.addListener(SWT.MouseEnter, new EnterListener());
+ child.addListener(SWT.MouseExit, new ExitListener());
+
+ }
+ }
+
+ private class EnterListener implements org.eclipse.swt.widgets.Listener {
+ public void handleEvent(Event event) {
+ ChartPanelHeader.this.setBackgroundImage(getHighlightedGradientBackgroundImage());
+ }
+ }
+
+ private class ExitListener implements org.eclipse.swt.widgets.Listener {
+ public void handleEvent(Event event) {
+ ChartPanelHeader.this.setBackgroundImage(getGradientBackgroundImage());
+ }
+ }
+
+ private void createColors() {
+ if(defaultColor == null) {
+ defaultColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
+ try {
+ defaultColor = new Color(getDisplay(), defaultColor.getRed() + 500, defaultColor.getGreen() + 10, defaultColor.getBlue() + 10);
+ } catch (IllegalArgumentException e) {
+ // Do nothing, use the default color
+ }
+ }
+
+ if(darker == null) {
+ try {
+ darker = new Color(getDisplay(), defaultColor.getRed() - 30, defaultColor.getGreen() - 30, defaultColor.getBlue() - 30);
+ } catch (IllegalArgumentException e) {
+ // Do nothing, use the default color
+ darker = defaultColor;
+ }
+ }
+
+ if(evenDarker == null) {
+ try {
+ evenDarker = new Color(getDisplay(), defaultColor.getRed() - 50, defaultColor.getGreen() - 50, defaultColor.getBlue() - 50);
+ } catch (IllegalArgumentException e) {
+ // Do nothing, use the default color
+ evenDarker = defaultColor;
+ }
+ }
+
+ }
+
+ private Image getHighlightedGradientBackgroundImage() {
+ createColors();
+ this.layout();
+ Point size = this.getSize();
+
+ borderImage = new Image(this.getDisplay(), 1, Math.max(1, size.y));
+ GC gc = new GC(borderImage);
+ gc.setForeground(defaultColor);
+ gc.setBackground(evenDarker);
+ gc.fillGradientRectangle(0, 0, 1, size.y, true);
+ gc.dispose();
+
+ return borderImage;
+ }
+
+ private Image getGradientBackgroundImage() {
+ createColors();
+ this.layout();
+ Point size = this.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ if(gradientBackgroundImage == null) {
+ gradientBackgroundImage = new Image(this.getDisplay(), 1, Math.max(1, size.y));
+ GC gc = new GC(gradientBackgroundImage);
+ gc.setForeground(defaultColor);
+ gc.setBackground(darker);
+ gc.fillGradientRectangle(0, 0, 1, size.y, true);
+ gc.dispose();
+ }
+
+ return gradientBackgroundImage;
+ }
+
+ private DragSourceListener dragSourceListener;
+ private DragSource source;
+
+ /**
+ * Return true if this element is minimized, false if expanded
+ * @return true if this element is minimized, false if expanded
+ */
+ private boolean isMinimized() {
+ return element.isMinimized();
+ }
+
+ /**
+ * Listener to minimize chart button. Expands and minimizes
+ * the chart of this header.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+ private class MinimizeListener implements SelectionListener {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if(ChartPanelHeader.this.isDisposed())
+ return;
+
+ element.toggleMinimize(true);
+
+ if(!name.isDisposed() && !minimize.isDisposed()) {
+ if(isMinimized()) {
+ minimize.setToolTipText("Expand");
+ } else {
+ minimize.setToolTipText("Minimize");
+ }
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ widgetSelected(e);
+ }
+
+ }
+
+ /**
+ * Listener for removing this chart from the chart panel.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+ private class RemoveChartListener implements SelectionListener {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ if(!ChartPanelHeader.this.isDisposed()) {
+ element.remove();
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ widgetSelected(e);
+ }
+
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart;\r
-\r
-import java.util.HashMap;\r
-\r
-import javax.swing.SwingUtilities;\r
-\r
-import org.jfree.chart.JFreeChart;\r
-import org.jfree.chart.axis.Axis;\r
-import org.jfree.chart.plot.Plot;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Abstract plot class for all JFreeChart plots\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public abstract class AbstractPlot implements IPlot {\r
-\r
- protected Resource resource;\r
- protected Plot plot;\r
- protected PlotProperties currentProperties;\r
- protected PlotPropertyListener listener;\r
- protected org.jfree.chart.JFreeChart jfreechart;\r
-\r
- public AbstractPlot(ReadGraph graph, Resource resource) {\r
- this.resource = resource;\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- if(currentProperties != null) {\r
- for(IAxis axis : currentProperties.ranges)\r
- axis.dispose();\r
-\r
- for(IAxis axis : currentProperties.domains)\r
- axis.dispose();\r
-\r
- for(IDataset dataset : currentProperties.datasets)\r
- dataset.dispose();\r
- }\r
- if(listener != null)\r
- listener.dispose();\r
- }\r
-\r
- @Override\r
- public Resource getResource() {\r
- return resource;\r
- }\r
- \r
- @Override\r
- public void setJFreeChart(JFreeChart jfreechart) {\r
- this.jfreechart = jfreechart;\r
- }\r
- \r
- public org.jfree.chart.JFreeChart getJfreechart() {\r
- return jfreechart;\r
- }\r
- \r
- public PlotProperties getPlotProperties() {\r
- return currentProperties;\r
- }\r
-\r
- protected abstract Plot newPlot();\r
- protected void setPlotProperties(PlotProperties properties) {\r
- this.currentProperties = properties;\r
- }\r
- protected abstract void getOtherProperties(ReadGraph graph, PlotProperties properties) throws DatabaseException;\r
-\r
- @Override\r
- public Plot getPlot() {\r
- if(plot == null)\r
- plot = newPlot();\r
-\r
- if(listener == null || listener.isDisposed()) {\r
- listener = new PlotPropertyListener();\r
- SimanticsUI.getSession().asyncRequest(new PlotPropertyQuery(), listener);\r
- }\r
-\r
- return plot;\r
- }\r
- \r
- protected IDataset getDataset(ReadGraph graph, Resource datasetResource) throws DatabaseException{\r
- return graph.adapt(datasetResource, IDataset.class);\r
- }\r
- \r
- @Override\r
- public void configurePlot(PlotProperties properties) {\r
- \r
- }\r
-\r
- protected class PlotPropertyQuery implements Read<PlotProperties> {\r
- \r
- public PlotPropertyQuery() {\r
- \r
- }\r
-\r
- @Override\r
- public PlotProperties perform(ReadGraph graph) throws DatabaseException {\r
-\r
- PlotProperties properties = new PlotProperties();\r
-\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- HashMap<Resource, IAxis> axisMap = new HashMap<Resource, IAxis>();\r
-\r
- // Get all range axis\r
- Resource rangeList = graph.getPossibleObject(resource, jfree.Plot_rangeAxisList);\r
- if(rangeList != null) {\r
- for(Resource axisResource : ListUtils.toList(graph, rangeList)) {\r
- IAxis axis = graph.adapt(axisResource, IAxis.class);\r
- if(axis.getAxis() instanceof Axis) {\r
- properties.ranges.add(axis);\r
- axisMap.put(axisResource, axis);\r
- }\r
- }\r
- }\r
-\r
- // Get all domain axis\r
- // There usually is only one domain axis, but this supports also multiple domain axis\r
- for(Resource axisResource : graph.syncRequest(new ObjectsWithType(resource, jfree.Plot_domainAxis, jfree.Axis))) {\r
- IAxis axis = graph.adapt(axisResource, IAxis.class);\r
- if(axis.getAxis() instanceof Axis) {\r
- properties.domains.add(axis);\r
- axisMap.put(axisResource, axis);\r
- }\r
- }\r
-\r
- // Get all datasets and map them to axis\r
- for(Resource datasetResource : graph.syncRequest(new ObjectsWithType(resource, l0.ConsistsOf, jfree.Dataset))) {\r
- IDataset dataset = getDataset(graph, datasetResource);\r
- if(dataset != null) {\r
- properties.datasets.add(dataset);\r
- Resource axisResource = graph.getPossibleObject(datasetResource, jfree.Dataset_mapToRangeAxis);\r
- IAxis axis;\r
- if(axisMap.containsKey(axisResource)) {\r
- axis = axisMap.get(axisResource);\r
- properties.rangeMappings.put(dataset, axis);\r
- }\r
-\r
- axisResource = graph.getPossibleObject(datasetResource, jfree.Dataset_mapToDomainAxis);\r
- if(axisMap.containsKey(axisResource)) {\r
- axis = axisMap.get(axisResource);\r
- properties.domainMappings.put(dataset, axis);\r
- }\r
- }\r
- }\r
- getOtherProperties(graph, properties);\r
- return properties;\r
-\r
- }\r
- }\r
- \r
- protected class PlotPropertyListener implements Listener<PlotProperties> {\r
-\r
- private boolean disposed = false;\r
- \r
- public PlotPropertyListener() {\r
- \r
- }\r
-\r
- public void dispose() {\r
- disposed = true;\r
- }\r
- @Override\r
- public void execute(final PlotProperties result) {\r
- SwingUtilities.invokeLater(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- setPlotProperties(result);\r
- configurePlot(result);\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
-\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart.chart;
+
+import java.util.HashMap;
+
+import javax.swing.SwingUtilities;
+
+import org.jfree.chart.JFreeChart;
+import org.jfree.chart.axis.Axis;
+import org.jfree.chart.plot.Plot;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+
+/**
+ * Abstract plot class for all JFreeChart plots
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public abstract class AbstractPlot implements IPlot {
+
+ protected Resource resource;
+ protected Plot plot;
+ protected PlotProperties currentProperties;
+ protected PlotPropertyListener listener;
+ protected org.jfree.chart.JFreeChart jfreechart;
+
+ public AbstractPlot(ReadGraph graph, Resource resource) {
+ this.resource = resource;
+ }
+
+ @Override
+ public void dispose() {
+ if(currentProperties != null) {
+ for(IAxis axis : currentProperties.ranges)
+ axis.dispose();
+
+ for(IAxis axis : currentProperties.domains)
+ axis.dispose();
+
+ for(IDataset dataset : currentProperties.datasets)
+ dataset.dispose();
+ }
+ if(listener != null)
+ listener.dispose();
+ }
+
+ @Override
+ public Resource getResource() {
+ return resource;
+ }
+
+ @Override
+ public void setJFreeChart(JFreeChart jfreechart) {
+ this.jfreechart = jfreechart;
+ }
+
+ public org.jfree.chart.JFreeChart getJfreechart() {
+ return jfreechart;
+ }
+
+ public PlotProperties getPlotProperties() {
+ return currentProperties;
+ }
+
+ protected abstract Plot newPlot();
+ protected void setPlotProperties(PlotProperties properties) {
+ this.currentProperties = properties;
+ }
+ protected abstract void getOtherProperties(ReadGraph graph, PlotProperties properties) throws DatabaseException;
+
+ @Override
+ public Plot getPlot() {
+ if(plot == null)
+ plot = newPlot();
+
+ if(listener == null || listener.isDisposed()) {
+ listener = new PlotPropertyListener();
+ Simantics.getSession().asyncRequest(new PlotPropertyQuery(), listener);
+ }
+
+ return plot;
+ }
+
+ protected IDataset getDataset(ReadGraph graph, Resource datasetResource) throws DatabaseException{
+ return graph.adapt(datasetResource, IDataset.class);
+ }
+
+ @Override
+ public void configurePlot(PlotProperties properties) {
+
+ }
+
+ protected class PlotPropertyQuery implements Read<PlotProperties> {
+
+ public PlotPropertyQuery() {
+
+ }
+
+ @Override
+ public PlotProperties perform(ReadGraph graph) throws DatabaseException {
+
+ PlotProperties properties = new PlotProperties();
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ HashMap<Resource, IAxis> axisMap = new HashMap<Resource, IAxis>();
+
+ // Get all range axis
+ Resource rangeList = graph.getPossibleObject(resource, jfree.Plot_rangeAxisList);
+ if(rangeList != null) {
+ for(Resource axisResource : ListUtils.toList(graph, rangeList)) {
+ IAxis axis = graph.adapt(axisResource, IAxis.class);
+ if(axis.getAxis() instanceof Axis) {
+ properties.ranges.add(axis);
+ axisMap.put(axisResource, axis);
+ }
+ }
+ }
+
+ // Get all domain axis
+ // There usually is only one domain axis, but this supports also multiple domain axis
+ for(Resource axisResource : graph.syncRequest(new ObjectsWithType(resource, jfree.Plot_domainAxis, jfree.Axis))) {
+ IAxis axis = graph.adapt(axisResource, IAxis.class);
+ if(axis.getAxis() instanceof Axis) {
+ properties.domains.add(axis);
+ axisMap.put(axisResource, axis);
+ }
+ }
+
+ // Get all datasets and map them to axis
+ for(Resource datasetResource : graph.syncRequest(new ObjectsWithType(resource, l0.ConsistsOf, jfree.Dataset))) {
+ IDataset dataset = getDataset(graph, datasetResource);
+ if(dataset != null) {
+ properties.datasets.add(dataset);
+ Resource axisResource = graph.getPossibleObject(datasetResource, jfree.Dataset_mapToRangeAxis);
+ IAxis axis;
+ if(axisMap.containsKey(axisResource)) {
+ axis = axisMap.get(axisResource);
+ properties.rangeMappings.put(dataset, axis);
+ }
+
+ axisResource = graph.getPossibleObject(datasetResource, jfree.Dataset_mapToDomainAxis);
+ if(axisMap.containsKey(axisResource)) {
+ axis = axisMap.get(axisResource);
+ properties.domainMappings.put(dataset, axis);
+ }
+ }
+ }
+ getOtherProperties(graph, properties);
+ return properties;
+
+ }
+ }
+
+ protected class PlotPropertyListener implements Listener<PlotProperties> {
+
+ private boolean disposed = false;
+
+ public PlotPropertyListener() {
+
+ }
+
+ public void dispose() {
+ disposed = true;
+ }
+ @Override
+ public void execute(final PlotProperties result) {
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run() {
+ setPlotProperties(result);
+ configurePlot(result);
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart;\r
-\r
-import java.awt.Frame;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.awt.SWT_AWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.jfree.chart.ChartPanel;\r
-import org.jfree.chart.JFreeChart;\r
-import org.simantics.Simantics;\r
-import org.simantics.db.AsyncReadGraph;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.AsyncListener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.RunnableWithObject;\r
-\r
-/**\r
- * Composite containing a single chart defined by a JFreeChart.Chart\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ChartComposite extends Composite {\r
-\r
- private Frame frame;\r
- private ChartPanel panel;\r
- private Composite composite;\r
- private IJFreeChart chart;\r
-\r
- /**\r
- * A new ChartComposite with a definition in chartResourceURI\r
- * @param parent Composite\r
- * @param chartResourceURI URI for a JFreeChart.Chart definition\r
- * @param style SWT style\r
- */\r
- public ChartComposite(Composite parent, final String chartResourceURI, int style) {\r
- super(parent, style | SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
-\r
- try {\r
- Resource chartResource = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return graph.getPossibleResource(chartResourceURI);\r
- }\r
-\r
- });\r
- if(chartResource != null)\r
- CreateContent(chartResource);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- /**\r
- * A new ChartComposite with a chartResource definition\r
- * @param parent Composite\r
- * @param chartResource JFreeChart.Chart resource\r
- * @param style SWT style\r
- */\r
- public ChartComposite(Composite parent, final Resource chartResource, int style) {\r
- super(parent, style | SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
- CreateContent(chartResource);\r
- }\r
-\r
- /**\r
- * Creates and displays the chart defined in chartResource\r
- * @param chartResource\r
- */\r
- private void CreateContent(final Resource chartResource) {\r
- composite = this;\r
-\r
- GridLayoutFactory.fillDefaults().applyTo(composite);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- frame = SWT_AWT.new_Frame(composite);\r
-\r
- // Add a listener displaying the contents of the chart. Chart is re-drawn if the definition changes\r
- Simantics.getSession().asyncRequest(new Read<IJFreeChart>() {\r
-\r
- @Override\r
- public IJFreeChart perform(ReadGraph graph) throws DatabaseException {\r
- // Adapt chartResource to a chart (XY, pie, bar, ...)\r
- if(graph.isInstanceOf(chartResource, JFreeChartResource.getInstance(graph).Chart)) {\r
- if(chart != null)\r
- chart.dispose();\r
- chart = graph.adapt(chartResource, IJFreeChart.class);\r
- return chart;\r
- } else {\r
- return null;\r
- }\r
- }\r
-\r
- } , new AsyncListener<IJFreeChart>() {\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return composite.isDisposed();\r
- }\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph, IJFreeChart chart) {\r
- if(chart == null || composite.isDisposed())\r
- return;\r
- \r
- JFreeChart jfreeChart = chart.getChart();\r
- // Display the result chart\r
- if (composite.isDisposed())\r
- return;\r
- composite.getDisplay().asyncExec(new RunnableWithObject(jfreeChart) {\r
-\r
- @Override\r
- public void run() {\r
- if(composite.isDisposed())\r
- return;\r
- if(panel != null)\r
- frame.remove(panel);\r
- composite.layout();\r
- JFreeChart chart = (JFreeChart)getObject();\r
- //panel = new ChartPanel(chart, false, true, true, true, true);\r
- panel = new ChartPanel(chart,\r
- ChartPanel.DEFAULT_WIDTH,\r
- ChartPanel.DEFAULT_HEIGHT,\r
- ChartPanel.DEFAULT_MINIMUM_DRAW_WIDTH,\r
- ChartPanel.DEFAULT_MINIMUM_DRAW_HEIGHT,\r
- ChartPanel.DEFAULT_MAXIMUM_DRAW_WIDTH, \r
- ChartPanel.DEFAULT_MAXIMUM_DRAW_HEIGHT,\r
- false,\r
- false, true, true, true, true);\r
- frame.add(panel);\r
-// frame.repaint();\r
- frame.validate();\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph, Throwable throwable) {\r
- throwable.printStackTrace();\r
-\r
- }\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart.chart;
+
+import java.awt.Frame;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.awt.SWT_AWT;
+import org.eclipse.swt.widgets.Composite;
+import org.jfree.chart.ChartPanel;
+import org.jfree.chart.JFreeChart;
+import org.simantics.Simantics;
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.procedure.AsyncListener;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.utils.RunnableWithObject;
+
+/**
+ * Composite containing a single chart defined by a JFreeChart.Chart
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ChartComposite extends Composite {
+
+ private Frame frame;
+ private ChartPanel panel;
+ private Composite composite;
+ private IJFreeChart chart;
+
+ /**
+ * A new ChartComposite with a definition in chartResourceURI
+ * @param parent Composite
+ * @param chartResourceURI URI for a JFreeChart.Chart definition
+ * @param style SWT style
+ */
+ public ChartComposite(Composite parent, final String chartResourceURI, int style) {
+ super(parent, style | SWT.NO_BACKGROUND | SWT.EMBEDDED);
+
+ try {
+ Resource chartResource = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return graph.getPossibleResource(chartResourceURI);
+ }
+
+ });
+ if(chartResource != null)
+ CreateContent(chartResource);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * A new ChartComposite with a chartResource definition
+ * @param parent Composite
+ * @param chartResource JFreeChart.Chart resource
+ * @param style SWT style
+ */
+ public ChartComposite(Composite parent, final Resource chartResource, int style) {
+ super(parent, style | SWT.NO_BACKGROUND | SWT.EMBEDDED);
+ CreateContent(chartResource);
+ }
+
+ /**
+ * Creates and displays the chart defined in chartResource
+ * @param chartResource
+ */
+ private void CreateContent(final Resource chartResource) {
+ composite = this;
+
+ GridLayoutFactory.fillDefaults().applyTo(composite);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ frame = SWT_AWT.new_Frame(composite);
+
+ // Add a listener displaying the contents of the chart. Chart is re-drawn if the definition changes
+ Simantics.getSession().asyncRequest(new Read<IJFreeChart>() {
+
+ @Override
+ public IJFreeChart perform(ReadGraph graph) throws DatabaseException {
+ // Adapt chartResource to a chart (XY, pie, bar, ...)
+ if(graph.isInstanceOf(chartResource, JFreeChartResource.getInstance(graph).Chart)) {
+ if(chart != null)
+ chart.dispose();
+ chart = graph.adapt(chartResource, IJFreeChart.class);
+ return chart;
+ } else {
+ return null;
+ }
+ }
+
+ } , new AsyncListener<IJFreeChart>() {
+
+ @Override
+ public boolean isDisposed() {
+ return composite.isDisposed();
+ }
+
+ @Override
+ public void execute(AsyncReadGraph graph, IJFreeChart chart) {
+ if(chart == null || composite.isDisposed())
+ return;
+
+ JFreeChart jfreeChart = chart.getChart();
+ // Display the result chart
+ if (composite.isDisposed())
+ return;
+ composite.getDisplay().asyncExec(new RunnableWithObject(jfreeChart) {
+
+ @Override
+ public void run() {
+ if(composite.isDisposed())
+ return;
+ if(panel != null)
+ frame.remove(panel);
+ composite.layout();
+ JFreeChart chart = (JFreeChart)getObject();
+ //panel = new ChartPanel(chart, false, true, true, true, true);
+ panel = new ChartPanel(chart,
+ ChartPanel.DEFAULT_WIDTH,
+ ChartPanel.DEFAULT_HEIGHT,
+ ChartPanel.DEFAULT_MINIMUM_DRAW_WIDTH,
+ ChartPanel.DEFAULT_MINIMUM_DRAW_HEIGHT,
+ ChartPanel.DEFAULT_MAXIMUM_DRAW_WIDTH,
+ ChartPanel.DEFAULT_MAXIMUM_DRAW_HEIGHT,
+ false,
+ false, true, true, true, true);
+ frame.add(panel);
+// frame.repaint();
+ frame.validate();
+ }
+ });
+ }
+
+ @Override
+ public void exception(AsyncReadGraph graph, Throwable throwable) {
+ throwable.printStackTrace();
+
+ }
+ });
+ }
+
+}
import org.simantics.db.procedure.AsyncListener;
import org.simantics.db.request.Read;
import org.simantics.sysdyn.JFreeChartResource;
-import org.simantics.ui.SimanticsUI;
import org.simantics.utils.threads.AWTThread;
import org.simantics.utils.threads.ThreadUtils;
import org.simantics.utils.ui.SWTAWTComponent;
public ChartComposite2(Composite parent, final String chartResourceURI, int style) {
super(parent, style);
try {
- Resource chartResource = SimanticsUI.getSession().syncRequest(new Read<Resource>() {
+ Resource chartResource = Simantics.getSession().syncRequest(new Read<Resource>() {
@Override
public Resource perform(ReadGraph graph) throws DatabaseException {
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart;\r
-\r
-import java.awt.Color;\r
-import java.awt.Font;\r
-import java.util.Collection;\r
-\r
-import javax.swing.SwingUtilities;\r
-\r
-import org.jfree.chart.title.LegendTitle;\r
-import org.jfree.chart.title.TextTitle;\r
-import org.jfree.ui.RectangleInsets;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-/**\r
- * Class representing a complete JFreeChart.Chart\r
- * \r
- * This class supports all types of charts. The details of the chart are \r
- * defined in plots and other adapted classes.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class JFreeChart implements IJFreeChart {\r
-\r
- protected org.jfree.chart.JFreeChart jfreechart;\r
- protected JFreeChartListener listener;\r
- protected IPlot plot;\r
- protected ITitle title;\r
- protected Resource chartResource;\r
-\r
- /**\r
- * \r
- * @param graph ReadGraph\r
- * @param chartResource Resource of type JFreeChart.Chart\r
- */\r
- public JFreeChart(ReadGraph graph, Resource chartResource) {\r
- this.chartResource = chartResource; \r
- initialize(graph);\r
- }\r
- \r
- protected JFreeChart() {\r
- // default constructor is used with inherited classes.\r
- }\r
- \r
- protected void initialize(ReadGraph graph) {\r
- try {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
-\r
- Collection<Resource> plotsCollection = graph.syncRequest(new ObjectsWithType(chartResource, l0.ConsistsOf, jfree.Plot));\r
- for(Resource plotResource : plotsCollection) {\r
- this.plot = getPlot(graph,plotResource);\r
- } \r
-\r
- } catch(DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- protected IPlot getPlot(ReadGraph graph, Resource plotResource) throws DatabaseException{\r
- return graph.adapt(plotResource, IPlot.class);\r
- }\r
-\r
-\r
- \r
-\r
- /**\r
- * Returns a new chart using the information collected in the constructor\r
- */\r
- @Override\r
- public org.jfree.chart.JFreeChart getChart() {\r
- if(plot == null)\r
- return null;\r
-\r
- if(jfreechart == null)\r
- jfreechart = new org.jfree.chart.JFreeChart(plot.getPlot());\r
- \r
- plot.setJFreeChart(jfreechart);\r
- \r
- if(listener == null) {\r
- listener = new JFreeChartListener();\r
- SimanticsUI.getSession().asyncRequest(new JFreeChartQuery(), listener);\r
- }\r
-\r
- return jfreechart;\r
- }\r
- \r
- @Override\r
- public IPlot getPlot() {\r
- return plot;\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- // Call dispose to title and plots to disable their possible listeners\r
- if(title != null)\r
- title.dispose();\r
- if(listener != null)\r
- listener.dispose();\r
- if(plot != null)\r
- plot.dispose();\r
- }\r
-\r
- protected class JFreeChartQuery implements Read<Pair<ITitle, Boolean>> {\r
- \r
- public JFreeChartQuery() {\r
- }\r
-\r
- @Override\r
- public Pair<ITitle, Boolean> perform(ReadGraph graph) throws DatabaseException {\r
- if(chartResource == null || !graph.hasStatement(chartResource))\r
- return null;\r
- \r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
-\r
- Resource titleResource = graph.syncRequest(new PossibleObjectWithType(chartResource, l0.ConsistsOf, jfree.Title));\r
- title = graph.adapt(titleResource, ITitle.class);\r
- Boolean legendVisible = graph.getPossibleRelatedValue(chartResource, jfree.Chart_visibleLegend, Bindings.BOOLEAN);\r
- return new Pair<ITitle, Boolean>(title, legendVisible);\r
- }\r
- }\r
- \r
- protected class JFreeChartListener implements Listener<Pair<ITitle, Boolean>> {\r
-\r
- private boolean disposed = false;\r
- private LegendTitle legend;\r
- \r
- public JFreeChartListener() {\r
- \r
- }\r
-\r
- public void dispose() {\r
- disposed = true;\r
- }\r
-\r
- @Override\r
- public void execute(final Pair<ITitle, Boolean> result) {\r
- if(result == null)\r
- return;\r
- \r
- SwingUtilities.invokeLater(new Runnable() {\r
- @Override\r
- public void run() {\r
- if(jfreechart == null)\r
- return;\r
-\r
- jfreechart.setBackgroundPaint(Color.WHITE);\r
- \r
- if(jfreechart.getLegend() != null && !jfreechart.getLegend().equals(legend)) {\r
- legend = jfreechart.getLegend(); \r
- legend.setBorder(0, 0, 0, 0);\r
- int size = legend.getItemFont().getSize();\r
- legend.setItemFont(new Font("helvetica", Font.PLAIN, size));\r
- }\r
-\r
- if(Boolean.FALSE.equals(result.second)) {\r
- jfreechart.removeLegend();\r
- } else if (jfreechart.getLegend() == null && legend != null){\r
- jfreechart.addLegend(legend);\r
- }\r
-\r
- TextTitle t = (org.jfree.chart.title.TextTitle)result.first.getTitle();\r
- if(t.isVisible()) {\r
- t.setFont(new Font("georgia", Font.BOLD, 13));\r
- t.setPadding(new RectangleInsets(4, 0, 0, 0));\r
- jfreechart.setTitle(t);\r
- } else {\r
- jfreechart.setTitle((TextTitle)null);\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
-\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart.chart;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.util.Collection;
+
+import javax.swing.SwingUtilities;
+
+import org.jfree.chart.title.LegendTitle;
+import org.jfree.chart.title.TextTitle;
+import org.jfree.ui.RectangleInsets;
+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.PossibleObjectWithType;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.utils.datastructures.Pair;
+
+/**
+ * Class representing a complete JFreeChart.Chart
+ *
+ * This class supports all types of charts. The details of the chart are
+ * defined in plots and other adapted classes.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class JFreeChart implements IJFreeChart {
+
+ protected org.jfree.chart.JFreeChart jfreechart;
+ protected JFreeChartListener listener;
+ protected IPlot plot;
+ protected ITitle title;
+ protected Resource chartResource;
+
+ /**
+ *
+ * @param graph ReadGraph
+ * @param chartResource Resource of type JFreeChart.Chart
+ */
+ public JFreeChart(ReadGraph graph, Resource chartResource) {
+ this.chartResource = chartResource;
+ initialize(graph);
+ }
+
+ protected JFreeChart() {
+ // default constructor is used with inherited classes.
+ }
+
+ protected void initialize(ReadGraph graph) {
+ try {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ Collection<Resource> plotsCollection = graph.syncRequest(new ObjectsWithType(chartResource, l0.ConsistsOf, jfree.Plot));
+ for(Resource plotResource : plotsCollection) {
+ this.plot = getPlot(graph,plotResource);
+ }
+
+ } catch(DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ protected IPlot getPlot(ReadGraph graph, Resource plotResource) throws DatabaseException{
+ return graph.adapt(plotResource, IPlot.class);
+ }
+
+
+
+
+ /**
+ * Returns a new chart using the information collected in the constructor
+ */
+ @Override
+ public org.jfree.chart.JFreeChart getChart() {
+ if(plot == null)
+ return null;
+
+ if(jfreechart == null)
+ jfreechart = new org.jfree.chart.JFreeChart(plot.getPlot());
+
+ plot.setJFreeChart(jfreechart);
+
+ if(listener == null) {
+ listener = new JFreeChartListener();
+ Simantics.getSession().asyncRequest(new JFreeChartQuery(), listener);
+ }
+
+ return jfreechart;
+ }
+
+ @Override
+ public IPlot getPlot() {
+ return plot;
+ }
+
+ @Override
+ public void dispose() {
+ // Call dispose to title and plots to disable their possible listeners
+ if(title != null)
+ title.dispose();
+ if(listener != null)
+ listener.dispose();
+ if(plot != null)
+ plot.dispose();
+ }
+
+ protected class JFreeChartQuery implements Read<Pair<ITitle, Boolean>> {
+
+ public JFreeChartQuery() {
+ }
+
+ @Override
+ public Pair<ITitle, Boolean> perform(ReadGraph graph) throws DatabaseException {
+ if(chartResource == null || !graph.hasStatement(chartResource))
+ return null;
+
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ Resource titleResource = graph.syncRequest(new PossibleObjectWithType(chartResource, l0.ConsistsOf, jfree.Title));
+ title = graph.adapt(titleResource, ITitle.class);
+ Boolean legendVisible = graph.getPossibleRelatedValue(chartResource, jfree.Chart_visibleLegend, Bindings.BOOLEAN);
+ return new Pair<ITitle, Boolean>(title, legendVisible);
+ }
+ }
+
+ protected class JFreeChartListener implements Listener<Pair<ITitle, Boolean>> {
+
+ private boolean disposed = false;
+ private LegendTitle legend;
+
+ public JFreeChartListener() {
+
+ }
+
+ public void dispose() {
+ disposed = true;
+ }
+
+ @Override
+ public void execute(final Pair<ITitle, Boolean> result) {
+ if(result == null)
+ return;
+
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ if(jfreechart == null)
+ return;
+
+ jfreechart.setBackgroundPaint(Color.WHITE);
+
+ if(jfreechart.getLegend() != null && !jfreechart.getLegend().equals(legend)) {
+ legend = jfreechart.getLegend();
+ legend.setBorder(0, 0, 0, 0);
+ int size = legend.getItemFont().getSize();
+ legend.setItemFont(new Font("helvetica", Font.PLAIN, size));
+ }
+
+ if(Boolean.FALSE.equals(result.second)) {
+ jfreechart.removeLegend();
+ } else if (jfreechart.getLegend() == null && legend != null){
+ jfreechart.addLegend(legend);
+ }
+
+ TextTitle t = (org.jfree.chart.title.TextTitle)result.first.getTitle();
+ if(t.isVisible()) {
+ t.setFont(new Font("georgia", Font.BOLD, 13));
+ t.setPadding(new RectangleInsets(4, 0, 0, 0));
+ jfreechart.setTitle(t);
+ } else {
+ jfreechart.setTitle((TextTitle)null);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart.ge;\r
-\r
-import java.util.List;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.DropActionFactory;\r
-import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Action for dropping axis on top of other axis or series in {@link AxisAndVariablesExplorerComposite}\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class AxisDropAction implements DropActionFactory {\r
-\r
- @Override\r
- public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {\r
- // Make sure that both target and source are resources\r
- Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);\r
- Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);\r
- \r
- if(t == null || s == null)\r
- return null;\r
- \r
- // Make sure that source and target are of correct type\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
- if(!g.isInstanceOf(s, jfree.Axis))\r
- return null;\r
- if(!g.isInstanceOf(t, jfree.Series) && !g.isInstanceOf(t, jfree.Axis))\r
- return null;\r
- \r
- return getRunnable(t, s);\r
- }\r
-\r
- /**\r
- * Get the runnable for doing the drop action \r
- * \r
- * @param t target resource\r
- * @param s source resource\r
- * @return Runnable\r
- */\r
- private Runnable getRunnable(final Resource t, final Resource s) {\r
- Runnable runnable = new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- if(t == null || s == null) return;\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource target = t;\r
- Resource source = s;\r
- \r
- // Dragged axis always exists in the same list with target axis, so it is safe to get the target index\r
- Resource plot = graph.getPossibleObject(source, l0.PartOf);\r
- Resource axisListResource = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
- List<Resource> axisList = ListUtils.toList(graph, axisListResource);\r
- if(graph.isInstanceOf(target, jfree.Series)) {\r
- // Dropped a axis over a series -> get the axis of the series\r
- Resource dataset = graph.getPossibleObject(target, l0.PartOf);\r
- target = graph.getPossibleObject(dataset, jfree.Dataset_mapToRangeAxis);\r
- }\r
- \r
- // move axis to target position\r
- int targetIndex = axisList.indexOf(target);\r
- axisList.remove(source);\r
- axisList.add(targetIndex, source);\r
- \r
- // Update the range axis list\r
- graph.deny(plot, jfree.Plot_rangeAxisList);\r
- axisListResource = ListUtils.create(graph, axisList);\r
- graph.claim(plot, jfree.Plot_rangeAxisList, axisListResource);\r
- }\r
-\r
- });\r
- }\r
- };\r
- return runnable;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart.chart.ge;
+
+import java.util.List;
+
+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.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.DropActionFactory;
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Action for dropping axis on top of other axis or series in {@link AxisAndVariablesExplorerComposite}
+ * @author Teemu Lempinen
+ *
+ */
+public class AxisDropAction implements DropActionFactory {
+
+ @Override
+ public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {
+ // Make sure that both target and source are resources
+ Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);
+ Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);
+
+ if(t == null || s == null)
+ return null;
+
+ // Make sure that source and target are of correct type
+ JFreeChartResource jfree = JFreeChartResource.getInstance(g);
+ if(!g.isInstanceOf(s, jfree.Axis))
+ return null;
+ if(!g.isInstanceOf(t, jfree.Series) && !g.isInstanceOf(t, jfree.Axis))
+ return null;
+
+ return getRunnable(t, s);
+ }
+
+ /**
+ * Get the runnable for doing the drop action
+ *
+ * @param t target resource
+ * @param s source resource
+ * @return Runnable
+ */
+ private Runnable getRunnable(final Resource t, final Resource s) {
+ Runnable runnable = new Runnable() {
+
+ @Override
+ public void run() {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ if(t == null || s == null) return;
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource target = t;
+ Resource source = s;
+
+ // Dragged axis always exists in the same list with target axis, so it is safe to get the target index
+ Resource plot = graph.getPossibleObject(source, l0.PartOf);
+ Resource axisListResource = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);
+ List<Resource> axisList = ListUtils.toList(graph, axisListResource);
+ if(graph.isInstanceOf(target, jfree.Series)) {
+ // Dropped a axis over a series -> get the axis of the series
+ Resource dataset = graph.getPossibleObject(target, l0.PartOf);
+ target = graph.getPossibleObject(dataset, jfree.Dataset_mapToRangeAxis);
+ }
+
+ // move axis to target position
+ int targetIndex = axisList.indexOf(target);
+ axisList.remove(source);
+ axisList.add(targetIndex, source);
+
+ // Update the range axis list
+ graph.deny(plot, jfree.Plot_rangeAxisList);
+ axisListResource = ListUtils.create(graph, axisList);
+ graph.claim(plot, jfree.Plot_rangeAxisList, axisListResource);
+ }
+
+ });
+ }
+ };
+ return runnable;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart.ge;\r
-\r
-import java.util.Collections;\r
-import java.util.List;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.DropActionFactory;\r
-import org.simantics.jfreechart.chart.properties.xyline.XYLineAxisAndVariablesTab;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Drop action for explorer in {@link XYLineAxisAndVariablesTab}. This action is used for dropping \r
- * both series on axis or another sries\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class SeriesDropAction implements DropActionFactory {\r
-\r
- @Override\r
- public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {\r
- // Make sure that both target and source are resources\r
- Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);\r
- Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);\r
- \r
- if(t == null || s == null)\r
- return null;\r
- \r
- // Make sure that source and target are of correct type\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
- if(!g.isInstanceOf(s, jfree.Series))\r
- return null;\r
- if(!g.isInstanceOf(t, jfree.Series) && !g.isInstanceOf(t, jfree.Axis))\r
- return null;\r
- \r
- return getRunnable(t, s);\r
- }\r
-\r
- /**\r
- * Get the runnable for doing the drop action \r
- * \r
- * @param t target resource\r
- * @param s source resource\r
- * @return Runnable\r
- */\r
- private Runnable getRunnable(final Resource t, final Resource s) {\r
- Runnable runnable = new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- if(t == null || s == null) return;\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource target = t;\r
- Resource source = s;\r
- Resource droppedOnSeries = null;\r
-\r
- // Dropped a series over a series -> get target dataset\r
- if(graph.isInstanceOf(target, jfree.Series)) {\r
- droppedOnSeries = target;\r
- Resource dataset = graph.getPossibleObject(target, l0.PartOf);\r
- if(dataset != null)\r
- target = dataset;\r
- }\r
-\r
- // Dropped a series over an axis -> get target dataset\r
- if(graph.isInstanceOf(target, jfree.Axis)) {\r
- Resource dataset = graph.syncRequest(new PossibleObjectWithType(target, jfree.Dataset_mapToRangeAxis_Inverse, jfree.Dataset));\r
- if(dataset != null)\r
- target = dataset;\r
- }\r
-\r
- // Move series to a dataset\r
- if(graph.isInstanceOf(target, jfree.Dataset)) {\r
- // Remove from old dataset if it was different than the new one\r
- Resource sourceDataset = graph.getPossibleObject(source, l0.PartOf);\r
- if(sourceDataset != null && !sourceDataset.equals(target)) {\r
- Resource sourceSeriesList = graph.getPossibleObject(sourceDataset, jfree.Dataset_seriesList);\r
- if(sourceSeriesList != null)\r
- ListUtils.removeElement(graph, sourceSeriesList, source);\r
- }\r
- graph.deny(source, l0.PartOf);\r
-\r
- // Add to new dataset\r
- Resource targetSeriesList = graph.getPossibleObject(target, jfree.Dataset_seriesList);\r
- if(targetSeriesList == null) {\r
- targetSeriesList = ListUtils.create(graph, Collections.<Resource>emptyList());\r
- graph.claim(target, jfree.Dataset_seriesList, targetSeriesList);\r
- }\r
-\r
-\r
- // Series was dropped on another series. Move the dropped series to that place and recreate the list\r
- if(droppedOnSeries != null) {\r
- List<Resource> list = ListUtils.toList(graph, targetSeriesList);\r
- int targetIndex = list.indexOf(droppedOnSeries);\r
- if(list.contains(source))\r
- list.remove(source);\r
- list.add(targetIndex, source);\r
- graph.deny(target, jfree.Dataset_seriesList);\r
- targetSeriesList = ListUtils.create(graph, list);\r
- graph.claim(target, jfree.Dataset_seriesList, targetSeriesList);\r
- } else {\r
- ListUtils.insertFront(graph, targetSeriesList, Collections.singleton(source));\r
- }\r
-\r
- graph.claim(target, l0.ConsistsOf, source);\r
- }\r
- }\r
- });\r
- }\r
- };\r
- return runnable;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart.chart.ge;
+
+import java.util.Collections;
+import java.util.List;
+
+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.PossibleObjectWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.DropActionFactory;
+import org.simantics.jfreechart.chart.properties.xyline.XYLineAxisAndVariablesTab;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Drop action for explorer in {@link XYLineAxisAndVariablesTab}. This action is used for dropping
+ * both series on axis or another sries
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class SeriesDropAction implements DropActionFactory {
+
+ @Override
+ public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {
+ // Make sure that both target and source are resources
+ Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);
+ Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);
+
+ if(t == null || s == null)
+ return null;
+
+ // Make sure that source and target are of correct type
+ JFreeChartResource jfree = JFreeChartResource.getInstance(g);
+ if(!g.isInstanceOf(s, jfree.Series))
+ return null;
+ if(!g.isInstanceOf(t, jfree.Series) && !g.isInstanceOf(t, jfree.Axis))
+ return null;
+
+ return getRunnable(t, s);
+ }
+
+ /**
+ * Get the runnable for doing the drop action
+ *
+ * @param t target resource
+ * @param s source resource
+ * @return Runnable
+ */
+ private Runnable getRunnable(final Resource t, final Resource s) {
+ Runnable runnable = new Runnable() {
+
+ @Override
+ public void run() {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ if(t == null || s == null) return;
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource target = t;
+ Resource source = s;
+ Resource droppedOnSeries = null;
+
+ // Dropped a series over a series -> get target dataset
+ if(graph.isInstanceOf(target, jfree.Series)) {
+ droppedOnSeries = target;
+ Resource dataset = graph.getPossibleObject(target, l0.PartOf);
+ if(dataset != null)
+ target = dataset;
+ }
+
+ // Dropped a series over an axis -> get target dataset
+ if(graph.isInstanceOf(target, jfree.Axis)) {
+ Resource dataset = graph.syncRequest(new PossibleObjectWithType(target, jfree.Dataset_mapToRangeAxis_Inverse, jfree.Dataset));
+ if(dataset != null)
+ target = dataset;
+ }
+
+ // Move series to a dataset
+ if(graph.isInstanceOf(target, jfree.Dataset)) {
+ // Remove from old dataset if it was different than the new one
+ Resource sourceDataset = graph.getPossibleObject(source, l0.PartOf);
+ if(sourceDataset != null && !sourceDataset.equals(target)) {
+ Resource sourceSeriesList = graph.getPossibleObject(sourceDataset, jfree.Dataset_seriesList);
+ if(sourceSeriesList != null)
+ ListUtils.removeElement(graph, sourceSeriesList, source);
+ }
+ graph.deny(source, l0.PartOf);
+
+ // Add to new dataset
+ Resource targetSeriesList = graph.getPossibleObject(target, jfree.Dataset_seriesList);
+ if(targetSeriesList == null) {
+ targetSeriesList = ListUtils.create(graph, Collections.<Resource>emptyList());
+ graph.claim(target, jfree.Dataset_seriesList, targetSeriesList);
+ }
+
+
+ // Series was dropped on another series. Move the dropped series to that place and recreate the list
+ if(droppedOnSeries != null) {
+ List<Resource> list = ListUtils.toList(graph, targetSeriesList);
+ int targetIndex = list.indexOf(droppedOnSeries);
+ if(list.contains(source))
+ list.remove(source);
+ list.add(targetIndex, source);
+ graph.deny(target, jfree.Dataset_seriesList);
+ targetSeriesList = ListUtils.create(graph, list);
+ graph.claim(target, jfree.Dataset_seriesList, targetSeriesList);
+ } else {
+ ListUtils.insertFront(graph, targetSeriesList, Collections.singleton(source));
+ }
+
+ graph.claim(target, l0.ConsistsOf, source);
+ }
+ }
+ });
+ }
+ };
+ return runnable;
+ }
+
+}
-package org.simantics.jfreechart.chart.properties;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-\r
-import org.eclipse.jface.dialogs.IInputValidator;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Variable exists validator for tracked text widgets. \r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class VariableExistsValidator implements IInputValidator, Widget {\r
-\r
- protected Collection<ChartVariable> variables;\r
- protected TrackedText text;\r
- private boolean allowEmpty;\r
- @SuppressWarnings("unused")\r
- private boolean useLabels = false;\r
- \r
- /**\r
- * Validate against all variables\r
- * \r
- * Do not allow empty input\r
- * @param support WidgetSupport\r
- * @param text Text widget\r
- */\r
- public VariableExistsValidator(WidgetSupport support, TrackedText text) {\r
- this(support, text, false);\r
- }\r
- \r
- \r
- \r
- /**\r
- * Validate against all variables\r
- * \r
- * @param support WidgetSupport\r
- * @param text Text widget\r
- * @param allowEmpty Allow empty input text\r
- */\r
- public VariableExistsValidator(WidgetSupport support, TrackedText text, boolean allowEmpty) {\r
- support.register(this);\r
- this.variables = new ArrayList<ChartVariable>();\r
- this.text = text;\r
- this.allowEmpty = allowEmpty;\r
- }\r
- \r
- public VariableExistsValidator(WidgetSupport support, TrackedText text, boolean allowEmpty, boolean useLabels) {\r
- this(support, text, allowEmpty);\r
- this.useLabels = useLabels;\r
- }\r
- \r
- /**\r
- * Returns null if there is a variable named newText in the model\r
- */\r
- @Override\r
- public String isValid(String newText) {\r
- if(newText == null || newText.isEmpty()) {\r
- if(allowEmpty)\r
- return null;\r
- else\r
- return "Empty name not allowed";\r
- }\r
- \r
- synchronized (variables) {\r
- for(ChartVariable variable : variables) {\r
- if(newText.equals(variable.getLabel()))\r
- return null;\r
- if(newText.equals(variable.getRvi()))\r
- return null;\r
- }\r
- }\r
- \r
- return "Not a valid variable name";\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- \r
- if(resource == null) {\r
- variables = new ArrayList<ChartVariable>();\r
- return;\r
- }\r
- \r
- \r
- try {\r
- /* Find the model resource. It can be found with PartOf \r
- relations from series resource in a chart */\r
- AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);\r
- \r
- if(query != null) {\r
- // Find all variables and set them as the reference for isValid(String)\r
- SimanticsUI.getSession().asyncRequest(query\r
- , new Listener<Collection<ChartVariable>>() {\r
-\r
- @Override\r
- public void execute(Collection<ChartVariable> variables) {\r
- VariableExistsValidator.this.variables = variables;\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return text.isDisposed();\r
- }\r
-\r
- }); \r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
-}\r
+package org.simantics.jfreechart.chart.properties;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.eclipse.jface.dialogs.IInputValidator;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.TrackedText;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.Listener;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Variable exists validator for tracked text widgets.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class VariableExistsValidator implements IInputValidator, Widget {
+
+ protected Collection<ChartVariable> variables;
+ protected TrackedText text;
+ private boolean allowEmpty;
+ @SuppressWarnings("unused")
+ private boolean useLabels = false;
+
+ /**
+ * Validate against all variables
+ *
+ * Do not allow empty input
+ * @param support WidgetSupport
+ * @param text Text widget
+ */
+ public VariableExistsValidator(WidgetSupport support, TrackedText text) {
+ this(support, text, false);
+ }
+
+
+
+ /**
+ * Validate against all variables
+ *
+ * @param support WidgetSupport
+ * @param text Text widget
+ * @param allowEmpty Allow empty input text
+ */
+ public VariableExistsValidator(WidgetSupport support, TrackedText text, boolean allowEmpty) {
+ support.register(this);
+ this.variables = new ArrayList<ChartVariable>();
+ this.text = text;
+ this.allowEmpty = allowEmpty;
+ }
+
+ public VariableExistsValidator(WidgetSupport support, TrackedText text, boolean allowEmpty, boolean useLabels) {
+ this(support, text, allowEmpty);
+ this.useLabels = useLabels;
+ }
+
+ /**
+ * Returns null if there is a variable named newText in the model
+ */
+ @Override
+ public String isValid(String newText) {
+ if(newText == null || newText.isEmpty()) {
+ if(allowEmpty)
+ return null;
+ else
+ return "Empty name not allowed";
+ }
+
+ synchronized (variables) {
+ for(ChartVariable variable : variables) {
+ if(newText.equals(variable.getLabel()))
+ return null;
+ if(newText.equals(variable.getRvi()))
+ return null;
+ }
+ }
+
+ return "Not a valid variable name";
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);
+
+ if(resource == null) {
+ variables = new ArrayList<ChartVariable>();
+ return;
+ }
+
+
+ try {
+ /* Find the model resource. It can be found with PartOf
+ relations from series resource in a chart */
+ AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);
+
+ if(query != null) {
+ // Find all variables and set them as the reference for isValid(String)
+ Simantics.getSession().asyncRequest(query
+ , new Listener<Collection<ChartVariable>>() {
+
+ @Override
+ public void execute(Collection<ChartVariable> variables) {
+ VariableExistsValidator.this.variables = variables;
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return text.isDisposed();
+ }
+
+ });
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart.properties;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Iterator;\r
-\r
-import org.eclipse.jface.fieldassist.ContentProposal;\r
-import org.eclipse.jface.fieldassist.IContentProposal;\r
-import org.eclipse.jface.fieldassist.IContentProposalProvider;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * \r
- * @author Marko Luukkainen <marko.luukkainen@vtt.fi>\r
- *\r
- */\r
-public class VariableProposalProvider implements IContentProposalProvider, Widget {\r
-\r
- /*\r
- * The proposals provided.\r
- */\r
- private Collection<ChartVariable> proposals;\r
-\r
- /*\r
- * The proposals mapped to IContentProposal. Cached for speed in the case\r
- * where filtering is not used.\r
- */\r
- private IContentProposal[] contentProposals;\r
-\r
- /*\r
- * Boolean that tracks whether filtering is used.\r
- */\r
- private boolean filterProposals = false;\r
-\r
-\r
- private boolean compareRVI = false;\r
- /**\r
- * Return an array of Objects representing the valid content proposals for a\r
- * field. \r
- * \r
- * @param contents\r
- * the current contents of the field (only consulted if filtering\r
- * is set to <code>true</code>)\r
- * @param position\r
- * the current cursor position within the field (ignored)\r
- * @return the array of Objects that represent valid proposals for the field\r
- * given its current content.\r
- */\r
- @SuppressWarnings("unchecked")\r
- public IContentProposal[] getProposals(String contents, int position) {\r
- if (filterProposals) {\r
- @SuppressWarnings("rawtypes")\r
- ArrayList list = new ArrayList();\r
- if (compareRVI) {\r
- for (ChartVariable proposal : proposals) {\r
- if (proposal.getRvi().length() >= contents.length() && proposal.getRvi().substring(0, contents.length()).equalsIgnoreCase(contents)) {\r
- if (proposal.getLabel() != null)\r
- list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));\r
- else\r
- list.add(new ContentProposal(proposal.getRvi()));\r
- } else if (proposal.getLabel() != null && proposal.getLabel().length() >= contents.length() && proposal.getLabel().substring(0, contents.length()).equalsIgnoreCase(contents)) {\r
- list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));\r
- }\r
- }\r
- } else {\r
- for (ChartVariable proposal : proposals) {\r
- if (proposal.getLabel() != null && proposal.getLabel().length() >= contents.length() && proposal.getLabel().substring(0, contents.length()).equalsIgnoreCase(contents)) {\r
- list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));\r
- }\r
- }\r
- }\r
- \r
- return (IContentProposal[]) list.toArray(new IContentProposal[list\r
- .size()]);\r
- }\r
- if (contentProposals == null) {\r
- contentProposals = new IContentProposal[proposals.size()];\r
- Iterator<ChartVariable> iter = proposals.iterator();\r
- for (int i = 0; i < proposals.size(); i++) {\r
- ChartVariable proposal = iter.next();\r
- if (proposal.getLabel() != null)\r
- contentProposals[i] = new ContentProposal(proposal.getRvi(),proposal.getLabel(),null);\r
- else\r
- contentProposals[i] = new ContentProposal(proposal.getRvi());\r
- }\r
- }\r
- return contentProposals;\r
- }\r
-\r
- /**\r
- * Set the Strings to be used as content proposals.\r
- * \r
- * @param items\r
- * the array of Strings to be used as proposals.\r
- */\r
- public void setProposals(Collection<ChartVariable> items) {\r
- this.proposals = items;\r
- contentProposals = null;\r
- }\r
-\r
- /**\r
- * Set the boolean that controls whether proposals are filtered according to\r
- * the current field content.\r
- * \r
- * @param filterProposals\r
- * <code>true</code> if the proposals should be filtered to\r
- * show only those that match the current contents of the field,\r
- * and <code>false</code> if the proposals should remain the\r
- * same, ignoring the field content.\r
- * @since 3.3\r
- */\r
- public void setFiltering(boolean filterProposals) {\r
- this.filterProposals = filterProposals;\r
- // Clear any cached proposals.\r
- contentProposals = null;\r
- }\r
- \r
- /**\r
- * Provides all variables a model contains. Given resource needs to be\r
- * part of a model (i.e. using PartOf leads eventually to a SysdynModel).\r
- * \r
- * @param control Control that is using this provider\r
- * @param resource A resource that is part of a model\r
- */\r
- public VariableProposalProvider(final Control control, WidgetSupport support) {\r
- this.proposals = new ArrayList<ChartVariable>();\r
- support.register(this);\r
- this.control = control;\r
- }\r
-\r
- private Resource resource;\r
- private Control control;\r
- \r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
-\r
- final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- if(resource == null)\r
- return;\r
- this.resource = resource;\r
- /* Find the model resource. It can be found with PartOf \r
- relations from series resource in a chart */\r
- try {\r
- AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);\r
- SimanticsUI.getSession().asyncRequest(query\r
- , new Listener<Collection<ChartVariable>>() {\r
-\r
- @Override\r
- public void execute(Collection<ChartVariable> result) {\r
- setProposals(result);\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return control == null || \r
- control.isDisposed() || \r
- !resource.equals(VariableProposalProvider.this.resource);\r
- }\r
-\r
- }); \r
- } catch (DatabaseException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- \r
- \r
- \r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart.chart.properties;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+
+import org.eclipse.jface.fieldassist.ContentProposal;
+import org.eclipse.jface.fieldassist.IContentProposal;
+import org.eclipse.jface.fieldassist.IContentProposalProvider;
+import org.eclipse.swt.widgets.Control;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.Listener;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ *
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
+ *
+ */
+public class VariableProposalProvider implements IContentProposalProvider, Widget {
+
+ /*
+ * The proposals provided.
+ */
+ private Collection<ChartVariable> proposals;
+
+ /*
+ * The proposals mapped to IContentProposal. Cached for speed in the case
+ * where filtering is not used.
+ */
+ private IContentProposal[] contentProposals;
+
+ /*
+ * Boolean that tracks whether filtering is used.
+ */
+ private boolean filterProposals = false;
+
+
+ private boolean compareRVI = false;
+ /**
+ * Return an array of Objects representing the valid content proposals for a
+ * field.
+ *
+ * @param contents
+ * the current contents of the field (only consulted if filtering
+ * is set to <code>true</code>)
+ * @param position
+ * the current cursor position within the field (ignored)
+ * @return the array of Objects that represent valid proposals for the field
+ * given its current content.
+ */
+ @SuppressWarnings("unchecked")
+ public IContentProposal[] getProposals(String contents, int position) {
+ if (filterProposals) {
+ @SuppressWarnings("rawtypes")
+ ArrayList list = new ArrayList();
+ if (compareRVI) {
+ for (ChartVariable proposal : proposals) {
+ if (proposal.getRvi().length() >= contents.length() && proposal.getRvi().substring(0, contents.length()).equalsIgnoreCase(contents)) {
+ if (proposal.getLabel() != null)
+ list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));
+ else
+ list.add(new ContentProposal(proposal.getRvi()));
+ } else if (proposal.getLabel() != null && proposal.getLabel().length() >= contents.length() && proposal.getLabel().substring(0, contents.length()).equalsIgnoreCase(contents)) {
+ list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));
+ }
+ }
+ } else {
+ for (ChartVariable proposal : proposals) {
+ if (proposal.getLabel() != null && proposal.getLabel().length() >= contents.length() && proposal.getLabel().substring(0, contents.length()).equalsIgnoreCase(contents)) {
+ list.add(new ContentProposal(proposal.getRvi(),proposal.getLabel(), null));
+ }
+ }
+ }
+
+ return (IContentProposal[]) list.toArray(new IContentProposal[list
+ .size()]);
+ }
+ if (contentProposals == null) {
+ contentProposals = new IContentProposal[proposals.size()];
+ Iterator<ChartVariable> iter = proposals.iterator();
+ for (int i = 0; i < proposals.size(); i++) {
+ ChartVariable proposal = iter.next();
+ if (proposal.getLabel() != null)
+ contentProposals[i] = new ContentProposal(proposal.getRvi(),proposal.getLabel(),null);
+ else
+ contentProposals[i] = new ContentProposal(proposal.getRvi());
+ }
+ }
+ return contentProposals;
+ }
+
+ /**
+ * Set the Strings to be used as content proposals.
+ *
+ * @param items
+ * the array of Strings to be used as proposals.
+ */
+ public void setProposals(Collection<ChartVariable> items) {
+ this.proposals = items;
+ contentProposals = null;
+ }
+
+ /**
+ * Set the boolean that controls whether proposals are filtered according to
+ * the current field content.
+ *
+ * @param filterProposals
+ * <code>true</code> if the proposals should be filtered to
+ * show only those that match the current contents of the field,
+ * and <code>false</code> if the proposals should remain the
+ * same, ignoring the field content.
+ * @since 3.3
+ */
+ public void setFiltering(boolean filterProposals) {
+ this.filterProposals = filterProposals;
+ // Clear any cached proposals.
+ contentProposals = null;
+ }
+
+ /**
+ * Provides all variables a model contains. Given resource needs to be
+ * part of a model (i.e. using PartOf leads eventually to a SysdynModel).
+ *
+ * @param control Control that is using this provider
+ * @param resource A resource that is part of a model
+ */
+ public VariableProposalProvider(final Control control, WidgetSupport support) {
+ this.proposals = new ArrayList<ChartVariable>();
+ support.register(this);
+ this.control = control;
+ }
+
+ private Resource resource;
+ private Control control;
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+
+ final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);
+ if(resource == null)
+ return;
+ this.resource = resource;
+ /* Find the model resource. It can be found with PartOf
+ relations from series resource in a chart */
+ try {
+ AllVariablesOfModel query = AllVariablesOfModel.withRandomResource(context, resource);
+ Simantics.getSession().asyncRequest(query
+ , new Listener<Collection<ChartVariable>>() {
+
+ @Override
+ public void execute(Collection<ChartVariable> result) {
+ setProposals(result);
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return control == null ||
+ control.isDisposed() ||
+ !resource.equals(VariableProposalProvider.this.resource);
+ }
+
+ });
+ } catch (DatabaseException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+
+
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart.properties.xyline;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Map;\r
-\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.NodeContext;\r
-import org.simantics.browsing.ui.common.ErrorLogger;\r
-import org.simantics.browsing.ui.model.InvalidContribution;\r
-import org.simantics.browsing.ui.model.dnd.DndBrowseContext;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.Procedure;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * ExplorerComposite allowing ontology-based DnD definitions. DnD Copied from {@link ModelBrowser2}\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class AxisAndVariablesExplorerComposite extends GraphExplorerComposite {\r
-\r
- volatile DndBrowseContext dndBrowseContext;\r
- \r
- public AxisAndVariablesExplorerComposite(Map<String, Object> args, IWorkbenchSite site, Composite parent,\r
- WidgetSupport support, int style) {\r
- super(args, site, parent, support, style);\r
- \r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException { \r
- ArrayList<Resource> browseContexts = new ArrayList<Resource>();\r
- for (String uri : getBrowseContexts()) {\r
- Resource browseContext = graph.getPossibleResource(uri);\r
- if (browseContext != null)\r
- browseContexts.add(browseContext);\r
- }\r
- try {\r
- dndBrowseContext = DndBrowseContext.create(graph, browseContexts);\r
- } catch (InvalidContribution e) {\r
- ErrorLogger.defaultLogError(e);\r
- }\r
- }\r
- });\r
- }\r
- \r
- @Override\r
- protected void handleDrop(final Object data, final NodeContext target) {\r
- if (target == null)\r
- return;\r
-\r
- SimanticsUI.getSession().asyncRequest(new Read<Runnable>() {\r
- @Override\r
- public Runnable perform(ReadGraph graph) throws DatabaseException {\r
- if (dndBrowseContext == null)\r
- return null;\r
- return dndBrowseContext.getAction(graph, target, data);\r
- }\r
- }, new Procedure<Runnable>() {\r
- @Override\r
- public void execute(Runnable result) {\r
- if (result != null)\r
- result.run();\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- ErrorLogger.defaultLogError(t);\r
- }\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.jfreechart.chart.properties.xyline;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.NodeContext;
+import org.simantics.browsing.ui.common.ErrorLogger;
+import org.simantics.browsing.ui.model.InvalidContribution;
+import org.simantics.browsing.ui.model.dnd.DndBrowseContext;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+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.db.procedure.Procedure;
+import org.simantics.db.request.Read;
+
+/**
+ * ExplorerComposite allowing ontology-based DnD definitions. DnD Copied from {@link ModelBrowser2}
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class AxisAndVariablesExplorerComposite extends GraphExplorerComposite {
+
+ volatile DndBrowseContext dndBrowseContext;
+
+ public AxisAndVariablesExplorerComposite(Map<String, Object> args, IWorkbenchSite site, Composite parent,
+ WidgetSupport support, int style) {
+ super(args, site, parent, support, style);
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ ArrayList<Resource> browseContexts = new ArrayList<Resource>();
+ for (String uri : getBrowseContexts()) {
+ Resource browseContext = graph.getPossibleResource(uri);
+ if (browseContext != null)
+ browseContexts.add(browseContext);
+ }
+ try {
+ dndBrowseContext = DndBrowseContext.create(graph, browseContexts);
+ } catch (InvalidContribution e) {
+ ErrorLogger.defaultLogError(e);
+ }
+ }
+ });
+ }
+
+ @Override
+ protected void handleDrop(final Object data, final NodeContext target) {
+ if (target == null)
+ return;
+
+ Simantics.getSession().asyncRequest(new Read<Runnable>() {
+ @Override
+ public Runnable perform(ReadGraph graph) throws DatabaseException {
+ if (dndBrowseContext == null)
+ return null;
+ return dndBrowseContext.getAction(graph, target, data);
+ }
+ }, new Procedure<Runnable>() {
+ @Override
+ public void execute(Runnable result) {
+ if (result != null)
+ result.run();
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ ErrorLogger.defaultLogError(t);
+ }
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.jfreechart.chart.properties.xyline;\r
-\r
-import java.util.List;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.ScrolledComposite;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.NodeContext;\r
-import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * PropertyTab displaying properties of axis and variables of a chart\r
- * \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class XYLineAxisAndVariablesTab extends AdjustableTab {\r
-\r
- private GraphExplorerComposite explorer;\r
- private ScrolledComposite propertyContainer;\r
- private Button addAxis, addVariable, remove;\r
- private WidgetSupportImpl additionalSupport;\r
- private Composite buttonComposite;\r
-\r
- public XYLineAxisAndVariablesTab(Object id) {\r
- super(id);\r
- additionalSupport = new WidgetSupportImpl();\r
- }\r
-\r
- /**\r
- * Updates the content of propertyContainer \r
- * @param context\r
- */\r
- private void updateSelection(ISessionContext context) {\r
- ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
- IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
- final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
- if(resource == null)\r
- return;\r
-\r
- // Get the type of the selected node (axis or series)\r
- String typeUri = null;\r
- try {\r
- typeUri = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- if(graph.isInstanceOf(resource, jfree.Axis))\r
- return graph.getURI(jfree.Axis);\r
- else if (graph.isInstanceOf(resource, jfree.Series))\r
- return graph.getURI(jfree.Series);\r
- return null;\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- // Create a PropertyComposite for the selected node\r
- if(typeUri != null) {\r
-\r
- for(Control child : propertyContainer.getChildren()) {\r
- child.dispose();\r
- }\r
-\r
- if(typeUri.equals(JFreeChartResource.URIs.Axis)) {\r
- AxisPropertyComposite apc = new AxisPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE, isVertical());\r
- propertyContainer.setContent(apc);\r
- Point size = apc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- } else if(typeUri.equals(JFreeChartResource.URIs.Series)) {\r
- SeriesPropertyComposite spc = new SeriesPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE);\r
- propertyContainer.setContent(spc);\r
- Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- }\r
- }\r
-\r
- additionalSupport.fireInput(context, selection);\r
- }\r
-\r
- /**\r
- * SelectionListener for adding a new range axis to a plot\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class NewAxisListener extends SelectionListenerImpl<Resource> {\r
-\r
- public NewAxisListener(ISessionContext context) {\r
- super(context);\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource chart) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));\r
- if(plot != null) {\r
- Resource rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);\r
- if(rangeAxis != null) {\r
- Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
- ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);\r
- }\r
- }\r
- }\r
- }\r
-\r
-\r
- /**\r
- * SelectionListener for adding a new variable to a plot\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class NewVariableListener extends SelectionListenerImpl<Resource> {\r
-\r
- public NewVariableListener(ISessionContext context) {\r
- super(context);\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
- NodeContext nc = explorer.getExplorer().getRoot();\r
- if(nc == null)\r
- return;\r
- \r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- if(input == null) {\r
- Resource chart = AdaptionUtils.adaptToSingle(nc, Resource.class);\r
- if(chart == null) return;\r
- Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));\r
- if(plot == null) return;\r
- Resource rangelist = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
- if(rangelist == null) return;\r
- List<Resource> list = ListUtils.toList(graph, rangelist);\r
- if(list == null || list.isEmpty()) return;\r
- input = list.get(0);\r
- }\r
- \r
- Resource dataset;\r
- if(graph.isInstanceOf(input, jfree.Series)) {\r
- // Selected resource is series. Add to same dataset\r
- dataset = graph.getPossibleObject(input, l0.PartOf);\r
- } else {\r
- // Selected resource is axis. Find the dataset it is mapped to or create dataset if not created already\r
- dataset = graph.getPossibleObject(input, jfree.Dataset_mapToRangeAxis_Inverse);\r
- if(dataset == null) {\r
- Resource plot = graph.getPossibleObject(input, l0.PartOf);\r
- if(plot == null) return;\r
- Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
- if(domainAxis == null) return;\r
- ChartUtils.createXYDataset(graph, plot, domainAxis, input);\r
- }\r
- }\r
-\r
- if(dataset != null) {\r
- // Create series with no rvi\r
- ChartUtils.createSeries(graph, dataset, null);\r
- }\r
- }\r
- }\r
-\r
-\r
- /**\r
- * SelectionListener for remove button\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class RemoveListener extends SelectionListenerImpl<Resource> {\r
-\r
- public RemoveListener(ISessionContext context) {\r
- super(context);\r
- }\r
-\r
- /**\r
- * Removes selected resource from explorer\r
- */\r
- @Override\r
- public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
- if(input == null)\r
- return; \r
-\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource list = null;\r
- if(graph.isInstanceOf(input, jfree.Series)) {\r
- // Remove series from dataset and seriesList\r
- Resource dataset = graph.getPossibleObject(input, l0.PartOf);\r
- if(dataset != null)\r
- list = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);\r
- } else {\r
- // Remove associated dataset\r
- Resource dataset = graph.getPossibleObject(input, jfree.Dataset_mapToRangeAxis_Inverse);\r
- if(dataset != null) {\r
- graph.deny(dataset, jfree.Dataset_mapToDomainAxis);\r
- graph.deny(dataset, jfree.Dataset_mapToRangeAxis);\r
- RemoverUtil.remove(graph, dataset);\r
- }\r
-\r
- // Remove axis from plot and rangeAxisList\r
- Resource plot = graph.getPossibleObject(input, l0.PartOf);\r
- if(plot != null)\r
- list = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
- }\r
- if(list != null)\r
- ListUtils.removeElement(graph, list, input);\r
- RemoverUtil.remove(graph, input);\r
- }\r
- }\r
-\r
-\r
- @Override\r
- protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
- final ISessionContext context, WidgetSupport support) {\r
- composite = new Composite(body, SWT.NONE);\r
-\r
- // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis\r
- explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
- explorer.setBrowseContexts(JFreeChartResource.URIs.ChartAxisAndVariablesBrowseContext);\r
- explorer.setInputSource(new SingleSelectionInputSource(\r
- Resource.class));\r
- explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
- explorer.finish();\r
-\r
- ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
- public void widgetSelected(SelectionEvent e) {\r
- updateSelection(context);\r
- }\r
- });\r
-\r
- // Scrolled composite for displaying properties of a selection in explorer\r
- propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
- propertyContainer.setExpandHorizontal(true);\r
- propertyContainer.setExpandVertical(true);\r
-\r
- // Buttons for adding axis and variables and removing selected items from explorer\r
- buttonComposite = new Composite(composite, SWT.NONE);\r
-\r
- addAxis = new Button(buttonComposite, support, SWT.NONE);\r
- addAxis.setText("Add axis");\r
- addAxis.addSelectionListener(new NewAxisListener(context));\r
-\r
- addVariable = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
- addVariable.setText("Add variable");\r
- addVariable.addSelectionListener(new NewVariableListener(context));\r
-\r
- remove = new Button(buttonComposite, additionalSupport, SWT.NONE);\r
- remove.setText("Remove");\r
- remove.addSelectionListener(new RemoveListener(context));\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutVertical() {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
-\r
- GridDataFactory.fillDefaults().hint(220, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
-\r
- // Scrolled composite for displaying properties of a selection in explorer\r
- GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 210).span(1, 1).grab(true, false).applyTo(propertyContainer);\r
- GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
-\r
- // Buttons for adding axis and variables and removing selected items from explorer\r
- GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutHorizontal(boolean wideScreen) {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
-\r
- GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
-\r
- // Scrolled composite for displaying properties of a selection in explorer\r
- GridDataFactory.fillDefaults().hint(SWT.DEFAULT, SWT.DEFAULT).span(1, 2).grab(true, true).applyTo(propertyContainer);\r
- GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
-\r
- // Buttons for adding axis and variables and removing selected items from explorer\r
- GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011, 2014 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.jfreechart.chart.properties.xyline;
+
+import java.util.List;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.NodeContext;
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;
+import org.simantics.browsing.ui.swt.widgets.Button;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.PossibleObjectWithType;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.jfreechart.chart.properties.AdjustableTab;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.utils.datastructures.ArrayMap;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * PropertyTab displaying properties of axis and variables of a chart
+ *
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class XYLineAxisAndVariablesTab extends AdjustableTab {
+
+ private GraphExplorerComposite explorer;
+ private ScrolledComposite propertyContainer;
+ private Button addAxis, addVariable, remove;
+ private WidgetSupportImpl additionalSupport;
+ private Composite buttonComposite;
+
+ public XYLineAxisAndVariablesTab(Object id) {
+ super(id);
+ additionalSupport = new WidgetSupportImpl();
+ }
+
+ /**
+ * Updates the content of propertyContainer
+ * @param context
+ */
+ private void updateSelection(ISessionContext context) {
+ ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);
+ IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();
+ final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);
+ if(resource == null)
+ return;
+
+ // Get the type of the selected node (axis or series)
+ String typeUri = null;
+ try {
+ typeUri = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ if(graph.isInstanceOf(resource, jfree.Axis))
+ return graph.getURI(jfree.Axis);
+ else if (graph.isInstanceOf(resource, jfree.Series))
+ return graph.getURI(jfree.Series);
+ return null;
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ // Create a PropertyComposite for the selected node
+ if(typeUri != null) {
+
+ for(Control child : propertyContainer.getChildren()) {
+ child.dispose();
+ }
+
+ if(typeUri.equals(JFreeChartResource.URIs.Axis)) {
+ AxisPropertyComposite apc = new AxisPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE, isVertical());
+ propertyContainer.setContent(apc);
+ Point size = apc.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ } else if(typeUri.equals(JFreeChartResource.URIs.Series)) {
+ SeriesPropertyComposite spc = new SeriesPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE);
+ propertyContainer.setContent(spc);
+ Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ }
+ }
+
+ additionalSupport.fireInput(context, selection);
+ }
+
+ /**
+ * SelectionListener for adding a new range axis to a plot
+ * @author Teemu Lempinen
+ *
+ */
+ private class NewAxisListener extends SelectionListenerImpl<Resource> {
+
+ public NewAxisListener(ISessionContext context) {
+ super(context);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, Resource chart) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));
+ if(plot != null) {
+ Resource rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);
+ if(rangeAxis != null) {
+ Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);
+ ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * SelectionListener for adding a new variable to a plot
+ * @author Teemu Lempinen
+ *
+ */
+ private class NewVariableListener extends SelectionListenerImpl<Resource> {
+
+ public NewVariableListener(ISessionContext context) {
+ super(context);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, Resource input) throws DatabaseException {
+ NodeContext nc = explorer.getExplorer().getRoot();
+ if(nc == null)
+ return;
+
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ if(input == null) {
+ Resource chart = AdaptionUtils.adaptToSingle(nc, Resource.class);
+ if(chart == null) return;
+ Resource plot = graph.syncRequest(new PossibleObjectWithType(chart, l0.ConsistsOf, jfree.Plot));
+ if(plot == null) return;
+ Resource rangelist = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);
+ if(rangelist == null) return;
+ List<Resource> list = ListUtils.toList(graph, rangelist);
+ if(list == null || list.isEmpty()) return;
+ input = list.get(0);
+ }
+
+ Resource dataset;
+ if(graph.isInstanceOf(input, jfree.Series)) {
+ // Selected resource is series. Add to same dataset
+ dataset = graph.getPossibleObject(input, l0.PartOf);
+ } else {
+ // Selected resource is axis. Find the dataset it is mapped to or create dataset if not created already
+ dataset = graph.getPossibleObject(input, jfree.Dataset_mapToRangeAxis_Inverse);
+ if(dataset == null) {
+ Resource plot = graph.getPossibleObject(input, l0.PartOf);
+ if(plot == null) return;
+ Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);
+ if(domainAxis == null) return;
+ ChartUtils.createXYDataset(graph, plot, domainAxis, input);
+ }
+ }
+
+ if(dataset != null) {
+ // Create series with no rvi
+ ChartUtils.createSeries(graph, dataset, null);
+ }
+ }
+ }
+
+
+ /**
+ * SelectionListener for remove button
+ * @author Teemu Lempinen
+ *
+ */
+ private class RemoveListener extends SelectionListenerImpl<Resource> {
+
+ public RemoveListener(ISessionContext context) {
+ super(context);
+ }
+
+ /**
+ * Removes selected resource from explorer
+ */
+ @Override
+ public void apply(WriteGraph graph, Resource input) throws DatabaseException {
+ if(input == null)
+ return;
+
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource list = null;
+ if(graph.isInstanceOf(input, jfree.Series)) {
+ // Remove series from dataset and seriesList
+ Resource dataset = graph.getPossibleObject(input, l0.PartOf);
+ if(dataset != null)
+ list = graph.getPossibleObject(dataset, jfree.Dataset_seriesList);
+ } else {
+ // Remove associated dataset
+ Resource dataset = graph.getPossibleObject(input, jfree.Dataset_mapToRangeAxis_Inverse);
+ if(dataset != null) {
+ graph.deny(dataset, jfree.Dataset_mapToDomainAxis);
+ graph.deny(dataset, jfree.Dataset_mapToRangeAxis);
+ RemoverUtil.remove(graph, dataset);
+ }
+
+ // Remove axis from plot and rangeAxisList
+ Resource plot = graph.getPossibleObject(input, l0.PartOf);
+ if(plot != null)
+ list = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);
+ }
+ if(list != null)
+ ListUtils.removeElement(graph, list, input);
+ RemoverUtil.remove(graph, input);
+ }
+ }
+
+
+ @Override
+ protected void createAndAddControls(Composite body, IWorkbenchSite site,
+ final ISessionContext context, WidgetSupport support) {
+ composite = new Composite(body, SWT.NONE);
+
+ // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis
+ explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);
+ explorer.setBrowseContexts(JFreeChartResource.URIs.ChartAxisAndVariablesBrowseContext);
+ explorer.setInputSource(new SingleSelectionInputSource(
+ Resource.class));
+ explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning
+ explorer.finish();
+
+ ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ updateSelection(context);
+ }
+ });
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);
+ propertyContainer.setExpandHorizontal(true);
+ propertyContainer.setExpandVertical(true);
+
+ // Buttons for adding axis and variables and removing selected items from explorer
+ buttonComposite = new Composite(composite, SWT.NONE);
+
+ addAxis = new Button(buttonComposite, support, SWT.NONE);
+ addAxis.setText("Add axis");
+ addAxis.addSelectionListener(new NewAxisListener(context));
+
+ addVariable = new Button(buttonComposite, additionalSupport, SWT.NONE);
+ addVariable.setText("Add variable");
+ addVariable.addSelectionListener(new NewVariableListener(context));
+
+ remove = new Button(buttonComposite, additionalSupport, SWT.NONE);
+ remove.setText("Remove");
+ remove.addSelectionListener(new RemoveListener(context));
+ }
+
+ @Override
+ protected void createControlLayoutVertical() {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);
+
+ GridDataFactory.fillDefaults().hint(220, SWT.DEFAULT).grab(false, true).applyTo(explorer);
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 210).span(1, 1).grab(true, false).applyTo(propertyContainer);
+ GridLayoutFactory.fillDefaults().applyTo(propertyContainer);
+
+ // Buttons for adding axis and variables and removing selected items from explorer
+ GridDataFactory.fillDefaults().applyTo(buttonComposite);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);
+ }
+
+ @Override
+ protected void createControlLayoutHorizontal(boolean wideScreen) {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);
+
+ GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ GridDataFactory.fillDefaults().hint(SWT.DEFAULT, SWT.DEFAULT).span(1, 2).grab(true, true).applyTo(propertyContainer);
+ GridLayoutFactory.fillDefaults().applyTo(propertyContainer);
+
+ // Buttons for adding axis and variables and removing selected items from explorer
+ GridDataFactory.fillDefaults().applyTo(buttonComposite);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);
+ }
+}
@L0.singleProperty L0.HasName
>-- SYSDYN.ExternalFunctionFile.externalFile --> L0.ByteArray <R L0.HasProperty
-SYSDYN.SysdynModelicaFunctionLibrary <T L0.Library
- @L0.singleProperty L0.HasName
+SYSDYN.SysdynModelicaFunctionLibrary <T L0.Library
+ @L0.singleProperty L0.HasName
SYSDYN.SysdynModelicaFunction.InterfaceVariable <T L0.Entity
@L0.singleProperty L0.HasName
-L0 = <http://www.simantics.org/Layer0-1.1>\r
-VP = <http://www.simantics.org/Viewpoint-1.2>\r
-SIMU = <http://www.simantics.org/Simulation-1.1>\r
-PROJECT = <http://www.simantics.org/Project-1.2>\r
-IMAGE = <http://www.simantics.org/Image2-1.2>\r
-ACT = <http://www.simantics.org/Action-1.1>\r
-MOD = <http://www.simantics.org/Modeling-1.2>\r
-STR = <http://www.simantics.org/Structural-1.2>\r
-SYSDYN = <http://www.simantics.org/Sysdyn-1.1>\r
-SILK = <http://www.simantics.org/Silk-1.1>\r
-SHEET = <http://www.simantics.org/Spreadsheet-1.2>\r
-JFREE = <http://www.simantics.org/JFreeChart-1.0>\r
-SEL = <http://www.simantics.org/SelectionView-1.2>\r
-\r
-SYSDYN.SysdynSelectionProcessor : SEL.SelectionProcessorContribution\r
-\r
-SBC = SYSDYN.ModelingBrowseContext : VP.BrowseContext\r
-SAC = SYSDYN.ModelingActionContext : VP.BrowseContext\r
- VP.BrowseContext.IsIncludedIn PROJECT.ProjectActionContext\r
-\r
-SBC.VariableNodeType <T VP.NodeType\r
- @L0.assert VP.HasContentType "Variable"\r
-\r
-SYSDYN.BrowseContextContribution : VP.BrowseContextContribution\r
- VP.BrowseContextContribution.HasType SYSDYN.SysdynModel\r
- VP.BrowseContextContribution.HasBrowseContext SBC\r
-\r
-////////////////////////////////\r
-// From Project Viewpoint\r
-////////////////////////////////\r
-SBC\r
- @VP.relationChildRule PROJECT.Project L0.ConsistsOf SYSDYN.SysdynModel\r
-\r
-SBC\r
- VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
- VP.VisualsContribution.HasNodeType L0.Entity\r
- VP.VisualsContribution.HasRule VP.ResourceLabelLabelRule\r
- VP.VisualsContribution.HasRule VP.ResourceNameModifierRule\r
-\r
-SBC\r
- @VP.constantImageRule SYSDYN.SysdynModel SILK.chart_organisation\r
-\r
-\r
-////////////////////////////////\r
-// From Modeling Viewpoint\r
-////////////////////////////////\r
-MBC = MOD.ModelingBrowseContext\r
-\r
-SBC\r
- @VP.relationChildRule SYSDYN.SysdynModel SIMU.HasConfiguration MBC.Configuration\r
-\r
-SBC\r
- @VP.constantLabelRule MBC.Configuration "Configuration"\r
- \r
-SBC\r
- @VP.constantImageRule MBC.Configuration SILK.bricks\r
- @VP.constantImageRule STR.Component SILK.brick\r
- @VP.constantImageRule STR.Composite SILK.bricks\r
-\r
-\r
-////////////////////////////////\r
-// Sysdyn-specific Viewpoint\r
-////////////////////////////////\r
-\r
-SBC.ModuleSymbolNodeType <T VP.NodeType\r
-SBC.ModuleSymbol : SBC.ModuleSymbolNodeType\r
-\r
-BuiltinFunctions = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions>\r
-SBC.BuiltinFunctions : VP.ResourceNodeType\r
-SBC.ModuleTypeChildRule : VP.ChildRule\r
-SBC.ModuleContentChildRule : VP.ChildRule\r
-SBC.VariableChildRule : VP.ChildRule\r
-SBC.ExperimentsFolder : VP.ResourceNodeType\r
-SBC.FunctionsFolder : VP.ResourceNodeType\r
-SBC.SharedFunctionsFolder : VP.ResourceNodeType\r
-SBC.Variable : SBC.VariableNodeType\r
-\r
-SBC\r
- @VP.relationChildRuleWithFolder SYSDYN.SysdynModel L0.ConsistsOf SYSDYN.Experiment\r
- SBC.ExperimentsFolder\r
- @VP.relationChildRule SYSDYN.Experiment SYSDYN.Experiment.result SYSDYN.Result\r
-\r
- @VP.customChildRule MBC.Configuration SBC.VariableChildRule\r
- SBC.Variable\r
- @VP.customChildRule SBC.Variable SBC.VariableChildRule\r
- SBC.Variable\r
-\r
- @VP.relationChildRule MBC.Configuration L0.ConsistsOf SHEET.Book\r
- @VP.relationChildRule SHEET.Book L0.ConsistsOf SHEET.Spreadsheet\r
-\r
-\r
- // Function libraries \r
- // Functions folder \r
- @VP.relationChildRuleWithFolder SYSDYN.SysdynModel L0.ConsistsOf SYSDYN.SysdynModelicaFunction\r
- SBC.FunctionsFolder \r
- @VP.relationChildRule SBC.FunctionsFolder L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary\r
-\r
- // Function libraries\r
- @VP.relationChildRule SYSDYN.SysdynModelicaFunctionLibrary L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary \r
- @VP.relationChildRule SYSDYN.SysdynModelicaFunctionLibrary L0.ConsistsOf SYSDYN.SysdynModelicaFunction\r
- @VP.relationChildRule SYSDYN.SharedFunctionOntology L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary \r
- @VP.relationChildRule SYSDYN.SharedFunctionOntology L0.ConsistsOf SYSDYN.SysdynModelicaFunction \r
-\r
- // Built-in functions\r
- VP.BrowseContext.HasChildContribution _ : VP.ChildContribution\r
- VP.ChildContribution.HasParentNodeType SBC.FunctionsFolder\r
- VP.ChildContribution.HasChildNodeType SBC.BuiltinFunctions\r
- VP.ChildContribution.HasRule _ : VP.ConstantChildRule\r
- VP.ConstantChildRule.HasChild BuiltinFunctions \r
- @VP.relationChildRule SBC.BuiltinFunctions L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary\r
- @VP.relationChildRule SBC.BuiltinFunctions L0.ConsistsOf SYSDYN.SysdynModelicaFunction\r
-\r
- // Shared functions linked to a model \r
- @VP.relationChildRuleWithFolder SBC.FunctionsFolder L0.IsLinkedTo SYSDYN.SharedFunctionOntology \r
- SBC.SharedFunctionsFolder\r
-\r
-\r
- // Modules \r
- @VP.equalContentChildRule MOD.StructuralModel\r
- SBC.ModulesFolder : VP.ResourceNodeType \r
- @VP.customChildRule SBC.ModulesFolder SBC.ModuleTypeChildRule\r
- SBC.ModuleSymbol\r
- @VP.customChildRule SBC.ModuleSymbol SBC.ModuleContentChildRule STR.Component \r
- \r
- // Charts\r
- @VP.relationChildRuleWithFolder MOD.StructuralModel L0.ConsistsOf JFREE.Chart\r
- SBC.ChartsFolder : VP.ResourceNodeType \r
- \r
-// Labels \r
-SBC.VariableNameLabelRule : VP.LabelRule\r
-SBC.ModuleTypeLabelRule : VP.LabelRule\r
- \r
-SBC\r
- @VP.constantLabelRule SBC.ExperimentsFolder "Experiments"\r
- @VP.constantLabelRule SBC.FunctionsFolder "Functions"\r
- @VP.constantLabelRule SBC.ChartsFolder "Charts"\r
- @VP.constantLabelRule SBC.ModulesFolder "Modules"\r
- @VP.constantLabelRule SBC.SharedFunctionsFolder "Shared Functions" \r
- @VP.constantLabelRule SHEET.Book "Spreadsheets"\r
- \r
- @VP.customLabelRule SIMU.Run PROJECT.ProjectBrowseContext.RunLabelRule\r
- @VP.customLabelRule SBC.BuiltinFunctions VP.ResourceNameLabelRule\r
- @VP.customLabelRule SBC.ModuleSymbol SBC.ModuleTypeLabelRule\r
- @VP.customLabelRule SBC.Variable SBC.VariableNameLabelRule\r
- @VP.customLabelRule SHEET.Spreadsheet VP.ResourceNameLabelRule \r
- @VP.customLabelRule SYSDYN.HistoryDataset VP.ResourceLabelLabelRule \r
- @VP.customLabelRule JFREE.Chart VP.ResourceLabelLabelRule \r
- \r
-// Modifiers\r
-SBC\r
- @VP.customLabelRule SYSDYN.SysdynModelicaFunction VP.ResourceNameModifierRule \r
- @VP.customLabelRule SYSDYN.HistoryDataset VP.ResourceLabelModifierRule \r
- @VP.customLabelRule JFREE.Chart VP.ResourceLabelModifierRule \r
- @VP.customLabelRule SBC.FunctionsFolder VP.NoModifierRule \r
- \r
- \r
-// Decorations\r
-SBC.ActiveLabelDecorationRule : VP.ConstantLabelDecorationRule\r
- VP.ConstantLabelDecorationRule.HasFormat "%s [ACTIVE]"\r
- VP.ConstantLabelDecorationRule.HasStyle "B" \r
- \r
- \r
-// Images\r
-SBC.VariableImageRule : VP.ImageRule\r
-SBC.ChartImageRule : VP.ImageRule\r
-SBC.ResultImageRule : VP.ImageRule\r
-\r
-SBC\r
- @VP.customImageRule SBC.Variable SBC.VariableImageRule\r
- @VP.customImageRule JFREE.Chart SBC.ChartImageRule\r
- @VP.customImageRule SYSDYN.Result SBC.ResultImageRule \r
- \r
-\r
- @VP.constantImageRule SBC.ExperimentsFolder SILK.folder\r
- @VP.constantImageRule SBC.FunctionsFolder SILK.folder\r
- @VP.constantImageRule SBC.SharedFunctionsFolder SILK.folder_link \r
- @VP.constantImageRule SYSDYN.SysdynModelicaFunctionLibrary SILK.folder \r
- @VP.constantImageRule SYSDYN.SysdynModelicaFunction SILK.brick\r
- @VP.constantImageRule SBC.ModulesFolder SILK.folder \r
- @VP.constantImageRule SBC.ModuleSymbol SILK.bricks\r
- @VP.constantImageRule SBC.BuiltinFunctions SILK.folder_link\r
- @VP.constantImageRule SYSDYN.SharedFunctionOntology SILK.folder_link\r
- @VP.constantImageRule SHEET.Book SILK.table_multiple\r
- @VP.constantImageRule SHEET.Spreadsheet SILK.table \r
- @VP.constantImageRule SYSDYN.BasicExperiment SILK.time \r
- @VP.constantImageRule SYSDYN.PlaybackExperiment SILK.timeline_marker \r
- @VP.constantImageRule SBC.ChartsFolder SILK.folder \r
- @VP.constantImageRule SYSDYN.HistoryDataset SILK.table \r
-\r
-SBC \r
- // Active experiment \r
- VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
- VP.VisualsContribution.HasNodeType SYSDYN.Experiment\r
- VP.VisualsContribution.HasCondition _ : VP.HasStatementTest\r
- VP.HasStatementTest.HasRelation SIMU.IsActive\r
- VP.VisualsContribution.HasRule SBC.ActiveLabelDecorationRule \r
- \r
- // Show result in charts \r
- VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution\r
- VP.VisualsContribution.HasNodeType SYSDYN.Result\r
- VP.VisualsContribution.HasCondition _ : VP.HasStatementTest\r
- VP.HasStatementTest.HasRelation SYSDYN.Result.showResult\r
- VP.VisualsContribution.HasRule SBC.ActiveLabelDecorationRule \r
- \r
- \r
-// Actions \r
-ACTIONS = SAC.Actions : L0.Library \r
- \r
-// NEW -Actions \r
-ACTIONS.NewModuleType : ACT.Action\r
-ACTIONS.NewEnumeration : ACT.Action\r
-ACTIONS.NewFunction : ACT.Action\r
-ACTIONS.NewFunctionLibrary : ACT.Action\r
-ACTIONS.NewSharedFunctionLibrary : ACT.Action\r
-ACTIONS.NewExperiment : ACT.Action\r
-ACTIONS.NewSimulationPlaybackExperiment : ACT.Action\r
-ACTIONS.NewLineChart : ACT.Action\r
-ACTIONS.NewBarChart : ACT.Action\r
-ACTIONS.NewPieChart : ACT.Action\r
-ACTIONS.NewSheet : ACT.Action\r
-ACTIONS.NewHistoryData : ACT.Action\r
- \r
-SAC\r
- @VP.actionContribution "Module" SBC.ModulesFolder SILK.bricks VP.NewActionCategory ACTIONS.NewModuleType\r
- @VP.actionContribution "Enumeration" MBC.Configuration SILK.brick VP.NewActionCategory ACTIONS.NewEnumeration\r
- @VP.actionContribution "Enumeration" SBC.ModuleSymbol SILK.brick VP.NewActionCategory ACTIONS.NewEnumeration\r
- @VP.actionContribution "Function" SBC.FunctionsFolder SILK.brick VP.NewActionCategory ACTIONS.NewFunction\r
- @VP.actionContribution "Function" SYSDYN.SysdynModelicaFunctionLibrary SILK.brick VP.NewActionCategory ACTIONS.NewFunction\r
- @VP.actionContribution "Function" SYSDYN.SharedFunctionOntology SILK.brick VP.NewActionCategory ACTIONS.NewFunction\r
- @VP.actionContribution "Function Library" SBC.FunctionsFolder SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary\r
- @VP.actionContribution "Function Library" SYSDYN.SysdynModelicaFunctionLibrary SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary\r
- @VP.actionContribution "Function Library" SYSDYN.SharedFunctionOntology SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary \r
- @VP.actionContribution "Shared Function Library" SBC.SharedFunctionsFolder SILK.folder VP.NewActionCategory ACTIONS.NewSharedFunctionLibrary \r
- @VP.actionContribution "Experiment" SBC.ExperimentsFolder SILK.time VP.NewActionCategory ACTIONS.NewExperiment\r
- @VP.actionContribution "Simulation Playback Experiment" SBC.ExperimentsFolder SILK.timeline_marker VP.NewActionCategory ACTIONS.NewSimulationPlaybackExperiment\r
- @VP.actionContribution "Line Chart" SBC.ChartsFolder SILK.chart_line VP.NewActionCategory ACTIONS.NewLineChart\r
- @VP.actionContribution "Pie Chart" SBC.ChartsFolder SILK.chart_pie VP.NewActionCategory ACTIONS.NewPieChart\r
- @VP.actionContribution "Bar Chart" SBC.ChartsFolder SILK.chart_bar VP.NewActionCategory ACTIONS.NewBarChart\r
- @VP.actionContribution "Sheet" SHEET.Book SILK.table VP.NewActionCategory ACTIONS.NewSheet \r
- @VP.actionContribution "History Data" SYSDYN.Experiment SILK.table VP.NewActionCategory ACTIONS.NewHistoryData \r
-\r
-\r
-// Drop actions\r
-ACTIONS.FunctionDropAction : ACT.DropAction\r
-ACTIONS.ChartDropAction : ACT.DropAction\r
-\r
-SBC\r
- @VP.dropActionContribution SBC.FunctionsFolder ACTIONS.FunctionDropAction 1.0\r
- @VP.dropActionContribution SYSDYN.SysdynModelicaFunction ACTIONS.FunctionDropAction 1.0\r
- @VP.dropActionContribution SYSDYN.SysdynModelicaFunctionLibrary ACTIONS.FunctionDropAction 1.0\r
- @VP.dropActionContribution SYSDYN.SharedFunctionOntology ACTIONS.FunctionDropAction 1.0 \r
- @VP.dropActionContribution JFREE.Chart ACTIONS.ChartDropAction 1.0 \r
-\r
+L0 = <http://www.simantics.org/Layer0-1.1>
+VP = <http://www.simantics.org/Viewpoint-1.2>
+SIMU = <http://www.simantics.org/Simulation-1.1>
+PROJECT = <http://www.simantics.org/Project-1.2>
+IMAGE = <http://www.simantics.org/Image2-1.2>
+ACT = <http://www.simantics.org/Action-1.1>
+MOD = <http://www.simantics.org/Modeling-1.2>
+STR = <http://www.simantics.org/Structural-1.2>
+SYSDYN = <http://www.simantics.org/Sysdyn-1.1>
+SILK = <http://www.simantics.org/Silk-1.1>
+SHEET = <http://www.simantics.org/Spreadsheet-1.2>
+JFREE = <http://www.simantics.org/JFreeChart-1.0>
+SEL = <http://www.simantics.org/SelectionView-1.2>
+
+SYSDYN.SysdynSelectionProcessor : SEL.SelectionProcessorContribution
+
+SBC = SYSDYN.ModelingBrowseContext : VP.BrowseContext
+SAC = SYSDYN.ModelingActionContext : VP.BrowseContext
+ VP.BrowseContext.IsIncludedIn PROJECT.ProjectActionContext
+
+SBC.VariableNodeType <T VP.NodeType
+ @L0.assert VP.HasContentType "Variable"
+
+SYSDYN.BrowseContextContribution : VP.BrowseContextContribution
+ VP.BrowseContextContribution.HasType SYSDYN.SysdynModel
+ VP.BrowseContextContribution.HasBrowseContext SBC
+
+////////////////////////////////
+// From Project Viewpoint
+////////////////////////////////
+SBC
+ @VP.relationChildRule PROJECT.Project L0.ConsistsOf SYSDYN.SysdynModel
+
+SBC
+ VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution
+ VP.VisualsContribution.HasNodeType L0.Entity
+ VP.VisualsContribution.HasRule VP.ResourceLabelLabelRule
+ VP.VisualsContribution.HasRule VP.ResourceNameModifierRule
+
+SBC
+ @VP.constantImageRule SYSDYN.SysdynModel SILK.chart_organisation
+
+
+////////////////////////////////
+// From Modeling Viewpoint
+////////////////////////////////
+MBC = MOD.ModelingBrowseContext
+
+SBC
+ @VP.relationChildRule SYSDYN.SysdynModel SIMU.HasConfiguration MBC.Configuration
+
+SBC
+ @VP.constantLabelRule MBC.Configuration "Configuration"
+
+SBC
+ @VP.constantImageRule MBC.Configuration SILK.bricks
+ @VP.constantImageRule STR.Component SILK.brick
+ @VP.constantImageRule STR.Composite SILK.bricks
+
+
+////////////////////////////////
+// Sysdyn-specific Viewpoint
+////////////////////////////////
+
+SBC.ModuleSymbolNodeType <T VP.NodeType
+SBC.ModuleSymbol : SBC.ModuleSymbolNodeType
+
+BuiltinFunctions = <http://www.simantics.org/Sysdyn-1.1/Built-in Functions>
+SBC.BuiltinFunctions : VP.ResourceNodeType
+SBC.ModuleTypeChildRule : VP.ChildRule
+SBC.ModuleContentChildRule : VP.ChildRule
+SBC.VariableChildRule : VP.ChildRule
+SBC.ExperimentsFolder : VP.ResourceNodeType
+SBC.FunctionsFolder : VP.ResourceNodeType
+SBC.SharedFunctionsFolder : VP.ResourceNodeType
+SBC.Variable : SBC.VariableNodeType
+SBC.InitialConditionFolder : VP.ResourceNodeType
+
+SBC
+ @VP.relationChildRuleWithFolder SYSDYN.SysdynModel L0.ConsistsOf SYSDYN.Experiment
+ SBC.ExperimentsFolder
+ @VP.relationChildRule SYSDYN.Experiment SYSDYN.Experiment.result SYSDYN.Result
+
+ // Initial Conditions
+ @VP.relationChildRuleWithFolder SYSDYN.SysdynModel L0.ConsistsOf SYSDYN.InitialCondition
+ SBC.InitialConditionFolder
+
+ @VP.customChildRule MBC.Configuration SBC.VariableChildRule
+ SBC.Variable
+ @VP.customChildRule SBC.Variable SBC.VariableChildRule
+ SBC.Variable
+
+ @VP.relationChildRule MBC.Configuration L0.ConsistsOf SHEET.Book
+ @VP.relationChildRule SHEET.Book L0.ConsistsOf SHEET.Spreadsheet
+
+
+ // Function libraries
+ // Functions folder
+ @VP.relationChildRuleWithFolder SYSDYN.SysdynModel L0.ConsistsOf SYSDYN.SysdynModelicaFunction
+ SBC.FunctionsFolder
+ @VP.relationChildRule SBC.FunctionsFolder L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary
+
+ // Function libraries
+ @VP.relationChildRule SYSDYN.SysdynModelicaFunctionLibrary L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary
+ @VP.relationChildRule SYSDYN.SysdynModelicaFunctionLibrary L0.ConsistsOf SYSDYN.SysdynModelicaFunction
+ @VP.relationChildRule SYSDYN.SharedFunctionOntology L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary
+ @VP.relationChildRule SYSDYN.SharedFunctionOntology L0.ConsistsOf SYSDYN.SysdynModelicaFunction
+
+ // Built-in functions
+ VP.BrowseContext.HasChildContribution _ : VP.ChildContribution
+ VP.ChildContribution.HasParentNodeType SBC.FunctionsFolder
+ VP.ChildContribution.HasChildNodeType SBC.BuiltinFunctions
+ VP.ChildContribution.HasRule _ : VP.ConstantChildRule
+ VP.ConstantChildRule.HasChild BuiltinFunctions
+ @VP.relationChildRule SBC.BuiltinFunctions L0.ConsistsOf SYSDYN.SysdynModelicaFunctionLibrary
+ @VP.relationChildRule SBC.BuiltinFunctions L0.ConsistsOf SYSDYN.SysdynModelicaFunction
+
+ // Shared functions linked to a model
+ @VP.relationChildRuleWithFolder SBC.FunctionsFolder L0.IsLinkedTo SYSDYN.SharedFunctionOntology
+ SBC.SharedFunctionsFolder
+
+
+ // Modules
+ @VP.equalContentChildRule MOD.StructuralModel
+ SBC.ModulesFolder : VP.ResourceNodeType
+ @VP.customChildRule SBC.ModulesFolder SBC.ModuleTypeChildRule
+ SBC.ModuleSymbol
+ @VP.customChildRule SBC.ModuleSymbol SBC.ModuleContentChildRule STR.Component
+
+ // Charts
+ @VP.relationChildRuleWithFolder MOD.StructuralModel L0.ConsistsOf JFREE.Chart
+ SBC.ChartsFolder : VP.ResourceNodeType
+
+// Labels
+SBC.VariableNameLabelRule : VP.LabelRule
+SBC.ModuleTypeLabelRule : VP.LabelRule
+
+SBC
+ @VP.constantLabelRule SBC.ExperimentsFolder "Experiments"
+ @VP.constantLabelRule SBC.FunctionsFolder "Functions"
+ @VP.constantLabelRule SBC.ChartsFolder "Charts"
+ @VP.constantLabelRule SBC.ModulesFolder "Modules"
+ @VP.constantLabelRule SBC.SharedFunctionsFolder "Shared Functions"
+ @VP.constantLabelRule SHEET.Book "Spreadsheets"
+ @VP.constantLabelRule SBC.InitialConditionFolder "Initial Conditions"
+
+ @VP.customLabelRule SIMU.Run PROJECT.ProjectBrowseContext.RunLabelRule
+ @VP.customLabelRule SBC.BuiltinFunctions VP.ResourceNameLabelRule
+ @VP.customLabelRule SBC.ModuleSymbol SBC.ModuleTypeLabelRule
+ @VP.customLabelRule SBC.Variable SBC.VariableNameLabelRule
+ @VP.customLabelRule SHEET.Spreadsheet VP.ResourceNameLabelRule
+ @VP.customLabelRule SYSDYN.HistoryDataset VP.ResourceLabelLabelRule
+ @VP.customLabelRule JFREE.Chart VP.ResourceLabelLabelRule
+
+// Modifiers
+SBC
+ @VP.customLabelRule SYSDYN.SysdynModelicaFunction VP.ResourceNameModifierRule
+ @VP.customLabelRule SYSDYN.HistoryDataset VP.ResourceLabelModifierRule
+ @VP.customLabelRule JFREE.Chart VP.ResourceLabelModifierRule
+ @VP.customLabelRule SBC.FunctionsFolder VP.NoModifierRule
+
+
+// Decorations
+SBC.ActiveLabelDecorationRule : VP.ConstantLabelDecorationRule
+ VP.ConstantLabelDecorationRule.HasFormat "%s [ACTIVE]"
+ VP.ConstantLabelDecorationRule.HasStyle "B"
+
+
+// Images
+SBC.VariableImageRule : VP.ImageRule
+SBC.ChartImageRule : VP.ImageRule
+SBC.ResultImageRule : VP.ImageRule
+
+SBC
+ @VP.customImageRule SBC.Variable SBC.VariableImageRule
+ @VP.customImageRule JFREE.Chart SBC.ChartImageRule
+ @VP.customImageRule SYSDYN.Result SBC.ResultImageRule
+
+ @VP.constantImageRule SBC.InitialConditionFolder SILK.folder
+ @VP.constantImageRule SBC.ExperimentsFolder SILK.folder
+ @VP.constantImageRule SBC.FunctionsFolder SILK.folder
+ @VP.constantImageRule SBC.SharedFunctionsFolder SILK.folder_link
+ @VP.constantImageRule SYSDYN.SysdynModelicaFunctionLibrary SILK.folder
+ @VP.constantImageRule SYSDYN.SysdynModelicaFunction SILK.text_italic_f
+ @VP.constantImageRule SBC.ModulesFolder SILK.folder
+ @VP.constantImageRule SBC.ModuleSymbol SILK.bricks
+ @VP.constantImageRule SBC.BuiltinFunctions SILK.folder_link
+ @VP.constantImageRule SYSDYN.SharedFunctionOntology SILK.folder_link
+ @VP.constantImageRule SHEET.Book SILK.table_multiple
+ @VP.constantImageRule SHEET.Spreadsheet SILK.table
+ @VP.constantImageRule SYSDYN.InitialCondition SILK.tag_red
+ @VP.constantImageRule SYSDYN.BasicExperiment SILK.time
+ @VP.constantImageRule SYSDYN.PlaybackExperiment SILK.timeline_marker
+ @VP.constantImageRule SYSDYN.GameExperiment SILK.time_go
+ @VP.constantImageRule SYSDYN.SensitivityAnalysisExperiment SILK.time_rainbow
+ @VP.constantImageRule SBC.ChartsFolder SILK.folder
+ @VP.constantImageRule SYSDYN.HistoryDataset SILK.table
+
+SBC
+ // Active experiment
+ VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution
+ VP.VisualsContribution.HasNodeType SYSDYN.Experiment
+ VP.VisualsContribution.HasCondition _ : VP.HasStatementTest
+ VP.HasStatementTest.HasRelation SIMU.IsActive
+ VP.VisualsContribution.HasRule SBC.ActiveLabelDecorationRule
+
+ // Show result in charts
+ VP.BrowseContext.HasVisualsContribution _ : VP.VisualsContribution
+ VP.VisualsContribution.HasNodeType SYSDYN.Result
+ VP.VisualsContribution.HasCondition _ : VP.HasStatementTest
+ VP.HasStatementTest.HasRelation SYSDYN.Result.showResult
+ VP.VisualsContribution.HasRule SBC.ActiveLabelDecorationRule
+
+
+// Actions
+ACTIONS = SAC.Actions : L0.Library
+
+// NEW -Actions
+ACTIONS.NewModuleType : ACT.Action
+ACTIONS.NewEnumeration : ACT.Action
+ACTIONS.NewFunction : ACT.Action
+ACTIONS.NewFunctionLibrary : ACT.Action
+ACTIONS.NewSharedFunctionLibrary : ACT.Action
+ACTIONS.NewExperiment : ACT.Action
+ACTIONS.NewSimulationPlaybackExperiment : ACT.Action
+ACTIONS.NewLineChart : ACT.Action
+ACTIONS.NewBarChart : ACT.Action
+ACTIONS.NewPieChart : ACT.Action
+ACTIONS.NewSheet : ACT.Action
+ACTIONS.NewHistoryData : ACT.Action
+ACTIONS.NewSensitivityAnalysisExperiment : ACT.Action
+ACTIONS.NewGameExperiment : ACT.Action
+ACTIONS.NewSensitivityChart : ACT.Action
+
+// IMPORT -Actions
+ACTIONS.ImportModule : ACT.Action
+ACTIONS.ImportFunctionLibrary : ACT.Action
+
+// EXPORT -Actions
+ACTIONS.ExportModule : ACT.Action
+ACTIONS.ExportFunctionLibrary : ACT.Action
+ACTIONS.ExportModel : ACT.Action
+
+// Misc -Actions
+ACTIONS.AssignIC : ACT.Action
+ACTIONS.ShowInCharts : ACT.Action
+ACTIONS.AssignSymbolGroups : ACT.Action
+ACTIONS.OpenDiagramEditorFromModel : ACT.Action
+
+// New
+SAC
+ @VP.actionContribution "Module" SBC.ModulesFolder SILK.bricks VP.NewActionCategory ACTIONS.NewModuleType
+ @VP.actionContribution "Enumeration" MBC.Configuration SILK.brick VP.NewActionCategory ACTIONS.NewEnumeration
+ @VP.actionContribution "Enumeration" SBC.ModuleSymbol SILK.brick VP.NewActionCategory ACTIONS.NewEnumeration
+ @VP.actionContribution "Function" SBC.FunctionsFolder SILK.brick VP.NewActionCategory ACTIONS.NewFunction
+ @VP.actionContribution "Function" SYSDYN.SysdynModelicaFunctionLibrary SILK.brick VP.NewActionCategory ACTIONS.NewFunction
+ @VP.actionContribution "Function" SYSDYN.SharedFunctionOntology SILK.brick VP.NewActionCategory ACTIONS.NewFunction
+ @VP.actionContribution "Function Library" SBC.FunctionsFolder SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary
+ @VP.actionContribution "Function Library" SYSDYN.SysdynModelicaFunctionLibrary SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary
+ @VP.actionContribution "Function Library" SYSDYN.SharedFunctionOntology SILK.folder VP.NewActionCategory ACTIONS.NewFunctionLibrary
+ @VP.actionContribution "Shared Function Library" SBC.SharedFunctionsFolder SILK.folder VP.NewActionCategory ACTIONS.NewSharedFunctionLibrary
+ @VP.actionContribution "Experiment" SBC.ExperimentsFolder SILK.time VP.NewActionCategory ACTIONS.NewExperiment
+ @VP.actionContribution "Simulation Playback Experiment" SBC.ExperimentsFolder SILK.timeline_marker VP.NewActionCategory ACTIONS.NewSimulationPlaybackExperiment
+ @VP.actionContribution "Game Experiment" SBC.ExperimentsFolder SILK.time_go VP.NewActionCategory ACTIONS.NewGameExperiment
+ @VP.actionContribution "Sensitity Analysis Experiment" SBC.ExperimentsFolder SILK.rainbow VP.NewActionCategory ACTIONS.NewSensitivityAnalysisExperiment
+ @VP.actionContribution "Line Chart" SBC.ChartsFolder SILK.chart_line VP.NewActionCategory ACTIONS.NewLineChart
+ @VP.actionContribution "Pie Chart" SBC.ChartsFolder SILK.chart_pie VP.NewActionCategory ACTIONS.NewPieChart
+ @VP.actionContribution "Bar Chart" SBC.ChartsFolder SILK.chart_bar VP.NewActionCategory ACTIONS.NewBarChart
+ @VP.actionContribution "Sensitivity Chart" SBC.ChartsFolder SILK.rainbow VP.NewActionCategory ACTIONS.NewSensitivityChart
+ @VP.actionContribution "Sheet" SHEET.Book SILK.table VP.NewActionCategory ACTIONS.NewSheet
+ @VP.actionContribution "History Data" SYSDYN.Experiment SILK.table VP.NewActionCategory ACTIONS.NewHistoryData
+
+// Import
+SAC
+ @VP.actionContribution "Module" SBC.ModulesFolder SILK.bricks VP.ImportActionCategory ACTIONS.ImportModule
+ @VP.actionContribution "Function Library" SBC.FunctionsFolder SILK.folder VP.ImportActionCategory ACTIONS.ImportFunctionLibrary
+ @VP.actionContribution "Function Library" SYSDYN.SysdynModelicaFunctionLibrary SILK.folder VP.ImportActionCategory ACTIONS.ImportFunctionLibrary
+ @VP.actionContribution "Function Library" SYSDYN.SharedFunctionOntology SILK.folder VP.ImportActionCategory ACTIONS.ImportFunctionLibrary
+
+// Export
+SAC
+ @VP.actionContribution "Module" SBC.ModuleSymbol SILK.bricks VP.ExportActionCategory ACTIONS.ExportModule
+ @VP.actionContribution "Function Library" SYSDYN.SysdynModelicaFunctionLibrary SILK.folder VP.ExportActionCategory ACTIONS.ExportFunctionLibrary
+ @VP.actionContribution "Function Library" SYSDYN.SharedFunctionOntology SILK.folder VP.ExportActionCategory ACTIONS.ExportFunctionLibrary
+ @VP.actionContribution "Model" SYSDYN.SysdynModel SILK.chart_organisation VP.ExportActionCategory ACTIONS.ExportModel
+
+// Misc
+SAC
+ @VP.actionContribution "Assign IC" SYSDYN.Experiment SILK.play_blue VP.EditActionCategory ACTIONS.AssignIC
+ @VP.actionContribution "Show in charts" SYSDYN.HistoryDataset SILK.table VP.EditActionCategory ACTIONS.ShowInCharts
+ @VP.actionContribution "Assign Symbol Groups..." SBC.ModuleSymbol SILK.link_edit VP.EditActionCategory ACTIONS.AssignSymbolGroups
+ @VP.actionContribution "Open Diagram Editor" SYSDYN.SysdynModel SILK.bricks VP.EditActionCategory ACTIONS.OpenDiagramEditorFromModel
+
+// Drop actions
+ACTIONS.FunctionDropAction : ACT.DropAction
+ACTIONS.ChartDropAction : ACT.DropAction
+
+SBC
+ @VP.dropActionContribution SBC.FunctionsFolder ACTIONS.FunctionDropAction 1.0
+ @VP.dropActionContribution SYSDYN.SysdynModelicaFunction ACTIONS.FunctionDropAction 1.0
+ @VP.dropActionContribution SYSDYN.SysdynModelicaFunctionLibrary ACTIONS.FunctionDropAction 1.0
+ @VP.dropActionContribution SYSDYN.SharedFunctionOntology ACTIONS.FunctionDropAction 1.0
+ @VP.dropActionContribution JFREE.Chart ACTIONS.ChartDropAction 1.0
+
public final Resource ModelBrowser;
public final Resource ModelingActionContext;
public final Resource ModelingActionContext_Actions;
+ public final Resource ModelingActionContext_Actions_AssignIC;
+ public final Resource ModelingActionContext_Actions_AssignSymbolGroups;
public final Resource ModelingActionContext_Actions_ChartDropAction;
+ public final Resource ModelingActionContext_Actions_ExportFunctionLibrary;
+ public final Resource ModelingActionContext_Actions_ExportModel;
+ public final Resource ModelingActionContext_Actions_ExportModule;
public final Resource ModelingActionContext_Actions_FunctionDropAction;
+ public final Resource ModelingActionContext_Actions_ImportFunctionLibrary;
+ public final Resource ModelingActionContext_Actions_ImportModule;
public final Resource ModelingActionContext_Actions_NewBarChart;
public final Resource ModelingActionContext_Actions_NewEnumeration;
public final Resource ModelingActionContext_Actions_NewExperiment;
public final Resource ModelingActionContext_Actions_NewFunction;
public final Resource ModelingActionContext_Actions_NewFunctionLibrary;
+ public final Resource ModelingActionContext_Actions_NewGameExperiment;
public final Resource ModelingActionContext_Actions_NewHistoryData;
public final Resource ModelingActionContext_Actions_NewLineChart;
public final Resource ModelingActionContext_Actions_NewModuleType;
public final Resource ModelingActionContext_Actions_NewPieChart;
+ public final Resource ModelingActionContext_Actions_NewSensitivityAnalysisExperiment;
+ public final Resource ModelingActionContext_Actions_NewSensitivityChart;
public final Resource ModelingActionContext_Actions_NewSharedFunctionLibrary;
public final Resource ModelingActionContext_Actions_NewSheet;
public final Resource ModelingActionContext_Actions_NewSimulationPlaybackExperiment;
+ public final Resource ModelingActionContext_Actions_OpenDiagramEditorFromModel;
+ public final Resource ModelingActionContext_Actions_ShowInCharts;
public final Resource ModelingBrowseContext;
public final Resource ModelingBrowseContext_ActiveLabelDecorationRule;
public final Resource ModelingBrowseContext_BuiltinFunctions;
public final Resource ModelingBrowseContext_ChartsFolder;
public final Resource ModelingBrowseContext_ExperimentsFolder;
public final Resource ModelingBrowseContext_FunctionsFolder;
+ public final Resource ModelingBrowseContext_InitialConditionFolder;
public final Resource ModelingBrowseContext_ModuleContentChildRule;
public final Resource ModelingBrowseContext_ModuleSymbol;
public final Resource ModelingBrowseContext_ModuleSymbolNodeType;
public static final String ModelBrowser = "http://www.simantics.org/Sysdyn-1.1/ModelBrowser";
public static final String ModelingActionContext = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext";
public static final String ModelingActionContext_Actions = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions";
+ public static final String ModelingActionContext_Actions_AssignIC = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/AssignIC";
+ public static final String ModelingActionContext_Actions_AssignSymbolGroups = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/AssignSymbolGroups";
public static final String ModelingActionContext_Actions_ChartDropAction = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ChartDropAction";
+ public static final String ModelingActionContext_Actions_ExportFunctionLibrary = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ExportFunctionLibrary";
+ public static final String ModelingActionContext_Actions_ExportModel = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ExportModel";
+ public static final String ModelingActionContext_Actions_ExportModule = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ExportModule";
public static final String ModelingActionContext_Actions_FunctionDropAction = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/FunctionDropAction";
+ public static final String ModelingActionContext_Actions_ImportFunctionLibrary = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ImportFunctionLibrary";
+ public static final String ModelingActionContext_Actions_ImportModule = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ImportModule";
public static final String ModelingActionContext_Actions_NewBarChart = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewBarChart";
public static final String ModelingActionContext_Actions_NewEnumeration = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewEnumeration";
public static final String ModelingActionContext_Actions_NewExperiment = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewExperiment";
public static final String ModelingActionContext_Actions_NewFunction = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewFunction";
public static final String ModelingActionContext_Actions_NewFunctionLibrary = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewFunctionLibrary";
+ public static final String ModelingActionContext_Actions_NewGameExperiment = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewGameExperiment";
public static final String ModelingActionContext_Actions_NewHistoryData = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewHistoryData";
public static final String ModelingActionContext_Actions_NewLineChart = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewLineChart";
public static final String ModelingActionContext_Actions_NewModuleType = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewModuleType";
public static final String ModelingActionContext_Actions_NewPieChart = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewPieChart";
+ public static final String ModelingActionContext_Actions_NewSensitivityAnalysisExperiment = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSensitivityAnalysisExperiment";
+ public static final String ModelingActionContext_Actions_NewSensitivityChart = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSensitivityChart";
public static final String ModelingActionContext_Actions_NewSharedFunctionLibrary = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSharedFunctionLibrary";
public static final String ModelingActionContext_Actions_NewSheet = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSheet";
public static final String ModelingActionContext_Actions_NewSimulationPlaybackExperiment = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/NewSimulationPlaybackExperiment";
+ public static final String ModelingActionContext_Actions_OpenDiagramEditorFromModel = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/OpenDiagramEditorFromModel";
+ public static final String ModelingActionContext_Actions_ShowInCharts = "http://www.simantics.org/Sysdyn-1.1/ModelingActionContext/Actions/ShowInCharts";
public static final String ModelingBrowseContext = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext";
public static final String ModelingBrowseContext_ActiveLabelDecorationRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ActiveLabelDecorationRule";
public static final String ModelingBrowseContext_BuiltinFunctions = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/BuiltinFunctions";
public static final String ModelingBrowseContext_ChartsFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ChartsFolder";
public static final String ModelingBrowseContext_ExperimentsFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ExperimentsFolder";
public static final String ModelingBrowseContext_FunctionsFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/FunctionsFolder";
+ public static final String ModelingBrowseContext_InitialConditionFolder = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/InitialConditionFolder";
public static final String ModelingBrowseContext_ModuleContentChildRule = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleContentChildRule";
public static final String ModelingBrowseContext_ModuleSymbol = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleSymbol";
public static final String ModelingBrowseContext_ModuleSymbolNodeType = "http://www.simantics.org/Sysdyn-1.1/ModelingBrowseContext/ModuleSymbolNodeType";
ModelBrowser = getResourceOrNull(graph, URIs.ModelBrowser);
ModelingActionContext = getResourceOrNull(graph, URIs.ModelingActionContext);
ModelingActionContext_Actions = getResourceOrNull(graph, URIs.ModelingActionContext_Actions);
+ ModelingActionContext_Actions_AssignIC = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_AssignIC);
+ ModelingActionContext_Actions_AssignSymbolGroups = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_AssignSymbolGroups);
ModelingActionContext_Actions_ChartDropAction = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ChartDropAction);
+ ModelingActionContext_Actions_ExportFunctionLibrary = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ExportFunctionLibrary);
+ ModelingActionContext_Actions_ExportModel = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ExportModel);
+ ModelingActionContext_Actions_ExportModule = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ExportModule);
ModelingActionContext_Actions_FunctionDropAction = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_FunctionDropAction);
+ ModelingActionContext_Actions_ImportFunctionLibrary = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ImportFunctionLibrary);
+ ModelingActionContext_Actions_ImportModule = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ImportModule);
ModelingActionContext_Actions_NewBarChart = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewBarChart);
ModelingActionContext_Actions_NewEnumeration = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewEnumeration);
ModelingActionContext_Actions_NewExperiment = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewExperiment);
ModelingActionContext_Actions_NewFunction = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewFunction);
ModelingActionContext_Actions_NewFunctionLibrary = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewFunctionLibrary);
+ ModelingActionContext_Actions_NewGameExperiment = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewGameExperiment);
ModelingActionContext_Actions_NewHistoryData = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewHistoryData);
ModelingActionContext_Actions_NewLineChart = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewLineChart);
ModelingActionContext_Actions_NewModuleType = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewModuleType);
ModelingActionContext_Actions_NewPieChart = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewPieChart);
+ ModelingActionContext_Actions_NewSensitivityAnalysisExperiment = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSensitivityAnalysisExperiment);
+ ModelingActionContext_Actions_NewSensitivityChart = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSensitivityChart);
ModelingActionContext_Actions_NewSharedFunctionLibrary = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSharedFunctionLibrary);
ModelingActionContext_Actions_NewSheet = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSheet);
ModelingActionContext_Actions_NewSimulationPlaybackExperiment = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_NewSimulationPlaybackExperiment);
+ ModelingActionContext_Actions_OpenDiagramEditorFromModel = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_OpenDiagramEditorFromModel);
+ ModelingActionContext_Actions_ShowInCharts = getResourceOrNull(graph, URIs.ModelingActionContext_Actions_ShowInCharts);
ModelingBrowseContext = getResourceOrNull(graph, URIs.ModelingBrowseContext);
ModelingBrowseContext_ActiveLabelDecorationRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ActiveLabelDecorationRule);
ModelingBrowseContext_BuiltinFunctions = getResourceOrNull(graph, URIs.ModelingBrowseContext_BuiltinFunctions);
ModelingBrowseContext_ChartsFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_ChartsFolder);
ModelingBrowseContext_ExperimentsFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_ExperimentsFolder);
ModelingBrowseContext_FunctionsFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_FunctionsFolder);
+ ModelingBrowseContext_InitialConditionFolder = getResourceOrNull(graph, URIs.ModelingBrowseContext_InitialConditionFolder);
ModelingBrowseContext_ModuleContentChildRule = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleContentChildRule);
ModelingBrowseContext_ModuleSymbol = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleSymbol);
ModelingBrowseContext_ModuleSymbolNodeType = getResourceOrNull(graph, URIs.ModelingBrowseContext_ModuleSymbolNodeType);
org.simantics.workbench,
org.simantics.annotation.ui;bundle-version="1.0.0",
org.simantics.annotation.ontology;bundle-version="1.0.0",
- org.simantics.spreadsheet.common;bundle-version="1.1.0"
+ org.simantics.spreadsheet.common;bundle-version="1.1.0",
+ org.slf4j.api;bundle-version="1.7.25"
Bundle-Activator: org.simantics.sysdyn.ui.Activator
Bundle-ActivationPolicy: lazy
Export-Package: org.simantics.sysdyn.ui.browser.nodes
class="org.simantics.sysdyn.ui.browser.actions.newActions.NewExperimentAction" />
<resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewSimulationPlaybackExperiment"
class="org.simantics.sysdyn.ui.browser.actions.newActions.NewSimulationPlaybackExperimentAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewGameExperiment"
+ class="org.simantics.sysdyn.ui.browser.actions.newActions.NewGameExperimentAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewSensitivityAnalysisExperiment"
+ class="org.simantics.sysdyn.ui.browser.actions.newActions.NewSensitivityAnalysisExperimentAction" />
<resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewLineChart"
class="org.simantics.sysdyn.ui.browser.actions.newActions.NewLineChartAction" />
<resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewBarChart"
<resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewSheet"
class="org.simantics.sysdyn.ui.browser.actions.newActions.NewSheetAction" />
<resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewHistoryData"
- class="org.simantics.sysdyn.ui.browser.actions.newActions.NewHistoryDataAction" />
+ class="org.simantics.sysdyn.ui.browser.actions.newActions.NewHistoryDataAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/NewSensitivityChart"
+ class="org.simantics.sysdyn.ui.browser.actions.newActions.NewSensitivityChartAction" />
</target>
-
+
+ <target interface="org.simantics.db.layer0.adapter.ActionFactory">
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/ImportModule"
+ class="org.simantics.sysdyn.ui.browser.actions.importActions.ImportModuleAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/ImportFunctionLibrary"
+ class="org.simantics.sysdyn.ui.browser.actions.importActions.ImportFunctionLibraryAction" />
+ </target>
+ <target interface="org.simantics.db.layer0.adapter.ActionFactory">
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/ExportModule"
+ class="org.simantics.sysdyn.ui.browser.actions.exportActions.ExportModuleAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/ExportFunctionLibrary"
+ class="org.simantics.sysdyn.ui.browser.actions.exportActions.ExportFunctionLibraryAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/ExportModel"
+ class="org.simantics.sysdyn.ui.browser.actions.exportActions.ExportModelAction" />
+ </target>
+ <target interface="org.simantics.db.layer0.adapter.ActionFactory">
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/AssignIC"
+ class="org.simantics.sysdyn.ui.browser.actions.AssignICAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/ShowInCharts"
+ class="org.simantics.sysdyn.ui.browser.actions.ShowInChartsAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/AssignSymbolGroups"
+ class="org.simantics.sysdyn.ui.browser.actions.AssignSymbolGroupsAction" />
+ <resource uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/OpenDiagramEditorFromModel"
+ class="org.simantics.sysdyn.ui.browser.actions.OpenDiagramEditorFromModelAction" />
+ </target>
<target interface="org.simantics.db.layer0.adapter.DropActionFactory">
<resource
uri="http://www.simantics.org/Sysdyn-0.0/ModelingActionContext/Actions/FunctionDropAction"
</target>
<target interface="org.simantics.db.layer0.adapter.Remover">
- <type uri="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext/ModuleSymbol"
- class="org.simantics.sysdyn.ui.browser.actions.remove.ModuleTypeRemover">
- <graph />
+ <type uri="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"
+ class="org.simantics.sysdyn.ui.browser.actions.remove.ModuleSymbolRemover">
<this />
</type>
<type uri="http://www.simantics.org/Sysdyn-0.0/Variable"
-<?xml version="1.0" encoding="UTF-8"?>\r
-<?eclipse version="3.4"?>\r
-<!--\r
- Copyright (c) 2010 Association for Decentralized Information Management in\r
- Industry THTH ry.\r
- All rights reserved. This program and the accompanying materials\r
- are made available under the terms of the Eclipse Public License v1.0\r
- which accompanies this distribution, and is available at\r
- http://www.eclipse.org/legal/epl-v10.html\r
- \r
- Contributors:\r
- VTT Technical Research Centre of Finland - initial API and implementation\r
- -->\r
-\r
-<plugin>\r
- <extension\r
- point="org.eclipse.ui.editors">\r
- <editor\r
- class="org.simantics.modeling.ui.diagramEditor.DiagramEditor:viewer=org.simantics.sysdyn.ui.editor.DiagramViewer"\r
- contributorClass="org.simantics.ui.toolbar.ToolbarContributor:toolbar=org.simantics.sysdyn.ui.diagramToolbar"\r
- default="false"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/plugin.png"\r
- id="org.simantics.sysdyn.ui.diagramViewer"\r
- matchingStrategy="org.simantics.ui.workbench.editor.input.ResourceEditorInputMatchingStrategy"\r
- name="System Dynamic Diagram Viewer">\r
- </editor>\r
- <editor\r
- class="org.simantics.sysdyn.ui.modelica.SysdynModelicaEditor"\r
- contributorClass="org.simantics.sysdyn.ui.modelica.TextEditorActionBarContributor"\r
- default="false"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/page_white_text.png"\r
- id="org.simantics.sysdyn.ui.modelicaEditor"\r
- name="Modelica Code Viewer">\r
- </editor>\r
- <editor\r
- class="org.simantics.sysdyn.ui.trend.TrendEditor"\r
- default="false"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"\r
- id="org.simantics.sysdyn.ui.jfreeChartEditor"\r
- name="Chart Viewer">\r
- </editor>\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.views">\r
- <category\r
- id="org.simantics.sysdyn.ui.category"\r
- name="System Dynamics">\r
- </category>\r
- <view\r
- allowMultiple="true"\r
- category="org.simantics.sysdyn.ui.category"\r
- class="org.simantics.sysdyn.ui.trend.TrendView"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"\r
- id="org.simantics.sysdyn.ui.trend.view"\r
- name="Trend"\r
- restorable="true">\r
- </view>\r
- <!--<view\r
- category="org.simantics.sysdyn.ui.category"\r
- class="org.simantics.sysdyn.ui.browser.SysdynBrowser"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.ui.browser"\r
- name="Model Browser"\r
- restorable="true">\r
- </view>-->\r
- <view\r
- allowMultiple="false"\r
- category="org.simantics.sysdyn.ui.category"\r
- class="org.simantics.sysdyn.ui.structure.StructureView"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/arrow_switch.png"\r
- id="org.simantics.sysdyn.ui.structure.view"\r
- name="Structure"\r
- restorable="true">\r
- </view>\r
- <view\r
- allowMultiple="false"\r
- category="org.simantics.sysdyn.ui.category"\r
- class="org.simantics.sysdyn.ui.values.ValueView"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/page_white_database.png"\r
- id="org.simantics.sysdyn.ui.values.view"\r
- name="Values"\r
- restorable="true">\r
- </view>\r
- <!--<view\r
- category="org.simantics.sysdyn.ui.category"\r
- class="org.simantics.sysdyn.ui.browser.SysdynModelBrowser"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.ui.modelBrowser"\r
- name="Model Browser"\r
- restorable="true">\r
- <description>\r
- Structural model browser view for Sysdyn.\r
- </description>\r
- </view>-->\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.perspectives">\r
- <perspective\r
- class="org.simantics.sysdyn.ui.project.SysdynPerspectiveFactory"\r
- icon="icons/sysdyn.png"\r
- id="org.simantics.sysdyn.ui.perspective"\r
- name="System Dynamics">\r
- </perspective>\r
- <perspective\r
- class="org.simantics.sysdyn.ui.project.SysdynEquationPerspectiveFactory"\r
- icon="icons/function.png"\r
- id="org.simantics.sysdyn.ui.perspective.equation"\r
- name="Equation">\r
- </perspective>\r
- <perspective\r
- class="org.simantics.sysdyn.ui.project.SysdynTrendPerspectiveFactory"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_curve.png"\r
- id="org.simantics.sysdyn.ui.perspective.trend"\r
- name="Trend">\r
- </perspective>\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.perspectiveExtensions">\r
- <perspectiveExtension\r
- targetID="org.simantics.sysdyn.ui.perspective">\r
- <view\r
- id="org.simantics.browsing.ui.graph.propertyView"\r
- ratio="0.65f"\r
- relationship="bottom"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.eclipse.ui.console.ConsoleView"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.trend.view"\r
- ratio="0.4f"\r
- relationship="left"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.structure.view"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.sysdyn.ui.trend.view">\r
- </view>\r
- <view\r
- id="org.simantics.modeling.ui.browser"\r
- ratio="0.25f"\r
- relationship="left"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.simantics.diagram.symbollibrary"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.modeling.ui.browser">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.values.view"\r
- relationship="stack"\r
- relative="org.simantics.sysdyn.ui.trend.view">\r
- </view>\r
- <view\r
- id="org.simantics.issues.ui.issueview2"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.diagram.profile"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.jfreechart.chartPanel"\r
- minimized="true"\r
- ratio="0.5"\r
- relationship="right"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.simantics.workbench.search.browser"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.modeling.ui.browser">\r
- </view>\r
- <!--\r
- <view\r
- id="org.simantics.document.workbench.documentViewer"\r
- minimized="true"\r
- relationship="stack"\r
- relative="org.simantics.jfreechart.chartPanel">\r
- </view>\r
- -->\r
- </perspectiveExtension>\r
- <perspectiveExtension\r
- targetID="org.simantics.sysdyn.ui.perspective.equation">\r
- <view\r
- id="org.simantics.browsing.ui.graph.propertyView"\r
- minimized="false"\r
- ratio="0.65f"\r
- relationship="right"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.eclipse.ui.console.ConsoleView"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.trend.view"\r
- minimized="true"\r
- ratio="0.4f"\r
- relationship="left"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.structure.view"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.sysdyn.ui.trend.view">\r
- </view>\r
- <view\r
- id="org.simantics.modeling.ui.browser"\r
- minimized="true"\r
- ratio="0.25f"\r
- relationship="left"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.simantics.diagram.symbollibrary"\r
- minimized="true"\r
- relationship="stack"\r
- relative="org.simantics.modeling.ui.browser">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.values.view"\r
- relationship="stack"\r
- relative="org.simantics.sysdyn.ui.trend.view">\r
- </view>\r
- <view\r
- id="org.simantics.issues.ui.issueview2"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.diagram.profile"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.jfreechart.chartPanel"\r
- minimized="true"\r
- ratio="0.5"\r
- relationship="right"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.simantics.workbench.search.browser"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.modeling.ui.browser">\r
- </view>\r
- </perspectiveExtension>\r
- <perspectiveExtension\r
- targetID="org.simantics.sysdyn.ui.perspective.trend">\r
- <view\r
- id="org.simantics.browsing.ui.graph.propertyView"\r
- minimized="true"\r
- ratio="0.6f"\r
- relationship="bottom"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.eclipse.ui.console.ConsoleView"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.trend.view"\r
- ratio="0.4f"\r
- relationship="bottom"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.structure.view"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.sysdyn.ui.trend.view">\r
- </view>\r
- <view\r
- id="org.simantics.modeling.ui.browser"\r
- minimized="true"\r
- ratio="0.25f"\r
- relationship="left"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.simantics.diagram.symbollibrary"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.modeling.ui.browser">\r
- </view>\r
- <view\r
- id="org.simantics.sysdyn.ui.values.view"\r
- relationship="stack"\r
- relative="org.simantics.sysdyn.ui.trend.view">\r
- </view>\r
- <view\r
- id="org.simantics.issues.ui.issueview2"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.diagram.profile"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.browsing.ui.graph.propertyView">\r
- </view>\r
- <view\r
- id="org.simantics.jfreechart.chartPanel"\r
- minimized="false"\r
- ratio="0.4"\r
- relationship="right"\r
- relative="org.eclipse.ui.editorss">\r
- </view>\r
- <view\r
- id="org.simantics.workbench.search.browser"\r
- minimized="false"\r
- relationship="stack"\r
- relative="org.simantics.modeling.ui.browser">\r
- </view>\r
- </perspectiveExtension>\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.contexts">\r
- <context\r
- id="org.simantics.sysdyn.ui.basicExperiment"\r
- name="Basic Experiment">\r
- </context>\r
- <context\r
- id="org.simantics.sysdyn.ui.playbackExperiment"\r
- name="Playback Experiment">\r
- </context>\r
- <context\r
- id="org.simantics.sysdyn.ui.gameExperiment"\r
- name="Game Experiment">\r
- </context>\r
- <context\r
- id="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment"\r
- name="Sensitivity Analysis Experiment">\r
- </context>\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.menus">\r
- <!--<menuContribution\r
- locationURI="menu:sFile?after=import.ext">\r
- <command commandId="org.eclipse.ui.file.import" />\r
- <command commandId="org.eclipse.ui.file.export" />\r
- </menuContribution>-->\r
- <menuContribution\r
- locationURI="toolbar:org.eclipse.ui.main.toolbar">\r
- <toolbar\r
- id="org.simantics.sysdyn.ui.modelToolbar">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.exportModelButton"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/disk.png"\r
- id="org.simantics.sysdyn.ui.export.button"\r
- tooltip="Save model">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.exportModelAsButton"\r
- icon="icons/save_as.png"\r
- id="org.simantics.sysdyn.ui.exportAs.button"\r
- tooltip="Save model as...">\r
- </command>\r
- </toolbar>\r
- <toolbar\r
- id="org.simantics.sysdyn.ui.diagramToolbar">\r
- </toolbar>\r
- <toolbar\r
- id="org.simantics.sysdyn.ui.experimentControlToolbar">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.run"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
- id="org.simantics.sysdyn.ui.run.button"\r
- label="Simulate"\r
- style="push">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.basicExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.toggleSimulation"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"\r
- label="Simulate On Change"\r
- style="toggle"\r
- tooltip="Simulate On Change">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.basicExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.dispose"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
- id="org.simantics.sysdyn.ui.dispose.button"\r
- label="Quit Experiment"\r
- tooltip="Quit Experiment">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.basicExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.saveResults"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
- id="org.simantics.sysdyn.ui.save.button"\r
- label="Save Results">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.basicExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.saveIC"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
- id="org.simantics.sysdyn.ui.saveic.button"\r
- label="Save Initial Condition">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.gameExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.saveHistory"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
- id="org.simantics.sysdyn.ui.savehistory.button"\r
- label="Save History">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.gameExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.synthesisSimulation"\r
- hoverIcon="icons/equalizer.png"\r
- icon="icons/equalizer.png"\r
- label="Sliders and Trends"\r
- style="toggle"\r
- tooltip="Sliders and Trends">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.basicExperiment">\r
- </equals>\r
- </iterate>\r
- <and>\r
- <count\r
- value="0">\r
- </count>\r
- </and>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- </toolbar>\r
- <toolbar\r
- id="org.simantics.sysdyn.ui.playbackControlToolbar">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.playbackReset"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_start_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_start.png"\r
- id="org.simantics.sysdyn.ui.playbackReset.button"\r
- label="Reset"\r
- style="push"\r
- tooltip="Reset">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.playbackExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.playback"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
- id="org.simantics.sysdyn.ui.playback.button"\r
- label="Start Playback"\r
- style="pulldown"\r
- tooltip="Start playback">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.playbackExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <dynamic\r
- class="org.simantics.sysdyn.ui.menu.PlaybackSliderContribution"\r
- id="org.simantics.sysdyn.ui.playbackSlider">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.playbackExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </dynamic>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.playbackReload"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"\r
- label="Reload"\r
- style="push"\r
- tooltip="Reload">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.playbackExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.dispose"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
- id="org.simantics.sysdyn.ui.dispose.button"\r
- label="Quit Experiment"\r
- tooltip="Quit Experiment">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.playbackExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- </toolbar>\r
- <toolbar\r
- id="org.simantics.sysdyn.ui.gameControlToolbar">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.reloadGame"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
- id="org.simantics.sysdyn.ui.reload.game.button"\r
- label="Reload Game"\r
- style="push">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.gameExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <dynamic\r
- class="org.simantics.sysdyn.ui.menu.GameStepDurationContribution"\r
- id="org.simantics.sysdyn.ui.gameStepDuration">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.gameExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </dynamic>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.step"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_end_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_end.png"\r
- id="org.simantics.sysdyn.ui.step.button"\r
- label="Step"\r
- style="push">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.gameExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.dispose"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
- id="org.simantics.sysdyn.ui.dispose.button"\r
- label="Quit Experiment"\r
- tooltip="Quit Experiment">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.gameExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- </toolbar>\r
- <toolbar\r
- id="org.simantics.sysdyn.ui.sensitivityAnalysisControlToolbar">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.runSensitivityAnalysis"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
- id="org.simantics.sysdyn.ui.runSensitivityAnalysis.button"\r
- label="Simulate"\r
- style="push">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"\r
- label="Simulate On Change"\r
- style="toggle"\r
- tooltip="Simulate On Change">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.dispose"\r
- hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"\r
- id="org.simantics.sysdyn.ui.dispose.button"\r
- label="Quit Experiment"\r
- tooltip="Quit Experiment">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.saveSensitivityAnalysisResults"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"\r
- id="org.simantics.sysdyn.ui.saveSensitivityAnalysis.button"\r
- label="Save Sensitivity Analysis Results">\r
- <visibleWhen>\r
- <with\r
- variable="activeContexts">\r
- <iterate\r
- ifEmpty="false"\r
- operator="or">\r
- <equals\r
- value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">\r
- </equals>\r
- </iterate>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- </toolbar>\r
- </menuContribution>\r
- <menuContribution\r
- locationURI="toolbar:org.simantics.sysdyn.ui.trend.view">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.trend.view.pin"\r
- icon="icons/table_multiple_pinned.png"\r
- label="Pin Trend"\r
- style="toggle"\r
- tooltip="Pins the trend so that it does not react to selection changes">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.trend.view.png"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/images.png"\r
- label="Export to PNG"\r
- style="push"\r
- tooltip="Exports the trend to PNG file">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.trend.view.svg"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/map.png"\r
- label="Export to SVG"\r
- style="push"\r
- tooltip="Exports the trend to SVG file">\r
- </command>\r
- </menuContribution>\r
- \r
- <menuContribution\r
- locationURI="popup:#EnumerationTabPopup?after=wbStart">\r
- \r
- <command\r
- commandId="org.simantics.sysdyn.ui.renameNode"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/textfield_rename.png"\r
- id="org.simantics.sysdyn.ui.browser.rename"\r
- label="Rename"\r
- style="push">\r
- <visibleWhen checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- \r
- </menuContribution>\r
- <menuContribution\r
- locationURI="popup:#SysdynBrowserPopup?after=wbStart">\r
- <menu id="org.simantics.new"\r
- label="New">\r
- <!--\r
- <command\r
- commandId="org.simantics.modeling.ui.newModel"\r
- id="org.simantics.sysdyn.ui.browser.newModel"\r
- label="Model"\r
- style="push">\r
- </command>\r
- -->\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newSCLModule"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/script.png"\r
- id="org.simantics.sysdyn.ui.newSCLModule"\r
- label="SCL Module"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/SharedOntology"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Library"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Simulation-0.0/Model"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newAnnotationType"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/note.png"\r
- id="org.simantics.sysdyn.ui.newAnnotationType"\r
- label="Annotation Type"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Library"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Structural-0.0/ComponentType"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newAnnotationValue"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/note.png"\r
- id="org.simantics.sysdyn.ui.newAnnotationValue"\r
- label="Annotation Value"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Entity"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newLibrary"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/folder.png"\r
- id="org.simantics.sysdyn.ui.newLibrary"\r
- label="Library"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Library"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newModuleNode"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"\r
- id="org.simantics.sysdyn.ui.browser.newModule"\r
- label="Module type"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModulesNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newExperiment"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/time.png"\r
- id="org.simantics.sysdyn.ui.browser.newExperiment"\r
- label="Experiment"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newPlaybackExperiment"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/timeline_marker.png"\r
- id="org.simantics.sysdyn.ui.browser.newPlaybackExperiment"\r
- label="Playback Experiment"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newGameExperiment"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/time_go.png"\r
- id="org.simantics.sysdyn.ui.browser.newGameExperiment"\r
- label="Game Experiment"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"\r
- icon="icons/time_rainbow.png"\r
- id="org.simantics.sysdyn.ui.browser.newSensitivityAnalysisExperiment"\r
- label="Sensitivity Analysis Experiment"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newEnumeration"\r
- id="org.simantics.sysdyn.ui.browser.newEnumeration"\r
- label="Enumeration"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newFunction"\r
- id="org.simantics.sysdyn.ui.browser.newFunction"\r
- label="Function"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newFunctionLibrary"\r
- label="Function Library"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newSharedFunctionLibrary"\r
- label="Shared Function Library"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newSpreadSheet"\r
- label="Sheet"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.BookNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newXYLineChart"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"\r
- id="org.simantics.sysdyn.ui.browser.newXYLineChart"\r
- label="Line Chart"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newSensitivityChart"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/rainbow.png"\r
- id="org.simantics.sysdyn.ui.browser.newSensitivityChart"\r
- label="Sensitivity Chart"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newBarChart"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_bar.png"\r
- id="org.simantics.sysdyn.ui.browser.newBarChart"\r
- label="Bar Chart"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newPieChart"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_pie.png"\r
- id="org.simantics.sysdyn.ui.browser.newPieChart"\r
- label="Pie Chart"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newHistoryData"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/table.png"\r
- id="org.simantics.sysdyn.ui.browser.newHistoryData"\r
- label="History Data"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newModel"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.ui.browser.newModel"\r
- label="Model"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <!--\r
- <command\r
- commandId="org.simantics.documentation.workbench.newDocumentation"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/script.png"\r
- id="org.simantics.sysdyn.ui.browser.newDocumentation"\r
- label="Document"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.document.workbench.browser_old.DocumentationFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- -->\r
- </menu>\r
- <dynamic\r
- class="org.simantics.ui.contribution.OpenWithMenuContribution"\r
- id="org.simantics.sysdyn.ui.browser.openWithMenu">\r
- </dynamic>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.activateResult"\r
- id="org.simantics.sysdyn.ui.browser.activateResult"\r
- label="Show in charts"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.activateResultSet"\r
- id="org.simantics.sysdyn.ui.browser.activateResultSet"\r
- label="Show in charts"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.renameNode"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/textfield_rename.png"\r
- id="org.simantics.sysdyn.ui.browser.rename"\r
- label="Rename"\r
- style="push">\r
- <visibleWhen checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.removeNode"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/cross.png"\r
- id="org.simantics.sysdyn.ui.browser.remove"\r
- label="Remove"\r
- style="push">\r
- <visibleWhen checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <menu\r
- id="org.simantics.import"\r
- label="Import">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importModel"\r
- label="Model"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importSharedLibrary"\r
- label="Shared Library"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <!--\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importMdl"\r
- label="Vensim model"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- -->\r
- <command\r
- commandId="org.simantics.image.ui.importImage"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/image_add.png"\r
- label="Image"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.image.ui.modelBrowser.ImagesNode"\r
- property="org.simantics.modeling.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importFunctionLibrary"\r
- label="Function library"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importModule"\r
- label="Module"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importMdl"\r
- label="Vensim Model (.mdl)"\r
- style="push">\r
- </command>\r
- </menu>\r
- <menu\r
- id="org.simantics.export"\r
- label="Export">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.exportSharedOntology"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/folder.png"\r
- id="org.simantics.sysdyn.ui.exportSharedOntology"\r
- label="Shared Library"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.exportModel"\r
- label="Model"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.exportFunctionLibrary"\r
- label="Function library"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.exportModule"\r
- label="Module"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- </visibleWhen>\r
- </command>\r
- </menu>\r
- <command\r
- commandId="org.eclipse.ui.edit.findReplace"\r
- label="Find"\r
- style="push">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.activateExperiment"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
- id="org.simantics.sysdyn.ui.browser.activateExperiment"\r
- label="Activate Experiment"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.assignIC"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"\r
- id="org.simantics.sysdyn.ui.browser.assignIC"\r
- label="Assign IC"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- </menuContribution>\r
- <menuContribution\r
- locationURI="popup:#SysdynDiagramPopup?after=wbStart">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.showModule"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/palette.png"\r
- label="Show Module"\r
- style="push">\r
- <visibleWhen>\r
- <with\r
- variable="selection">\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
- property="org.simantics.graph.resourceType">\r
- </test>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <dynamic\r
- class="org.simantics.sysdyn.ui.menu.FontContextMenuContribution"\r
- id="org.simantics.sysdyn.ui.fontContextMenu">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Diagram-0.0/FontProvider"\r
- property="org.simantics.graph.resourceTypes"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </dynamic>\r
- <command\r
- commandId="org.eclipse.ui.edit.copy"\r
- label="Copy"\r
- style="push">\r
- <visibleWhen\r
- checkEnabled="true">\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.eclipse.ui.edit.paste"\r
- label="Paste"\r
- style="push">\r
- </command>\r
- <command\r
- commandId="org.eclipse.ui.edit.findReplace"\r
- label="Find"\r
- style="push">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.pasteSpecial"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/paste_plain.png"\r
- label="Paste special"\r
- style="push">\r
- </command> \r
- <command\r
- commandId="org.eclipse.ui.edit.cut"\r
- label="Cut"\r
- style="push">\r
- <visibleWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/SCLModule"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- <command\r
- commandId="org.eclipse.ui.edit.rename"\r
- label="Rename"\r
- style="push">\r
- <visibleWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/SCLModule"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </visibleWhen>\r
- </command>\r
- </menuContribution>\r
- <menuContribution\r
- locationURI="popup:#ExternalFunctionFileBrowser?after=wbStart">\r
- </menuContribution>\r
- <menuContribution\r
- allPopups="false"\r
- locationURI="menu:sFile?after=#FileNewMenu">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importModel"\r
- label="Import Model"\r
- style="push">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.importSharedLibrary"\r
- label="Import Shared Library"\r
- style="push">\r
- </command>\r
- </menuContribution>\r
- <menuContribution\r
- allPopups="false"\r
- locationURI="menu:#FileNewMenu">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.newModel"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation_add.png"\r
- label="SD Model"\r
- style="push">\r
- </command>\r
- </menuContribution>\r
- <menuContribution\r
- allPopups="false"\r
- locationURI="menu:org.simantics.sysdyn.ui.playback.button">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.playbackSlow"\r
- icon="icons/control_step.png"\r
- label="Slow"\r
- style="push">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.playbackNormal"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"\r
- label="Normal"\r
- style="push">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.playbackFast"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/control_fastforward.png"\r
- label="Fast"\r
- style="push">\r
- </command>\r
- </menuContribution>\r
- <menuContribution\r
- locationURI="toolbar:org.simantics.sysdyn.ui.chartPanel">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.chartPanelOrientation"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/page_white_text_width.png"\r
- label="Change Orientation"\r
- style="push"\r
- tooltip="Change orientation">\r
- </command>\r
- </menuContribution>\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.commands">\r
- <command\r
- id="org.simantics.sysdyn.ui.newSCLModule"\r
- name="New SCL Module">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newAnnotationType"\r
- name="New Annotation Type">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newAnnotationValue"\r
- name="New Annotation Value">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newLibrary"\r
- name="New Library">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.exportSharedOntology"\r
- name="Export Shared Library">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.trend.view.pin"\r
- name="Pin Trend">\r
- <state\r
- class="org.eclipse.jface.commands.ToggleState"\r
- id="org.simantics.sysdyn.ui.trend.view.pin.state">\r
- </state>\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.trend.view.png"\r
- name="Export To PNG">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.trend.view.svg"\r
- name="Export To SVG">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.showModule"\r
- name="Show Module">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.pasteSpecial"\r
- name="Paste Special">\r
- </command> \r
- <command\r
- id="org.simantics.sysdyn.ui.removeNode"\r
- name="Remove Node">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.renameNode"\r
- name="Rename Node">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.enumerationIndexRenameNode"\r
- name="Rename Node">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleSimulation"\r
- id="org.simantics.sysdyn.ui.toggleSimulation"\r
- name="Toggle Simulate">\r
- <state\r
- class="org.eclipse.jface.commands.ToggleState"\r
- id="org.simantics.sysdyn.ui.toggleSimulation.state">\r
- </state>\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.SynthesisSimulation"\r
- id="org.simantics.sysdyn.ui.synthesisSimulation"\r
- name="Slider and Trends">\r
- <state\r
- class="org.eclipse.jface.commands.ToggleState"\r
- id="org.simantics.sysdyn.ui.synthesisSimulation.state">\r
- </state>\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewModuleNodeHandler"\r
- id="org.simantics.sysdyn.ui.newModuleNode"\r
- name="New Module">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.activateExperiment"\r
- name="Activate Experiment">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.assignIC"\r
- name="Assign IC">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.RunBasicExperiment"\r
- id="org.simantics.sysdyn.ui.run"\r
- name="Run Basic Simulation">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.DisposeExperiment"\r
- id="org.simantics.sysdyn.ui.dispose"\r
- name="Quit Experiment">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.SaveResultsHandler"\r
- id="org.simantics.sysdyn.ui.saveResults"\r
- name="Save Results">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.SaveICHandler"\r
- id="org.simantics.sysdyn.ui.saveIC"\r
- name="Save Initial Condition">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.SaveHistoryHandler"\r
- id="org.simantics.sysdyn.ui.saveHistory"\r
- name="Save History">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleResultActivation"\r
- id="org.simantics.sysdyn.ui.activateResult"\r
- name="Show In Charts">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleResultSetActivation"\r
- id="org.simantics.sysdyn.ui.activateResultSet"\r
- name="Show In Charts">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewExperimentNodeHandler"\r
- id="org.simantics.sysdyn.ui.newExperiment"\r
- name="New Experiment">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.exportModel"\r
- name="Export Model">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.importModel"\r
- name="Import Model">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.importSharedLibrary"\r
- name="Import Shared Library">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newEnumeration"\r
- name="New Enumeration">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.importMdl"\r
- name="Import .mdl">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewFunctionHandler"\r
- id="org.simantics.sysdyn.ui.newFunction"\r
- name="NewFunction">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.importExternalFunctionFile"\r
- name="ImportExternalFunctionFile">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.exportExternalFunctionFile"\r
- name="ExportExternalFunctionFile">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newFunctionLibrary"\r
- name="New Function Library">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newSharedFunctionLibrary"\r
- name="New Shared Function Library">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.importFunctionLibrary"\r
- name="Import Function Library">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.exportFunctionLibrary"\r
- name="Export Function Library">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.importModule"\r
- name="Import Module">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.exportModule"\r
- name="Export Module">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newSpreadSheet"\r
- name="New SpreadSheet">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newModel"\r
- name="New System Dynamics Model">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newPlaybackExperiment"\r
- name="New Playback Experiment">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newGameExperiment"\r
- name="New Game Experiment">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"\r
- name="New Sensitivity Analysis Experiment">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackExperimentHandler"\r
- id="org.simantics.sysdyn.ui.playback"\r
- name="Playback experiment">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.SlowSpeedHandler"\r
- id="org.simantics.sysdyn.ui.playbackSlow"\r
- name="Slow Playback">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.NormalSpeedHandler"\r
- id="org.simantics.sysdyn.ui.playbackNormal"\r
- name="Normal Playback">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.FastSpeedHandler"\r
- id="org.simantics.sysdyn.ui.playbackFast"\r
- name="Fast Playback">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackResetHandler"\r
- id="org.simantics.sysdyn.ui.playbackReset"\r
- name="Reset Playback">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackReloadHandler"\r
- id="org.simantics.sysdyn.ui.playbackReload"\r
- name="Reload Playback">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.ChartPanelOrientationHandler"\r
- id="org.simantics.sysdyn.ui.chartPanelOrientation"\r
- name="Chart Panel Orientation">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewXYLineChartHandler"\r
- id="org.simantics.sysdyn.ui.newXYLineChart"\r
- name="New XY Line Chart">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewBarChartHandler"\r
- id="org.simantics.sysdyn.ui.newBarChart"\r
- name="New Bar Chart">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewPieChartHandler"\r
- id="org.simantics.sysdyn.ui.newPieChart"\r
- name="New Pie Chart">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityChartHandler"\r
- id="org.simantics.sysdyn.ui.newSensitivityChart"\r
- name="New XY Line Chart">\r
- </command> \r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewHistoryDataHandler"\r
- id="org.simantics.sysdyn.ui.newHistoryData"\r
- name="New History Data">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.game.StepHandler"\r
- id="org.simantics.sysdyn.ui.step"\r
- name="Step">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.game.ReloadGameExperimentHandler"\r
- id="org.simantics.sysdyn.ui.reloadGame"\r
- name="Reload Game">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"\r
- name="New Game Experiment">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.RunSensitivityAnalysisExperiment"\r
- id="org.simantics.sysdyn.ui.runSensitivityAnalysis"\r
- name="Run Basic Simulation">\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.ToggleSimulation"\r
- id="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation"\r
- name="Toggle Simulate">\r
- <state\r
- class="org.eclipse.jface.commands.ToggleState"\r
- id="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation.state">\r
- </state>\r
- </command>\r
- <command\r
- defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.SaveResultsHandler"\r
- id="org.simantics.sysdyn.ui.saveSensitivityAnalysisResults"\r
- name="Save Results">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.exportModelButton"\r
- name="Export Model">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.exportModelAsButton"\r
- name="Export Model As...">\r
- </command>\r
- <command\r
- id="org.simantics.sysdyn.ui.diagramTool"\r
- name="Diagram Tool">\r
- <state\r
- id="org.eclipse.ui.commands.radioState">\r
- <class\r
- class="org.eclipse.ui.handlers.RadioState">\r
- <parameter\r
- name="default"\r
- value="pointer">\r
- </parameter>\r
- <parameter\r
- name="persisted"\r
- value="true">\r
- </parameter>\r
- </class>\r
- </state>\r
- </command>\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.handlers">\r
- \r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.EnumerationIndexRenameNodeHandler"\r
- commandId="org.simantics.sysdyn.ui.enumerationIndexRenameNode">\r
- </handler>\r
- \r
- \r
- <handler\r
- class="org.simantics.sysdyn.ui.trend.PinTrend"\r
- commandId="org.simantics.sysdyn.ui.trend.view.pin">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.trend.TrendToPng"\r
- commandId="org.simantics.sysdyn.ui.trend.view.png">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.trend.TrendToSvg"\r
- commandId="org.simantics.sysdyn.ui.trend.view.svg">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.NewSCLModuleHandler"\r
- commandId="org.simantics.sysdyn.ui.newSCLModule">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/SharedOntology"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Library"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Simulation-0.0/Model"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.NewAnnotationTypeHandler"\r
- commandId="org.simantics.sysdyn.ui.newAnnotationType">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Library"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="http://www.simantics.org/Structural-0.0/ComponentType"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.NewAnnotationValueHandler"\r
- commandId="org.simantics.sysdyn.ui.newAnnotationValue">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Entity"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.NewLibraryHandler"\r
- commandId="org.simantics.sysdyn.ui.newLibrary">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="http://www.simantics.org/Layer0-0.0/Library"\r
- property="org.simantics.graph.resourceType"\r
- value="true">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.ShowModuleHandler"\r
- commandId="org.simantics.sysdyn.ui.showModule">\r
- <enabledWhen>\r
- <and>\r
- <with\r
- variable="selection">\r
- <and>\r
- <test\r
- args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"\r
- property="org.simantics.graph.resourceType">\r
- </test>\r
- </and>\r
- </with>\r
- </and>\r
- </enabledWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.PasteSpecialHandler"\r
- commandId="org.simantics.sysdyn.ui.pasteSpecial">\r
- </handler> \r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.UnlinkNodeHandler2"\r
- commandId="org.simantics.sysdyn.ui.removeNode">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.image.ui.modelBrowser.ImageNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.operating.ui.modelBrowser.CompositeNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SheetNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.AbstractChartNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SCLModule"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <!--\r
- <test\r
- args="org.simantics.document.workbench.browser_old.DocumentationNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- -->\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.RenameNodeHandler"\r
- commandId="org.simantics.sysdyn.ui.renameNode">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SheetNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.BarChartNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModuleNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SCLModule"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <!--\r
- <test\r
- args="org.simantics.document.workbench.browser_old.DocumentationNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- -->\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.imports.ImportModelHandler"\r
- commandId="org.simantics.sysdyn.ui.importModel">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.imports.ImportSharedLibraryHandler"\r
- commandId="org.simantics.sysdyn.ui.importSharedLibrary">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.exports.ExportModelHandler"\r
- commandId="org.simantics.sysdyn.ui.exportModel">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.imports.ImportMdlHandler"\r
- commandId="org.simantics.sysdyn.ui.importMdl">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewEnumerationNodeHandler"\r
- commandId="org.simantics.sysdyn.ui.newEnumeration">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.imports.ImportExternalFunctionFilesHandler"\r
- commandId="org.simantics.sysdyn.ui.importExternalFunctionFile">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.exports.ExportExternalFunctionFilesHandler"\r
- commandId="org.simantics.sysdyn.ui.exportExternalFunctionFile">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewFunctionLibraryHandler"\r
- commandId="org.simantics.sysdyn.ui.newFunctionLibrary">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewSharedFunctionLibraryHandler"\r
- commandId="org.simantics.sysdyn.ui.newSharedFunctionLibrary">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.exports.ExportFunctionLibrary"\r
- commandId="org.simantics.sysdyn.ui.exportFunctionLibrary">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.imports.ImportFunctionLibrary"\r
- commandId="org.simantics.sysdyn.ui.importFunctionLibrary">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.imports.ImportModuleHandler"\r
- commandId="org.simantics.sysdyn.ui.importModule">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModulesNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.exports.ExportModuleHandler"\r
- commandId="org.simantics.sysdyn.ui.exportModule">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.modeling.ui.modelBrowser.handlers.StandardCopyHandler"\r
- commandId="org.eclipse.ui.edit.copy">\r
- <enabledWhen>\r
- <not>\r
- <count\r
- value="0">\r
- </count>\r
- </not>\r
- </enabledWhen>\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.modeling.ui.modelBrowser.handlers.StandardPasteHandler"\r
- commandId="org.eclipse.ui.edit.paste">\r
- <enabledWhen>\r
- <not>\r
- <count\r
- value="0">\r
- </count>\r
- </not>\r
- </enabledWhen>\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModuleNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewSpreadSheetHandler"\r
- commandId="org.simantics.sysdyn.ui.newSpreadSheet">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewModelHandler"\r
- commandId="org.simantics.sysdyn.ui.newModel">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewPlaybackExperimentNodeHandler"\r
- commandId="org.simantics.sysdyn.ui.newPlaybackExperiment">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewGameExperimentNodeHandler"\r
- commandId="org.simantics.sysdyn.ui.newGameExperiment">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityAnalysisExperimentNodeHandler"\r
- commandId="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.FindReplaceHandler"\r
- commandId="org.eclipse.ui.edit.findReplace">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.exports.ExportModelAsButtonHandler"\r
- commandId="org.simantics.sysdyn.ui.exportModelAsButton">\r
- <activeWhen>\r
- <or>\r
- <with\r
- variable="activePartId">\r
- <equals value="org.simantics.browsing.ui.graph.propertyView"/>\r
- </with>\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"\r
- property="org.simantics.sysdyn.ui.nodeClass2">\r
- </test>\r
- </with>\r
- </or>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.exports.ExportModelButtonHandler"\r
- commandId="org.simantics.sysdyn.ui.exportModelButton">\r
- <activeWhen>\r
- <or>\r
- <with\r
- variable="activePartId">\r
- <equals\r
- value="org.simantics.browsing.ui.graph.propertyView">\r
- </equals>\r
- </with>\r
- <with\r
- variable="selection">\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"\r
- property="org.simantics.sysdyn.ui.nodeClass2">\r
- </test>\r
- </with>\r
- </or>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.DiagramToolHandler"\r
- commandId="org.simantics.sysdyn.ui.diagramTool">\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator"\r
- commandId="org.simantics.sysdyn.ui.activateExperiment">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.AssignIC"\r
- commandId="org.simantics.sysdyn.ui.assignIC">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.handlers.ExportSharedOntologyHandler"\r
- commandId="org.simantics.sysdyn.ui.exportSharedOntology">\r
- <activeWhen>\r
- <with\r
- variable="selection">\r
- <or>\r
- <test\r
- args="org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode"\r
- property="org.simantics.sysdyn.ui.nodeClass">\r
- </test>\r
- </or>\r
- </with>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.PropertyViewUndoHandler"\r
- commandId="org.eclipse.ui.edit.undo">\r
- <activeWhen>\r
- <reference\r
- definitionId="org.simantics.sysdyn.ui.inExpressionField">\r
- </reference>\r
- </activeWhen>\r
- </handler>\r
- <handler\r
- class="org.simantics.sysdyn.ui.PropertyViewUndoHandler"\r
- commandId="org.eclipse.ui.edit.redo">\r
- <activeWhen>\r
- <reference\r
- definitionId="org.simantics.sysdyn.ui.inExpressionField">\r
- </reference>\r
- </activeWhen>\r
- </handler>\r
- \r
- </extension>\r
- \r
- <extension\r
- point="org.eclipse.ui.importWizards">\r
- \r
- <category\r
- id="org.simantics.sysdyn.import"\r
- name="Sysdyn">\r
- </category>\r
-<!-- <wizard\r
- category="org.simantics.sysdyn.import"\r
- class="org.simantics.sysdyn.ui.wizards.models.ImportWizardModel"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.ui.wizards.modelImport"\r
- name="Import Sysdyn Model">\r
- </wizard> -->\r
- <wizard\r
- category="org.simantics.sysdyn.import"\r
- class="org.simantics.sysdyn.ui.wizards.model.SysdynModelImportWizard"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.import.model2"\r
- name="Import Sysdyn Model">\r
- </wizard>\r
-<!-- <wizard\r
- category="org.simantics.sysdyn.import"\r
- class="org.simantics.sysdyn.ui.wizards.modules.ImportWizardModule"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"\r
- id="org.simantics.sysdyn.ui.wizards.moduleImport"\r
- name="Import Sysdyn Module">\r
- </wizard>\r
- <wizard\r
- category="org.simantics.sysdyn.import"\r
- class="org.simantics.sysdyn.ui.wizards.functions.ImportWizardFunction"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/brick.png"\r
- id="org.simantics.sysdyn.ui.wizards.functionImport"\r
- name="Import Sysdyn Function Library">\r
- </wizard>\r
- <wizard\r
- category="org.simantics.sysdyn.import"\r
- class="org.simantics.sysdyn.ui.wizards.mdl.ImportWizardMdl"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.ui.wizards.mdlImport"\r
- name="Import Vensim Model (.mdl)">\r
- </wizard> -->\r
- </extension>\r
- \r
- <extension\r
- point="org.eclipse.ui.exportWizards">\r
- \r
- <category\r
- id="org.simantics.sysdyn.export"\r
- name="Sysdyn">\r
- </category>\r
-<!-- <wizard\r
- category="org.simantics.sysdyn.export"\r
- class="org.simantics.sysdyn.ui.wizards.models.ExportWizardModel"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.export.model"\r
- name="Export Sysdyn Model">\r
- </wizard> -->\r
- <wizard\r
- category="org.simantics.sysdyn.export"\r
- class="org.simantics.sysdyn.ui.wizards.model.SysdynModelExportWizard"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"\r
- id="org.simantics.sysdyn.export.model2"\r
- name="Export Sysdyn Model">\r
- </wizard>\r
-<!-- <wizard\r
- category="org.simantics.sysdyn.export"\r
- class="org.simantics.sysdyn.ui.wizards.modules.ExportWizardModule"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"\r
- id="org.simantics.sysdyn.export.module"\r
- name="Export Sysdyn Module">\r
- </wizard> \r
- <wizard\r
- category="org.simantics.sysdyn.export"\r
- class="org.simantics.sysdyn.ui.wizards.functions.ExportWizardFunction"\r
- icon="platform:/plugin/com.famfamfam.silk/icons/brick.png"\r
- id="org.simantics.sysdyn.export.function"\r
- name="Export Sysdyn Function Library">\r
- </wizard> -->\r
- </extension>\r
- \r
- <extension\r
- point="org.eclipse.core.expressions.propertyTesters">\r
- <propertyTester\r
- class="org.simantics.browsing.ui.swt.NodePropertyTester"\r
- id="org.simantics.browsing.ui.nodePropertyTester"\r
- namespace="org.simantics.sysdyn.ui"\r
- properties="nodeClass"\r
- type="org.eclipse.jface.viewers.IStructuredSelection">\r
- </propertyTester>\r
- <propertyTester\r
- class="org.simantics.sysdyn.ui.browser.nodes.ExportTester"\r
- id="org.simantics.sysdyn.ui.selectionPropertyTester"\r
- namespace="org.simantics.sysdyn.ui"\r
- properties="nodeClass2"\r
- type="org.eclipse.jface.viewers.IStructuredSelection">\r
- </propertyTester>\r
- </extension>\r
- <extension\r
- point="org.simantics.browsing.ui.common.viewpointContributionBinding">\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ModuleType"\r
- preference="1.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.Project"\r
- preference="1.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.Modules"\r
- preference="1.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.Model"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AnnotationContribution"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AnnotationContribution2"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.LibraryContribution"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.Experiment"\r
- preference="1.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResult"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSet"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.Configuration"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraries"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.LibraryFunctions"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SharedFunctionLibraries"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.Book"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.Charts"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SCLModules"\r
- preference="2">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.InitialConditions"\r
- preference="2">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableVariableIndexes">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.AvailableEnumerations"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/UsedVariableIndexes">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.UsedEnumerations"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationIndexes"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationReplacement">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.ReplaceableEnumerations"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFiles"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ModelBrowser">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SysdynProject"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.functions.SharedFunctionLibraries"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.functions.SelectedSharedFunctionLibraries"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/FunctionTree">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModels"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeLibraries"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedLibraries"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSubLibraries"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ImportModuleTree">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModels"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ExportModuleTree">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModels"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModules"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- </extension>\r
-\r
- <extension\r
- point="org.simantics.browsing.ui.common.comparableContextBinding">\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
- <implementation\r
- class="org.simantics.modeling.ui.modelBrowser2.contributions.LexicalComparableContributor"\r
- preference="1.0">\r
- </implementation>\r
- </binding>\r
- </extension>\r
- \r
- <extension\r
- point="org.simantics.browsing.ui.common.labelerBinding">\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SharedOntologyLabeler"\r
- preference="3.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ConfigurationLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.VariableLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ExperimentsLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ModelLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ModulesLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ExperimentLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ModuleLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.InputLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ModuleTypeLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.FunctionsLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SharedFunctionsLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.BookLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SheetLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ChartLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ChartsLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SCLModulesLabeler"\r
- preference="2">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.InitialConditionsLabeler"\r
- preference="2">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SCLModuleLabeler"\r
- preference="2">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.InitialConditionLabeler"\r
- preference="2">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AnnotationTypeLabeler"\r
- preference="2">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AnnotationValueLabeler"\r
- preference="2">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.LibraryLabeler"\r
- preference="2">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableVariableIndexes">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationLabeler"\r
- preference="1.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/UsedVariableIndexes">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.ConflictingEnumerationLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationIndexLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationReplacement">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.ReplaceableEnumerationsLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/FunctionTree">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeFunctionLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedLibraryLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedFolderLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ImportModuleTree">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ExportModuleTree">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModulesLabeler"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- </extension>\r
- <extension\r
- point="org.simantics.browsing.ui.common.imagerBinding">\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SharedOntologyImager"\r
- preference="3.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AnnotationTypeImager"\r
- preference="3.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AnnotationValueImager"\r
- preference="3.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.LibraryImager"\r
- preference="3.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.browsing.ui.swt.ImageDescriptorProviderAdapter"\r
- preference="1.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultImager"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetImager"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ChartImager"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ChartsImager"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileImager"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- </extension>\r
- <extension\r
- point="org.simantics.browsing.ui.common.labelDecoratorBinding">\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultDecorator"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetDecorator"\r
- preference="2.0">\r
- </implementation>\r
- <implementation\r
- class="org.simantics.sysdyn.ui.browser.contributions.ExperimentLabelDecorator"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- </extension>\r
- <extension\r
- point="org.simantics.browsing.ui.common.selectionProcessorBinding">\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Modeling-0.0/ModelingBrowseContext">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">\r
- </implementation>\r
- </binding>\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">\r
- </implementation>\r
- </binding>\r
- </extension>\r
- <extension\r
- point="org.simantics.browsing.ui.common.checkedStateBinding">\r
- <binding\r
- browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">\r
- <implementation\r
- class="org.simantics.sysdyn.ui.properties.widgets.arrays.ShowInChartsCheckBox"\r
- preference="2.0">\r
- </implementation>\r
- </binding>\r
- </extension>\r
- <extension\r
- point="org.simantics.ui.resourceEditorAdapter">\r
- <adapterClass\r
- class="org.simantics.sysdyn.ui.editor.OpenDiagramFromConfigurationAdapter"\r
- groupId="org.simantics.diagramEditor.group"\r
- priority="100">\r
- </adapterClass>\r
- <adapterClass\r
- class="org.simantics.sysdyn.ui.editor.OpenDiagramFromComponentAdapter"\r
- priority="90">\r
- </adapterClass>\r
- <adapter\r
- editorId="org.simantics.sysdyn.ui.modelicaEditor"\r
- priority="2"\r
- type_uris="http://www.simantics.org/Sysdyn-0.0/Configuration">\r
- </adapter>\r
- <adapter\r
- editorId="org.simantics.sysdyn.ui.jfreeChartEditor"\r
- priority="2"\r
- type_uris="http://www.simantics.org/JFreeChart-0.0/Chart">\r
- </adapter>\r
- </extension>\r
- <extension\r
- point="org.simantics.ui.doubleClick">\r
- <doubleClickAction\r
- class="org.simantics.sysdyn.ui.actions.ActivateExperimentAction"\r
- name="Activate Sysdyn Experiment"\r
- priority="300.0">\r
- </doubleClickAction>\r
- <doubleClickAction\r
- class="org.simantics.sysdyn.ui.browser.actions.ActivateResultDatasetAction"\r
- name="Activate Result In Charts"\r
- priority="250.0">\r
- </doubleClickAction> \r
- <doubleClickAction\r
- class="org.simantics.sysdyn.ui.browser.actions.ActivateResultSetDatasetAction"\r
- name="Activate Result In Charts"\r
- priority="240.0">\r
- </doubleClickAction> \r
- <doubleClickAction\r
- class="org.simantics.sysdyn.ui.browser.actions.OpenSheetAction"\r
- name="Open Spreadsheet"\r
- priority="220.0">\r
- </doubleClickAction>\r
- <!--<doubleClickAction\r
- class="org.simantics.sysdyn.ui.actions.ConsumeUnnecessaryEntersAction"\r
- name="Consume unnecessary enters"\r
- priority="200.0">\r
- </doubleClickAction>-->\r
- <doubleClickAction\r
- class="org.simantics.sysdyn.ui.actions.ShowInstantiatedModuleAction"\r
- name="Show Instantiated Module"\r
- priority="100.0">\r
- </doubleClickAction>\r
- </extension>\r
- <extension\r
- point="org.simantics.ui.toolbarCommand">\r
- <command\r
- commandId="org.simantics.sysdyn.ui.diagramTool"\r
- image="platform:/plugin/com.famfamfam.silk/icons/lock.png"\r
- name="Lock Sketch"\r
- toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
- type="radio"\r
- value="lock">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.diagramTool"\r
- image="icons/cursor.png"\r
- name="Pointer"\r
- toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
- type="radio"\r
- value="pointer">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.diagramTool"\r
- image="icons/dependency.png"\r
- name="Create Dependency (Alt+Mouse1)"\r
- toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
- type="radio"\r
- value="dependency">\r
- </command>\r
- <command\r
- commandId="org.simantics.sysdyn.ui.diagramTool"\r
- image="icons/flow.png"\r
- name="Create Flow (Alt+Mouse2)"\r
- toolbarId="org.simantics.sysdyn.ui.diagramToolbar"\r
- type="radio"\r
- value="flow">\r
- </command>\r
- </extension>\r
- <extension\r
- point="org.simantics.project.feature">\r
- <feature\r
- class="org.simantics.sysdyn.ui.project.SysdynProject"\r
- description="System dynamics modelling project. Create system dynamics models and simulate them with OpenModelica."\r
- id="org.simantics.sysdyn.project"\r
- label="System Dynamics Project"\r
- published="true">\r
- <requires id="org.simantics.sysdyn.dependencies"/>\r
- <requires id="org.simantics.simulation.experimentManager"/>\r
- <installGroup id="org.simantics.sysdyn.feature.group" version="[1.0.0,2.0.0)"/>\r
- </feature>\r
- <feature\r
- class="org.simantics.project.features.DependencyValidationFeature:http://www.simantics.org/Sysdyn-0.0/ImportedOntologies"\r
- id="org.simantics.sysdyn.dependencies"\r
- label="System Dynamics Ontology Dependencies">\r
- </feature>\r
- </extension>\r
- \r
- \r
- <extension point="org.simantics.scl.reflection.binding">\r
- <namespace path="http://www.simantics.org/Sysdyn-0.0/Validations">\r
- <namespace path="Dependencies">\r
- <externalClass className="org.simantics.db.Resource"/>\r
- <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
- <externalClass className="org.simantics.db.ReadGraph"/>\r
- <externalClass className="org.simantics.db.WriteGraph"/>\r
- <class className="org.simantics.sysdyn.ui.validation.DependencyFunction"/>\r
- </namespace>\r
- <namespace path="Expressions">\r
- <externalClass className="org.simantics.db.Resource"/>\r
- <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
- <externalClass className="org.simantics.db.ReadGraph"/>\r
- <externalClass className="org.simantics.db.WriteGraph"/>\r
- <class className="org.simantics.sysdyn.ui.validation.ExpressionIssueFunction"/>\r
- </namespace>\r
- <namespace path="Functions">\r
- <externalClass className="org.simantics.db.Resource"/>\r
- <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
- <externalClass className="org.simantics.db.ReadGraph"/>\r
- <externalClass className="org.simantics.db.WriteGraph"/>\r
- <class className="org.simantics.sysdyn.ui.validation.Functions"/>\r
- </namespace>\r
- <namespace path="Enumerations">\r
- <externalClass className="org.simantics.db.Resource"/>\r
- <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
- <externalClass className="org.simantics.db.ReadGraph"/>\r
- <externalClass className="org.simantics.db.WriteGraph"/>\r
- <class className="org.simantics.sysdyn.ui.validation.EnumerationFunction"/>\r
- </namespace> \r
- <namespace path="Units">\r
- <externalClass className="org.simantics.db.Resource"/>\r
- <externalClass className="org.simantics.db.layer0.variable.Variable"/>\r
- <externalClass className="org.simantics.db.ReadGraph"/>\r
- <externalClass className="org.simantics.db.WriteGraph"/>\r
- <class className="org.simantics.sysdyn.ui.validation.UnitFunction"/>\r
- </namespace> \r
- </namespace>\r
- </extension>\r
- <extension\r
- point="org.eclipse.ui.preferencePages">\r
- <page\r
- class="org.simantics.sysdyn.ui.preferences.SolverPreferencePage"\r
- id="org.simantics.sysdyn.solver.preferences"\r
- name="Solver">\r
- </page>\r
- <page\r
- class="org.simantics.sysdyn.ui.preferences.ModelicaPreferencePage"\r
- id="org.simantics.modelica.preferences"\r
- name="Modelica">\r
- </page>\r
- <page\r
- class="org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferencePage"\r
- id="org.simantics.sysdyn.diagram.preferences"\r
- name="Sysdyn Diagrams">\r
- </page> \r
- </extension>\r
- <extension\r
- point="org.eclipse.core.runtime.preferences">\r
- <initializer\r
- class="org.simantics.modelica.preferences.ModelicaPreferenceInitializer">\r
- </initializer>\r
- <initializer\r
- class="org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferencesInitializer">\r
- </initializer> \r
- </extension>\r
- \r
- <extension point="org.eclipse.core.expressions.definitions">\r
- <definition\r
- id="org.simantics.sysdyn.ui.inExpressionField">\r
- <with variable="activePartId">\r
- <equals\r
- value="org.simantics.browsing.ui.graph.propertyView">\r
- </equals>\r
- </with>\r
- </definition>\r
- </extension>\r
- \r
-</plugin>\r
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<!--
+ Copyright (c) 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
+ -->
+
+<plugin>
+ <extension
+ point="org.eclipse.ui.editors">
+ <editor
+ class="org.simantics.modeling.ui.diagramEditor.DiagramEditor:viewer=org.simantics.sysdyn.ui.editor.DiagramViewer"
+ contributorClass="org.simantics.ui.toolbar.ToolbarContributor:toolbar=org.simantics.sysdyn.ui.diagramToolbar"
+ default="false"
+ icon="platform:/plugin/com.famfamfam.silk/icons/plugin.png"
+ id="org.simantics.sysdyn.ui.diagramViewer"
+ matchingStrategy="org.simantics.ui.workbench.editor.input.ResourceEditorInputMatchingStrategy"
+ name="System Dynamic Diagram Viewer">
+ </editor>
+ <editor
+ class="org.simantics.sysdyn.ui.modelica.SysdynModelicaEditor"
+ contributorClass="org.simantics.sysdyn.ui.modelica.TextEditorActionBarContributor"
+ default="false"
+ icon="platform:/plugin/com.famfamfam.silk/icons/page_white_text.png"
+ id="org.simantics.sysdyn.ui.modelicaEditor"
+ name="Modelica Code Viewer">
+ </editor>
+ <editor
+ class="org.simantics.sysdyn.ui.trend.TrendEditor"
+ default="false"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"
+ id="org.simantics.sysdyn.ui.jfreeChartEditor"
+ name="Chart Viewer">
+ </editor>
+ </extension>
+ <extension
+ point="org.eclipse.ui.views">
+ <category
+ id="org.simantics.sysdyn.ui.category"
+ name="System Dynamics">
+ </category>
+ <view
+ allowMultiple="true"
+ category="org.simantics.sysdyn.ui.category"
+ class="org.simantics.sysdyn.ui.trend.TrendView"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"
+ id="org.simantics.sysdyn.ui.trend.view"
+ name="Trend"
+ restorable="true">
+ </view>
+ <!--<view
+ category="org.simantics.sysdyn.ui.category"
+ class="org.simantics.sysdyn.ui.browser.SysdynBrowser"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.ui.browser"
+ name="Model Browser"
+ restorable="true">
+ </view>-->
+ <view
+ allowMultiple="false"
+ category="org.simantics.sysdyn.ui.category"
+ class="org.simantics.sysdyn.ui.structure.StructureView"
+ icon="platform:/plugin/com.famfamfam.silk/icons/arrow_switch.png"
+ id="org.simantics.sysdyn.ui.structure.view"
+ name="Structure"
+ restorable="true">
+ </view>
+ <view
+ allowMultiple="false"
+ category="org.simantics.sysdyn.ui.category"
+ class="org.simantics.sysdyn.ui.values.ValueView"
+ icon="platform:/plugin/com.famfamfam.silk/icons/page_white_database.png"
+ id="org.simantics.sysdyn.ui.values.view"
+ name="Values"
+ restorable="true">
+ </view>
+ <!--<view
+ category="org.simantics.sysdyn.ui.category"
+ class="org.simantics.sysdyn.ui.browser.SysdynModelBrowser"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.ui.modelBrowser"
+ name="Model Browser"
+ restorable="true">
+ <description>
+ Structural model browser view for Sysdyn.
+ </description>
+ </view>-->
+ </extension>
+ <extension
+ point="org.eclipse.ui.perspectives">
+ <perspective
+ class="org.simantics.sysdyn.ui.project.SysdynPerspectiveFactory"
+ icon="icons/sysdyn.png"
+ id="org.simantics.sysdyn.ui.perspective"
+ name="System Dynamics">
+ </perspective>
+ <perspective
+ class="org.simantics.sysdyn.ui.project.SysdynEquationPerspectiveFactory"
+ icon="icons/function.png"
+ id="org.simantics.sysdyn.ui.perspective.equation"
+ name="Equation">
+ </perspective>
+ <perspective
+ class="org.simantics.sysdyn.ui.project.SysdynTrendPerspectiveFactory"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_curve.png"
+ id="org.simantics.sysdyn.ui.perspective.trend"
+ name="Trend">
+ </perspective>
+ </extension>
+ <extension
+ point="org.eclipse.ui.perspectiveExtensions">
+ <perspectiveExtension
+ targetID="org.simantics.sysdyn.ui.perspective">
+ <view
+ id="org.simantics.browsing.ui.graph.propertyView"
+ ratio="0.65f"
+ relationship="bottom"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.eclipse.ui.console.ConsoleView"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.trend.view"
+ ratio="0.4f"
+ relationship="left"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.structure.view"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.sysdyn.ui.trend.view">
+ </view>
+ <view
+ id="org.simantics.modeling.ui.browser"
+ ratio="0.25f"
+ relationship="left"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.simantics.diagram.symbollibrary"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.modeling.ui.browser">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.values.view"
+ relationship="stack"
+ relative="org.simantics.sysdyn.ui.trend.view">
+ </view>
+ <view
+ id="org.simantics.issues.ui.issueview2"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.diagram.profile"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.jfreechart.chartPanel"
+ minimized="true"
+ ratio="0.5"
+ relationship="right"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.simantics.workbench.search.browser"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.modeling.ui.browser">
+ </view>
+ <!--
+ <view
+ id="org.simantics.document.workbench.documentViewer"
+ minimized="true"
+ relationship="stack"
+ relative="org.simantics.jfreechart.chartPanel">
+ </view>
+ -->
+ </perspectiveExtension>
+ <perspectiveExtension
+ targetID="org.simantics.sysdyn.ui.perspective.equation">
+ <view
+ id="org.simantics.browsing.ui.graph.propertyView"
+ minimized="false"
+ ratio="0.65f"
+ relationship="right"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.eclipse.ui.console.ConsoleView"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.trend.view"
+ minimized="true"
+ ratio="0.4f"
+ relationship="left"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.structure.view"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.sysdyn.ui.trend.view">
+ </view>
+ <view
+ id="org.simantics.modeling.ui.browser"
+ minimized="true"
+ ratio="0.25f"
+ relationship="left"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.simantics.diagram.symbollibrary"
+ minimized="true"
+ relationship="stack"
+ relative="org.simantics.modeling.ui.browser">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.values.view"
+ relationship="stack"
+ relative="org.simantics.sysdyn.ui.trend.view">
+ </view>
+ <view
+ id="org.simantics.issues.ui.issueview2"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.diagram.profile"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.jfreechart.chartPanel"
+ minimized="true"
+ ratio="0.5"
+ relationship="right"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.simantics.workbench.search.browser"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.modeling.ui.browser">
+ </view>
+ </perspectiveExtension>
+ <perspectiveExtension
+ targetID="org.simantics.sysdyn.ui.perspective.trend">
+ <view
+ id="org.simantics.browsing.ui.graph.propertyView"
+ minimized="true"
+ ratio="0.6f"
+ relationship="bottom"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.eclipse.ui.console.ConsoleView"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.trend.view"
+ ratio="0.4f"
+ relationship="bottom"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.structure.view"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.sysdyn.ui.trend.view">
+ </view>
+ <view
+ id="org.simantics.modeling.ui.browser"
+ minimized="true"
+ ratio="0.25f"
+ relationship="left"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.simantics.diagram.symbollibrary"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.modeling.ui.browser">
+ </view>
+ <view
+ id="org.simantics.sysdyn.ui.values.view"
+ relationship="stack"
+ relative="org.simantics.sysdyn.ui.trend.view">
+ </view>
+ <view
+ id="org.simantics.issues.ui.issueview2"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.diagram.profile"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.browsing.ui.graph.propertyView">
+ </view>
+ <view
+ id="org.simantics.jfreechart.chartPanel"
+ minimized="false"
+ ratio="0.4"
+ relationship="right"
+ relative="org.eclipse.ui.editorss">
+ </view>
+ <view
+ id="org.simantics.workbench.search.browser"
+ minimized="false"
+ relationship="stack"
+ relative="org.simantics.modeling.ui.browser">
+ </view>
+ </perspectiveExtension>
+ </extension>
+ <extension
+ point="org.eclipse.ui.contexts">
+ <context
+ id="org.simantics.sysdyn.ui.basicExperiment"
+ name="Basic Experiment">
+ </context>
+ <context
+ id="org.simantics.sysdyn.ui.playbackExperiment"
+ name="Playback Experiment">
+ </context>
+ <context
+ id="org.simantics.sysdyn.ui.gameExperiment"
+ name="Game Experiment">
+ </context>
+ <context
+ id="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment"
+ name="Sensitivity Analysis Experiment">
+ </context>
+ </extension>
+ <extension
+ point="org.eclipse.ui.menus">
+ <!--<menuContribution
+ locationURI="menu:sFile?after=import.ext">
+ <command commandId="org.eclipse.ui.file.import" />
+ <command commandId="org.eclipse.ui.file.export" />
+ </menuContribution>-->
+ <menuContribution
+ locationURI="toolbar:org.eclipse.ui.main.toolbar">
+ <toolbar
+ id="org.simantics.sysdyn.ui.modelToolbar">
+ <command
+ commandId="org.simantics.sysdyn.ui.exportModelButton"
+ icon="platform:/plugin/com.famfamfam.silk/icons/disk.png"
+ id="org.simantics.sysdyn.ui.export.button"
+ tooltip="Save model">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.exportModelAsButton"
+ icon="icons/save_as.png"
+ id="org.simantics.sysdyn.ui.exportAs.button"
+ tooltip="Save model as...">
+ </command>
+ </toolbar>
+ <toolbar
+ id="org.simantics.sysdyn.ui.diagramToolbar">
+ </toolbar>
+ <toolbar
+ id="org.simantics.sysdyn.ui.experimentControlToolbar">
+ <command
+ commandId="org.simantics.sysdyn.ui.run"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"
+ id="org.simantics.sysdyn.ui.run.button"
+ label="Simulate"
+ style="push">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.basicExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.toggleSimulation"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"
+ label="Simulate On Change"
+ style="toggle"
+ tooltip="Simulate On Change">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.basicExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.dispose"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"
+ id="org.simantics.sysdyn.ui.dispose.button"
+ label="Quit Experiment"
+ tooltip="Quit Experiment">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.basicExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.saveResults"
+ icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"
+ id="org.simantics.sysdyn.ui.save.button"
+ label="Save Results">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.basicExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.saveIC"
+ icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"
+ id="org.simantics.sysdyn.ui.saveic.button"
+ label="Save Initial Condition">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.gameExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.saveHistory"
+ icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"
+ id="org.simantics.sysdyn.ui.savehistory.button"
+ label="Save History">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.gameExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.synthesisSimulation"
+ hoverIcon="icons/equalizer.png"
+ icon="icons/equalizer.png"
+ label="Sliders and Trends"
+ style="toggle"
+ tooltip="Sliders and Trends">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.basicExperiment">
+ </equals>
+ </iterate>
+ <and>
+ <count
+ value="0">
+ </count>
+ </and>
+ </with>
+ </visibleWhen>
+ </command>
+ </toolbar>
+ <toolbar
+ id="org.simantics.sysdyn.ui.playbackControlToolbar">
+ <command
+ commandId="org.simantics.sysdyn.ui.playbackReset"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_start_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_start.png"
+ id="org.simantics.sysdyn.ui.playbackReset.button"
+ label="Reset"
+ style="push"
+ tooltip="Reset">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.playbackExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.playback"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"
+ id="org.simantics.sysdyn.ui.playback.button"
+ label="Start Playback"
+ style="pulldown"
+ tooltip="Start playback">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.playbackExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <dynamic
+ class="org.simantics.sysdyn.ui.menu.PlaybackSliderContribution"
+ id="org.simantics.sysdyn.ui.playbackSlider">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.playbackExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </dynamic>
+ <command
+ commandId="org.simantics.sysdyn.ui.playbackReload"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"
+ label="Reload"
+ style="push"
+ tooltip="Reload">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.playbackExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.dispose"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"
+ id="org.simantics.sysdyn.ui.dispose.button"
+ label="Quit Experiment"
+ tooltip="Quit Experiment">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.playbackExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ </toolbar>
+ <toolbar
+ id="org.simantics.sysdyn.ui.gameControlToolbar">
+ <command
+ commandId="org.simantics.sysdyn.ui.reloadGame"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"
+ id="org.simantics.sysdyn.ui.reload.game.button"
+ label="Reload Game"
+ style="push">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.gameExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <dynamic
+ class="org.simantics.sysdyn.ui.menu.GameStepDurationContribution"
+ id="org.simantics.sysdyn.ui.gameStepDuration">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.gameExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </dynamic>
+ <command
+ commandId="org.simantics.sysdyn.ui.step"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_end_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_end.png"
+ id="org.simantics.sysdyn.ui.step.button"
+ label="Step"
+ style="push">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.gameExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.dispose"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"
+ id="org.simantics.sysdyn.ui.dispose.button"
+ label="Quit Experiment"
+ tooltip="Quit Experiment">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.gameExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ </toolbar>
+ <toolbar
+ id="org.simantics.sysdyn.ui.sensitivityAnalysisControlToolbar">
+ <command
+ commandId="org.simantics.sysdyn.ui.runSensitivityAnalysis"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"
+ id="org.simantics.sysdyn.ui.runSensitivityAnalysis.button"
+ label="Simulate"
+ style="push">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_repeat_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_repeat.png"
+ label="Simulate On Change"
+ style="toggle"
+ tooltip="Simulate On Change">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.dispose"
+ hoverIcon="platform:/plugin/com.famfamfam.silk/icons/control_eject_blue.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_eject.png"
+ id="org.simantics.sysdyn.ui.dispose.button"
+ label="Quit Experiment"
+ tooltip="Quit Experiment">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.saveSensitivityAnalysisResults"
+ icon="platform:/plugin/com.famfamfam.silk/icons/table_save.png"
+ id="org.simantics.sysdyn.ui.saveSensitivityAnalysis.button"
+ label="Save Sensitivity Analysis Results">
+ <visibleWhen>
+ <with
+ variable="activeContexts">
+ <iterate
+ ifEmpty="false"
+ operator="or">
+ <equals
+ value="org.simantics.sysdyn.ui.sensitivityAnalysisExperiment">
+ </equals>
+ </iterate>
+ </with>
+ </visibleWhen>
+ </command>
+ </toolbar>
+ </menuContribution>
+ <menuContribution
+ locationURI="toolbar:org.simantics.sysdyn.ui.trend.view">
+ <command
+ commandId="org.simantics.sysdyn.ui.trend.view.pin"
+ icon="icons/table_multiple_pinned.png"
+ label="Pin Trend"
+ style="toggle"
+ tooltip="Pins the trend so that it does not react to selection changes">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.trend.view.png"
+ icon="platform:/plugin/com.famfamfam.silk/icons/images.png"
+ label="Export to PNG"
+ style="push"
+ tooltip="Exports the trend to PNG file">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.trend.view.svg"
+ icon="platform:/plugin/com.famfamfam.silk/icons/map.png"
+ label="Export to SVG"
+ style="push"
+ tooltip="Exports the trend to SVG file">
+ </command>
+ </menuContribution>
+
+ <menuContribution
+ locationURI="popup:#EnumerationTabPopup?after=wbStart">
+
+ <command
+ commandId="org.simantics.sysdyn.ui.renameNode"
+ icon="platform:/plugin/com.famfamfam.silk/icons/textfield_rename.png"
+ id="org.simantics.sysdyn.ui.browser.rename"
+ label="Rename"
+ style="push">
+ <visibleWhen checkEnabled="true">
+ </visibleWhen>
+ </command>
+
+ </menuContribution>
+ <menuContribution
+ locationURI="popup:#SysdynBrowserPopup?after=wbStart">
+ <menu id="org.simantics.new"
+ label="New">
+ <!--
+ <command
+ commandId="org.simantics.modeling.ui.newModel"
+ id="org.simantics.sysdyn.ui.browser.newModel"
+ label="Model"
+ style="push">
+ </command>
+ -->
+ <command
+ commandId="org.simantics.sysdyn.ui.newSCLModule"
+ icon="platform:/plugin/com.famfamfam.silk/icons/script.png"
+ id="org.simantics.sysdyn.ui.newSCLModule"
+ label="SCL Module"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/SharedOntology"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Library"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Simulation-0.0/Model"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newAnnotationType"
+ icon="platform:/plugin/com.famfamfam.silk/icons/note.png"
+ id="org.simantics.sysdyn.ui.newAnnotationType"
+ label="Annotation Type"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Library"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Structural-0.0/ComponentType"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newAnnotationValue"
+ icon="platform:/plugin/com.famfamfam.silk/icons/note.png"
+ id="org.simantics.sysdyn.ui.newAnnotationValue"
+ label="Annotation Value"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Entity"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newLibrary"
+ icon="platform:/plugin/com.famfamfam.silk/icons/folder.png"
+ id="org.simantics.sysdyn.ui.newLibrary"
+ label="Library"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Library"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newModuleNode"
+ icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"
+ id="org.simantics.sysdyn.ui.browser.newModule"
+ label="Module type"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModulesNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newExperiment"
+ icon="platform:/plugin/com.famfamfam.silk/icons/time.png"
+ id="org.simantics.sysdyn.ui.browser.newExperiment"
+ label="Experiment"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newPlaybackExperiment"
+ icon="platform:/plugin/com.famfamfam.silk/icons/timeline_marker.png"
+ id="org.simantics.sysdyn.ui.browser.newPlaybackExperiment"
+ label="Playback Experiment"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newGameExperiment"
+ icon="platform:/plugin/com.famfamfam.silk/icons/time_go.png"
+ id="org.simantics.sysdyn.ui.browser.newGameExperiment"
+ label="Game Experiment"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"
+ icon="icons/time_rainbow.png"
+ id="org.simantics.sysdyn.ui.browser.newSensitivityAnalysisExperiment"
+ label="Sensitivity Analysis Experiment"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newEnumeration"
+ id="org.simantics.sysdyn.ui.browser.newEnumeration"
+ label="Enumeration"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newFunction"
+ id="org.simantics.sysdyn.ui.browser.newFunction"
+ label="Function"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newFunctionLibrary"
+ label="Function Library"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newSharedFunctionLibrary"
+ label="Shared Function Library"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newSpreadSheet"
+ label="Sheet"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.BookNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newXYLineChart"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_line.png"
+ id="org.simantics.sysdyn.ui.browser.newXYLineChart"
+ label="Line Chart"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newSensitivityChart"
+ icon="platform:/plugin/com.famfamfam.silk/icons/rainbow.png"
+ id="org.simantics.sysdyn.ui.browser.newSensitivityChart"
+ label="Sensitivity Chart"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newBarChart"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_bar.png"
+ id="org.simantics.sysdyn.ui.browser.newBarChart"
+ label="Bar Chart"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newPieChart"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_pie.png"
+ id="org.simantics.sysdyn.ui.browser.newPieChart"
+ label="Pie Chart"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ChartsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newHistoryData"
+ icon="platform:/plugin/com.famfamfam.silk/icons/table.png"
+ id="org.simantics.sysdyn.ui.browser.newHistoryData"
+ label="History Data"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.newModel"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.ui.browser.newModel"
+ label="Model"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <!--
+ <command
+ commandId="org.simantics.documentation.workbench.newDocumentation"
+ icon="platform:/plugin/com.famfamfam.silk/icons/script.png"
+ id="org.simantics.sysdyn.ui.browser.newDocumentation"
+ label="Document"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.document.workbench.browser_old.DocumentationFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ -->
+ </menu>
+ <dynamic
+ class="org.simantics.ui.contribution.OpenWithMenuContribution"
+ id="org.simantics.sysdyn.ui.browser.openWithMenu">
+ </dynamic>
+ <command
+ commandId="org.simantics.sysdyn.ui.activateResult"
+ id="org.simantics.sysdyn.ui.browser.activateResult"
+ label="Show in charts"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.activateResultSet"
+ id="org.simantics.sysdyn.ui.browser.activateResultSet"
+ label="Show in charts"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.renameNode"
+ icon="platform:/plugin/com.famfamfam.silk/icons/textfield_rename.png"
+ id="org.simantics.sysdyn.ui.browser.rename"
+ label="Rename"
+ style="push">
+ <visibleWhen checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.removeNode"
+ icon="platform:/plugin/com.famfamfam.silk/icons/cross.png"
+ id="org.simantics.sysdyn.ui.browser.remove"
+ label="Remove"
+ style="push">
+ <visibleWhen checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <menu
+ id="org.simantics.import"
+ label="Import">
+ <command
+ commandId="org.simantics.sysdyn.ui.importModel"
+ label="Model"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.importSharedLibrary"
+ label="Shared Library"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <!--
+ <command
+ commandId="org.simantics.sysdyn.ui.importMdl"
+ label="Vensim model"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ -->
+ <command
+ commandId="org.simantics.image.ui.importImage"
+ icon="platform:/plugin/com.famfamfam.silk/icons/image_add.png"
+ label="Image"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.image.ui.modelBrowser.ImagesNode"
+ property="org.simantics.modeling.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.importFunctionLibrary"
+ label="Function library"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.importModule"
+ label="Module"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.importMdl"
+ label="Vensim Model (.mdl)"
+ style="push">
+ </command>
+ </menu>
+ <menu
+ id="org.simantics.export"
+ label="Export">
+ <command
+ commandId="org.simantics.sysdyn.ui.exportSharedOntology"
+ icon="platform:/plugin/com.famfamfam.silk/icons/folder.png"
+ id="org.simantics.sysdyn.ui.exportSharedOntology"
+ label="Shared Library"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.exportModel"
+ label="Model"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.exportFunctionLibrary"
+ label="Function library"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.exportModule"
+ label="Module"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ </visibleWhen>
+ </command>
+ </menu>
+ <command
+ commandId="org.eclipse.ui.edit.findReplace"
+ label="Find"
+ style="push">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.activateExperiment"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"
+ id="org.simantics.sysdyn.ui.browser.activateExperiment"
+ label="Activate Experiment"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.assignIC"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_play_blue.png"
+ id="org.simantics.sysdyn.ui.browser.assignIC"
+ label="Assign IC"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ </menuContribution>
+ <menuContribution
+ locationURI="popup:#SysdynDiagramPopup?after=wbStart">
+ <command
+ commandId="org.simantics.sysdyn.ui.showModule"
+ icon="platform:/plugin/com.famfamfam.silk/icons/palette.png"
+ label="Show Module"
+ style="push">
+ <visibleWhen>
+ <with
+ variable="selection">
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"
+ property="org.simantics.graph.resourceType">
+ </test>
+ </with>
+ </visibleWhen>
+ </command>
+ <dynamic
+ class="org.simantics.sysdyn.ui.menu.FontContextMenuContribution"
+ id="org.simantics.sysdyn.ui.fontContextMenu">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Diagram-0.0/FontProvider"
+ property="org.simantics.graph.resourceTypes"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </dynamic>
+ <command
+ commandId="org.eclipse.ui.edit.copy"
+ label="Copy"
+ style="push">
+ <visibleWhen
+ checkEnabled="true">
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.eclipse.ui.edit.paste"
+ label="Paste"
+ style="push">
+ </command>
+ <command
+ commandId="org.eclipse.ui.edit.findReplace"
+ label="Find"
+ style="push">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.pasteSpecial"
+ icon="platform:/plugin/com.famfamfam.silk/icons/paste_plain.png"
+ label="Paste special"
+ style="push">
+ </command>
+ <command
+ commandId="org.eclipse.ui.edit.cut"
+ label="Cut"
+ style="push">
+ <visibleWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/SCLModule"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ <command
+ commandId="org.eclipse.ui.edit.rename"
+ label="Rename"
+ style="push">
+ <visibleWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ValveSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/StockSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/AuxiliarySymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/CloudSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/InputSymbol"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/SCLModule"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </visibleWhen>
+ </command>
+ </menuContribution>
+ <menuContribution
+ locationURI="popup:#ExternalFunctionFileBrowser?after=wbStart">
+ </menuContribution>
+ <menuContribution
+ allPopups="false"
+ locationURI="menu:sFile?after=#FileNewMenu">
+ <command
+ commandId="org.simantics.sysdyn.ui.importModel"
+ label="Import Model"
+ style="push">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.importSharedLibrary"
+ label="Import Shared Library"
+ style="push">
+ </command>
+ </menuContribution>
+ <menuContribution
+ allPopups="false"
+ locationURI="menu:#FileNewMenu">
+ <command
+ commandId="org.simantics.sysdyn.ui.newModel"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation_add.png"
+ label="SD Model"
+ style="push">
+ </command>
+ </menuContribution>
+ <menuContribution
+ allPopups="false"
+ locationURI="menu:org.simantics.sysdyn.ui.playback.button">
+ <command
+ commandId="org.simantics.sysdyn.ui.playbackSlow"
+ icon="icons/control_step.png"
+ label="Slow"
+ style="push">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.playbackNormal"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_play.png"
+ label="Normal"
+ style="push">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.playbackFast"
+ icon="platform:/plugin/com.famfamfam.silk/icons/control_fastforward.png"
+ label="Fast"
+ style="push">
+ </command>
+ </menuContribution>
+ <menuContribution
+ locationURI="toolbar:org.simantics.sysdyn.ui.chartPanel">
+ <command
+ commandId="org.simantics.sysdyn.ui.chartPanelOrientation"
+ icon="platform:/plugin/com.famfamfam.silk/icons/page_white_text_width.png"
+ label="Change Orientation"
+ style="push"
+ tooltip="Change orientation">
+ </command>
+ </menuContribution>
+ </extension>
+ <extension
+ point="org.eclipse.ui.commands">
+ <command
+ id="org.simantics.sysdyn.ui.newSCLModule"
+ name="New SCL Module">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newAnnotationType"
+ name="New Annotation Type">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newAnnotationValue"
+ name="New Annotation Value">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newLibrary"
+ name="New Library">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.exportSharedOntology"
+ name="Export Shared Library">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.trend.view.pin"
+ name="Pin Trend">
+ <state
+ class="org.eclipse.jface.commands.ToggleState"
+ id="org.simantics.sysdyn.ui.trend.view.pin.state">
+ </state>
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.trend.view.png"
+ name="Export To PNG">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.trend.view.svg"
+ name="Export To SVG">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.showModule"
+ name="Show Module">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.pasteSpecial"
+ name="Paste Special">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.removeNode"
+ name="Remove Node">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.renameNode"
+ name="Rename Node">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.enumerationIndexRenameNode"
+ name="Rename Node">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleSimulation"
+ id="org.simantics.sysdyn.ui.toggleSimulation"
+ name="Toggle Simulate">
+ <state
+ class="org.eclipse.jface.commands.ToggleState"
+ id="org.simantics.sysdyn.ui.toggleSimulation.state">
+ </state>
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.SynthesisSimulation"
+ id="org.simantics.sysdyn.ui.synthesisSimulation"
+ name="Slider and Trends">
+ <state
+ class="org.eclipse.jface.commands.ToggleState"
+ id="org.simantics.sysdyn.ui.synthesisSimulation.state">
+ </state>
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewModuleNodeHandler"
+ id="org.simantics.sysdyn.ui.newModuleNode"
+ name="New Module">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.activateExperiment"
+ name="Activate Experiment">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.assignIC"
+ name="Assign IC">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.RunBasicExperiment"
+ id="org.simantics.sysdyn.ui.run"
+ name="Run Basic Simulation">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.DisposeExperiment"
+ id="org.simantics.sysdyn.ui.dispose"
+ name="Quit Experiment">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.SaveResultsHandler"
+ id="org.simantics.sysdyn.ui.saveResults"
+ name="Save Results">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.SaveICHandler"
+ id="org.simantics.sysdyn.ui.saveIC"
+ name="Save Initial Condition">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.SaveHistoryHandler"
+ id="org.simantics.sysdyn.ui.saveHistory"
+ name="Save History">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleResultActivation"
+ id="org.simantics.sysdyn.ui.activateResult"
+ name="Show In Charts">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.ToggleResultSetActivation"
+ id="org.simantics.sysdyn.ui.activateResultSet"
+ name="Show In Charts">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewExperimentNodeHandler"
+ id="org.simantics.sysdyn.ui.newExperiment"
+ name="New Experiment">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.exportModel"
+ name="Export Model">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.importModel"
+ name="Import Model">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.importSharedLibrary"
+ name="Import Shared Library">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newEnumeration"
+ name="New Enumeration">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.importMdl"
+ name="Import .mdl">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewFunctionHandler"
+ id="org.simantics.sysdyn.ui.newFunction"
+ name="NewFunction">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.importExternalFunctionFile"
+ name="ImportExternalFunctionFile">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.exportExternalFunctionFile"
+ name="ExportExternalFunctionFile">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newFunctionLibrary"
+ name="New Function Library">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newSharedFunctionLibrary"
+ name="New Shared Function Library">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.importFunctionLibrary"
+ name="Import Function Library">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.exportFunctionLibrary"
+ name="Export Function Library">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.importModule"
+ name="Import Module">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.exportModule"
+ name="Export Module">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newSpreadSheet"
+ name="New SpreadSheet">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newModel"
+ name="New System Dynamics Model">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newPlaybackExperiment"
+ name="New Playback Experiment">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newGameExperiment"
+ name="New Game Experiment">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"
+ name="New Sensitivity Analysis Experiment">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackExperimentHandler"
+ id="org.simantics.sysdyn.ui.playback"
+ name="Playback experiment">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.SlowSpeedHandler"
+ id="org.simantics.sysdyn.ui.playbackSlow"
+ name="Slow Playback">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.NormalSpeedHandler"
+ id="org.simantics.sysdyn.ui.playbackNormal"
+ name="Normal Playback">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.FastSpeedHandler"
+ id="org.simantics.sysdyn.ui.playbackFast"
+ name="Fast Playback">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackResetHandler"
+ id="org.simantics.sysdyn.ui.playbackReset"
+ name="Reset Playback">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.simulationPlayback.PlaybackReloadHandler"
+ id="org.simantics.sysdyn.ui.playbackReload"
+ name="Reload Playback">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.ChartPanelOrientationHandler"
+ id="org.simantics.sysdyn.ui.chartPanelOrientation"
+ name="Chart Panel Orientation">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewXYLineChartHandler"
+ id="org.simantics.sysdyn.ui.newXYLineChart"
+ name="New XY Line Chart">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewBarChartHandler"
+ id="org.simantics.sysdyn.ui.newBarChart"
+ name="New Bar Chart">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewPieChartHandler"
+ id="org.simantics.sysdyn.ui.newPieChart"
+ name="New Pie Chart">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityChartHandler"
+ id="org.simantics.sysdyn.ui.newSensitivityChart"
+ name="New XY Line Chart">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.newComponents.NewHistoryDataHandler"
+ id="org.simantics.sysdyn.ui.newHistoryData"
+ name="New History Data">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.game.StepHandler"
+ id="org.simantics.sysdyn.ui.step"
+ name="Step">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.game.ReloadGameExperimentHandler"
+ id="org.simantics.sysdyn.ui.reloadGame"
+ name="Reload Game">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment"
+ name="New Game Experiment">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.RunSensitivityAnalysisExperiment"
+ id="org.simantics.sysdyn.ui.runSensitivityAnalysis"
+ name="Run Sensitivity Analysis Simulation">
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.ToggleSimulation"
+ id="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation"
+ name="Toggle Simulate">
+ <state
+ class="org.eclipse.jface.commands.ToggleState"
+ id="org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation.state">
+ </state>
+ </command>
+ <command
+ defaultHandler="org.simantics.sysdyn.ui.handlers.sensitivityAnalysis.SaveResultsHandler"
+ id="org.simantics.sysdyn.ui.saveSensitivityAnalysisResults"
+ name="Save Results">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.exportModelButton"
+ name="Export Model">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.exportModelAsButton"
+ name="Export Model As...">
+ </command>
+ <command
+ id="org.simantics.sysdyn.ui.diagramTool"
+ name="Diagram Tool">
+ <state
+ id="org.eclipse.ui.commands.radioState">
+ <class
+ class="org.eclipse.ui.handlers.RadioState">
+ <parameter
+ name="default"
+ value="pointer">
+ </parameter>
+ <parameter
+ name="persisted"
+ value="true">
+ </parameter>
+ </class>
+ </state>
+ </command>
+ </extension>
+ <extension
+ point="org.eclipse.ui.handlers">
+
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.EnumerationIndexRenameNodeHandler"
+ commandId="org.simantics.sysdyn.ui.enumerationIndexRenameNode">
+ </handler>
+
+
+ <handler
+ class="org.simantics.sysdyn.ui.trend.PinTrend"
+ commandId="org.simantics.sysdyn.ui.trend.view.pin">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.trend.TrendToPng"
+ commandId="org.simantics.sysdyn.ui.trend.view.png">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.trend.TrendToSvg"
+ commandId="org.simantics.sysdyn.ui.trend.view.svg">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.NewSCLModuleHandler"
+ commandId="org.simantics.sysdyn.ui.newSCLModule">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SCLModulesFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/SharedOntology"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Library"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Simulation-0.0/Model"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.NewAnnotationTypeHandler"
+ commandId="org.simantics.sysdyn.ui.newAnnotationType">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Library"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="http://www.simantics.org/Structural-0.0/ComponentType"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.NewAnnotationValueHandler"
+ commandId="org.simantics.sysdyn.ui.newAnnotationValue">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Entity"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.NewLibraryHandler"
+ commandId="org.simantics.sysdyn.ui.newLibrary">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="http://www.simantics.org/Layer0-0.0/Library"
+ property="org.simantics.graph.resourceType"
+ value="true">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"
+ property="org.simantics.sysdyn.ui.nodeClass"
+ value="true">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.ShowModuleHandler"
+ commandId="org.simantics.sysdyn.ui.showModule">
+ <enabledWhen>
+ <and>
+ <with
+ variable="selection">
+ <and>
+ <test
+ args="http://www.simantics.org/Sysdyn-0.0/ModuleSymbol"
+ property="org.simantics.graph.resourceType">
+ </test>
+ </and>
+ </with>
+ </and>
+ </enabledWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.PasteSpecialHandler"
+ commandId="org.simantics.sysdyn.ui.pasteSpecial">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.UnlinkNodeHandler2"
+ commandId="org.simantics.sysdyn.ui.removeNode">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.image.ui.modelBrowser.ImageNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.operating.ui.modelBrowser.CompositeNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SheetNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.AbstractChartNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SCLModule"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <!--
+ <test
+ args="org.simantics.document.workbench.browser_old.DocumentationNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ -->
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.RenameNodeHandler"
+ commandId="org.simantics.sysdyn.ui.renameNode">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SimulationResultSetNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SheetNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.BarChartNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModuleNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SCLModule"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <!--
+ <test
+ args="org.simantics.document.workbench.browser_old.DocumentationNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ -->
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.imports.ImportModelHandler"
+ commandId="org.simantics.sysdyn.ui.importModel">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.imports.ImportSharedLibraryHandler"
+ commandId="org.simantics.sysdyn.ui.importSharedLibrary">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.exports.ExportModelHandler"
+ commandId="org.simantics.sysdyn.ui.exportModel">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModelNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.imports.ImportMdlHandler"
+ commandId="org.simantics.sysdyn.ui.importMdl">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewEnumerationNodeHandler"
+ commandId="org.simantics.sysdyn.ui.newEnumeration">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.imports.ImportExternalFunctionFilesHandler"
+ commandId="org.simantics.sysdyn.ui.importExternalFunctionFile">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.exports.ExportExternalFunctionFilesHandler"
+ commandId="org.simantics.sysdyn.ui.exportExternalFunctionFile">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewFunctionLibraryHandler"
+ commandId="org.simantics.sysdyn.ui.newFunctionLibrary">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewSharedFunctionLibraryHandler"
+ commandId="org.simantics.sysdyn.ui.newSharedFunctionLibrary">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.exports.ExportFunctionLibrary"
+ commandId="org.simantics.sysdyn.ui.exportFunctionLibrary">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.imports.ImportFunctionLibrary"
+ commandId="org.simantics.sysdyn.ui.importFunctionLibrary">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.imports.ImportModuleHandler"
+ commandId="org.simantics.sysdyn.ui.importModule">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModulesNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.exports.ExportModuleHandler"
+ commandId="org.simantics.sysdyn.ui.exportModule">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.modeling.ui.modelBrowser.handlers.StandardCopyHandler"
+ commandId="org.eclipse.ui.edit.copy">
+ <enabledWhen>
+ <not>
+ <count
+ value="0">
+ </count>
+ </not>
+ </enabledWhen>
+ <activeWhen>
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.EnumerationNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.modeling.ui.modelBrowser.handlers.StandardPasteHandler"
+ commandId="org.eclipse.ui.edit.paste">
+ <enabledWhen>
+ <not>
+ <count
+ value="0">
+ </count>
+ </not>
+ </enabledWhen>
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ConfigurationNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModuleNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ModuleTypeNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewSpreadSheetHandler"
+ commandId="org.simantics.sysdyn.ui.newSpreadSheet">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewModelHandler"
+ commandId="org.simantics.sysdyn.ui.newModel">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewPlaybackExperimentNodeHandler"
+ commandId="org.simantics.sysdyn.ui.newPlaybackExperiment">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewGameExperimentNodeHandler"
+ commandId="org.simantics.sysdyn.ui.newGameExperiment">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityAnalysisExperimentNodeHandler"
+ commandId="org.simantics.sysdyn.ui.newSensitivityAnalysisExperiment">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.FindReplaceHandler"
+ commandId="org.eclipse.ui.edit.findReplace">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.exports.ExportModelAsButtonHandler"
+ commandId="org.simantics.sysdyn.ui.exportModelAsButton">
+ <activeWhen>
+ <or>
+ <with
+ variable="activePartId">
+ <equals value="org.simantics.browsing.ui.graph.propertyView"/>
+ </with>
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"
+ property="org.simantics.sysdyn.ui.nodeClass2">
+ </test>
+ </with>
+ </or>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.exports.ExportModelButtonHandler"
+ commandId="org.simantics.sysdyn.ui.exportModelButton">
+ <activeWhen>
+ <or>
+ <with
+ variable="activePartId">
+ <equals
+ value="org.simantics.browsing.ui.graph.propertyView">
+ </equals>
+ </with>
+ <with
+ variable="selection">
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.VariableNode"
+ property="org.simantics.sysdyn.ui.nodeClass2">
+ </test>
+ </with>
+ </or>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.DiagramToolHandler"
+ commandId="org.simantics.sysdyn.ui.diagramTool">
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator"
+ commandId="org.simantics.sysdyn.ui.activateExperiment">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.AssignIC"
+ commandId="org.simantics.sysdyn.ui.assignIC">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.ExperimentNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.handlers.ExportSharedOntologyHandler"
+ commandId="org.simantics.sysdyn.ui.exportSharedOntology">
+ <activeWhen>
+ <with
+ variable="selection">
+ <or>
+ <test
+ args="org.simantics.sysdyn.ui.browser.nodes.SharedOntologyNode"
+ property="org.simantics.sysdyn.ui.nodeClass">
+ </test>
+ </or>
+ </with>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.PropertyViewUndoHandler"
+ commandId="org.eclipse.ui.edit.undo">
+ <activeWhen>
+ <reference
+ definitionId="org.simantics.sysdyn.ui.inExpressionField">
+ </reference>
+ </activeWhen>
+ </handler>
+ <handler
+ class="org.simantics.sysdyn.ui.PropertyViewUndoHandler"
+ commandId="org.eclipse.ui.edit.redo">
+ <activeWhen>
+ <reference
+ definitionId="org.simantics.sysdyn.ui.inExpressionField">
+ </reference>
+ </activeWhen>
+ </handler>
+
+ </extension>
+
+ <extension
+ point="org.eclipse.ui.importWizards">
+
+ <category
+ id="org.simantics.sysdyn.import"
+ name="Sysdyn">
+ </category>
+<!-- <wizard
+ category="org.simantics.sysdyn.import"
+ class="org.simantics.sysdyn.ui.wizards.models.ImportWizardModel"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.ui.wizards.modelImport"
+ name="Import Sysdyn Model">
+ </wizard> -->
+ <wizard
+ category="org.simantics.sysdyn.import"
+ class="org.simantics.sysdyn.ui.wizards.model.SysdynModelImportWizard"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.import.model2"
+ name="Import Sysdyn Model">
+ </wizard>
+<!-- <wizard
+ category="org.simantics.sysdyn.import"
+ class="org.simantics.sysdyn.ui.wizards.modules.ImportWizardModule"
+ icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"
+ id="org.simantics.sysdyn.ui.wizards.moduleImport"
+ name="Import Sysdyn Module">
+ </wizard>
+ <wizard
+ category="org.simantics.sysdyn.import"
+ class="org.simantics.sysdyn.ui.wizards.functions.ImportWizardFunction"
+ icon="platform:/plugin/com.famfamfam.silk/icons/brick.png"
+ id="org.simantics.sysdyn.ui.wizards.functionImport"
+ name="Import Sysdyn Function Library">
+ </wizard>
+ <wizard
+ category="org.simantics.sysdyn.import"
+ class="org.simantics.sysdyn.ui.wizards.mdl.ImportWizardMdl"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.ui.wizards.mdlImport"
+ name="Import Vensim Model (.mdl)">
+ </wizard> -->
+ </extension>
+
+ <extension
+ point="org.eclipse.ui.exportWizards">
+
+ <category
+ id="org.simantics.sysdyn.export"
+ name="Sysdyn">
+ </category>
+<!-- <wizard
+ category="org.simantics.sysdyn.export"
+ class="org.simantics.sysdyn.ui.wizards.models.ExportWizardModel"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.export.model"
+ name="Export Sysdyn Model">
+ </wizard> -->
+ <wizard
+ category="org.simantics.sysdyn.export"
+ class="org.simantics.sysdyn.ui.wizards.model.SysdynModelExportWizard"
+ icon="platform:/plugin/com.famfamfam.silk/icons/chart_organisation.png"
+ id="org.simantics.sysdyn.export.model2"
+ name="Export Sysdyn Model">
+ </wizard>
+<!-- <wizard
+ category="org.simantics.sysdyn.export"
+ class="org.simantics.sysdyn.ui.wizards.modules.ExportWizardModule"
+ icon="platform:/plugin/com.famfamfam.silk/icons/bricks.png"
+ id="org.simantics.sysdyn.export.module"
+ name="Export Sysdyn Module">
+ </wizard>
+ <wizard
+ category="org.simantics.sysdyn.export"
+ class="org.simantics.sysdyn.ui.wizards.functions.ExportWizardFunction"
+ icon="platform:/plugin/com.famfamfam.silk/icons/brick.png"
+ id="org.simantics.sysdyn.export.function"
+ name="Export Sysdyn Function Library">
+ </wizard> -->
+ </extension>
+
+ <extension
+ point="org.eclipse.core.expressions.propertyTesters">
+ <propertyTester
+ class="org.simantics.browsing.ui.swt.NodePropertyTester"
+ id="org.simantics.browsing.ui.nodePropertyTester"
+ namespace="org.simantics.sysdyn.ui"
+ properties="nodeClass"
+ type="org.eclipse.jface.viewers.IStructuredSelection">
+ </propertyTester>
+ <propertyTester
+ class="org.simantics.sysdyn.ui.browser.nodes.ExportTester"
+ id="org.simantics.sysdyn.ui.selectionPropertyTester"
+ namespace="org.simantics.sysdyn.ui"
+ properties="nodeClass2"
+ type="org.eclipse.jface.viewers.IStructuredSelection">
+ </propertyTester>
+ </extension>
+ <extension
+ point="org.simantics.browsing.ui.common.viewpointContributionBinding">
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ModuleType"
+ preference="1.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.Project"
+ preference="1.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.Modules"
+ preference="1.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.Model"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AnnotationContribution"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AnnotationContribution2"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.LibraryContribution"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.Experiment"
+ preference="1.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResult"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSet"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.Configuration"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraries"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.LibraryFunctions"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SharedFunctionLibraries"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.Book"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.Charts"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SCLModules"
+ preference="2">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.InitialConditions"
+ preference="2">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableVariableIndexes">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.AvailableEnumerations"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/UsedVariableIndexes">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.UsedEnumerations"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationIndexes"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationReplacement">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.ReplaceableEnumerations"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFiles"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ModelBrowser">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SysdynProject"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.functions.SharedFunctionLibraries"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.functions.SelectedSharedFunctionLibraries"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/FunctionTree">
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModels"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeLibraries"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedLibraries"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSubLibraries"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ImportModuleTree">
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModels"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ExportModuleTree">
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModels"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModules"
+ preference="2.0">
+ </implementation>
+ </binding>
+ </extension>
+
+ <extension
+ point="org.simantics.browsing.ui.common.comparableContextBinding">
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">
+ <implementation
+ class="org.simantics.modeling.ui.modelBrowser2.contributions.LexicalComparableContributor"
+ preference="1.0">
+ </implementation>
+ </binding>
+ </extension>
+
+ <extension
+ point="org.simantics.browsing.ui.common.labelerBinding">
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SharedOntologyLabeler"
+ preference="3.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ConfigurationLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.VariableLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ExperimentsLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ModelLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ModulesLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ExperimentLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ModuleLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.InputLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ModuleTypeLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.FunctionsLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SharedFunctionsLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.BookLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SheetLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ChartLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ChartsLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SCLModulesLabeler"
+ preference="2">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.InitialConditionsLabeler"
+ preference="2">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SCLModuleLabeler"
+ preference="2">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.InitialConditionLabeler"
+ preference="2">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AnnotationTypeLabeler"
+ preference="2">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AnnotationValueLabeler"
+ preference="2">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.LibraryLabeler"
+ preference="2">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableVariableIndexes">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationLabeler"
+ preference="1.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/UsedVariableIndexes">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.ConflictingEnumerationLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.EnumerationIndexLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationReplacement">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.ReplaceableEnumerationsLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.FunctionLibraryLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/FunctionTree">
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeFunctionLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedLibraryLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeSharedFolderLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ImportModuleTree">
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ExportModuleTree">
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.modules.ModuleTreeModulesLabeler"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.wizards.functions.FunctionTreeModelLabeler"
+ preference="2.0">
+ </implementation>
+ </binding>
+ </extension>
+ <extension
+ point="org.simantics.browsing.ui.common.imagerBinding">
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SharedOntologyImager"
+ preference="3.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AnnotationTypeImager"
+ preference="3.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AnnotationValueImager"
+ preference="3.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.LibraryImager"
+ preference="3.0">
+ </implementation>
+ <implementation
+ class="org.simantics.browsing.ui.swt.ImageDescriptorProviderAdapter"
+ preference="1.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultImager"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetImager"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ChartImager"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ChartsImager"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ExternalFiles">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.externalFiles.ExternalFileImager"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/AvailableSharedFunctionLibraries">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"
+ preference="2.0">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/SelectedSharedFunctionLibraries">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.AbstractNodeImager"
+ preference="2.0">
+ </implementation>
+ </binding>
+ </extension>
+ <extension
+ point="org.simantics.browsing.ui.common.labelDecoratorBinding">
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultDecorator"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.SimulationResultSetDecorator"
+ preference="2.0">
+ </implementation>
+ <implementation
+ class="org.simantics.sysdyn.ui.browser.contributions.ExperimentLabelDecorator"
+ preference="2.0">
+ </implementation>
+ </binding>
+ </extension>
+ <extension
+ point="org.simantics.browsing.ui.common.selectionProcessorBinding">
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/Browser">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Modeling-0.0/ModelingBrowseContext">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">
+ </implementation>
+ </binding>
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/ModelingBrowseContext">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.ResourceSelectionProcessor">
+ </implementation>
+ </binding>
+ </extension>
+ <extension
+ point="org.simantics.browsing.ui.common.checkedStateBinding">
+ <binding
+ browseContext="http://www.simantics.org/Sysdyn-0.0/EnumerationIndexes">
+ <implementation
+ class="org.simantics.sysdyn.ui.properties.widgets.arrays.ShowInChartsCheckBox"
+ preference="2.0">
+ </implementation>
+ </binding>
+ </extension>
+ <extension
+ point="org.simantics.ui.resourceEditorAdapter">
+ <adapterClass
+ class="org.simantics.sysdyn.ui.editor.OpenDiagramFromConfigurationAdapter"
+ groupId="org.simantics.diagramEditor.group"
+ priority="100">
+ </adapterClass>
+ <adapterClass
+ class="org.simantics.sysdyn.ui.editor.OpenDiagramFromComponentAdapter"
+ priority="90">
+ </adapterClass>
+ <adapter
+ editorId="org.simantics.sysdyn.ui.modelicaEditor"
+ priority="2"
+ type_uris="http://www.simantics.org/Sysdyn-0.0/Configuration">
+ </adapter>
+ <adapter
+ editorId="org.simantics.sysdyn.ui.jfreeChartEditor"
+ priority="2"
+ type_uris="http://www.simantics.org/JFreeChart-0.0/Chart">
+ </adapter>
+ </extension>
+ <extension
+ point="org.simantics.ui.doubleClick">
+ <doubleClickAction
+ class="org.simantics.sysdyn.ui.actions.ActivateExperimentAction"
+ name="Activate Sysdyn Experiment"
+ priority="300.0">
+ </doubleClickAction>
+ <doubleClickAction
+ class="org.simantics.sysdyn.ui.browser.actions.ActivateResultDatasetAction"
+ name="Activate Result In Charts"
+ priority="250.0">
+ </doubleClickAction>
+ <doubleClickAction
+ class="org.simantics.sysdyn.ui.browser.actions.ActivateResultSetDatasetAction"
+ name="Activate Result In Charts"
+ priority="240.0">
+ </doubleClickAction>
+ <doubleClickAction
+ class="org.simantics.sysdyn.ui.browser.actions.OpenSheetAction"
+ name="Open Spreadsheet"
+ priority="220.0">
+ </doubleClickAction>
+ <!--<doubleClickAction
+ class="org.simantics.sysdyn.ui.actions.ConsumeUnnecessaryEntersAction"
+ name="Consume unnecessary enters"
+ priority="200.0">
+ </doubleClickAction>-->
+ <doubleClickAction
+ class="org.simantics.sysdyn.ui.actions.ShowInstantiatedModuleAction"
+ name="Show Instantiated Module"
+ priority="100.0">
+ </doubleClickAction>
+ <doubleClickAction
+ name="Open Diagram Editor"
+ priority="10.0"
+ class="org.simantics.sysdyn.ui.browser.actions.OpenDiagramEditorFromModelDoubleClickAction">
+ </doubleClickAction>
+ </extension>
+ <extension
+ point="org.simantics.ui.toolbarCommand">
+ <command
+ commandId="org.simantics.sysdyn.ui.diagramTool"
+ image="platform:/plugin/com.famfamfam.silk/icons/lock.png"
+ name="Lock Sketch"
+ toolbarId="org.simantics.sysdyn.ui.diagramToolbar"
+ type="radio"
+ value="lock">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.diagramTool"
+ image="icons/cursor.png"
+ name="Pointer"
+ toolbarId="org.simantics.sysdyn.ui.diagramToolbar"
+ type="radio"
+ value="pointer">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.diagramTool"
+ image="icons/dependency.png"
+ name="Create Dependency (Alt+Mouse1)"
+ toolbarId="org.simantics.sysdyn.ui.diagramToolbar"
+ type="radio"
+ value="dependency">
+ </command>
+ <command
+ commandId="org.simantics.sysdyn.ui.diagramTool"
+ image="icons/flow.png"
+ name="Create Flow (Alt+Mouse2)"
+ toolbarId="org.simantics.sysdyn.ui.diagramToolbar"
+ type="radio"
+ value="flow">
+ </command>
+ </extension>
+ <extension
+ point="org.simantics.project.feature">
+ <feature
+ class="org.simantics.sysdyn.ui.project.SysdynProject"
+ description="System dynamics modelling project. Create system dynamics models and simulate them with OpenModelica."
+ id="org.simantics.sysdyn.project"
+ label="System Dynamics Project"
+ published="true">
+ <requires id="org.simantics.sysdyn.dependencies"/>
+ <requires id="org.simantics.simulation.experimentManager"/>
+ <installGroup id="org.simantics.sysdyn.feature.group" version="[1.0.0,2.0.0)"/>
+ </feature>
+ <feature
+ class="org.simantics.project.features.DependencyValidationFeature:http://www.simantics.org/Sysdyn-0.0/ImportedOntologies"
+ id="org.simantics.sysdyn.dependencies"
+ label="System Dynamics Ontology Dependencies">
+ </feature>
+ </extension>
+
+
+ <extension point="org.simantics.scl.reflection.binding">
+ <namespace path="http://www.simantics.org/Sysdyn-0.0/Validations">
+ <namespace path="Dependencies">
+ <externalClass className="org.simantics.db.Resource"/>
+ <externalClass className="org.simantics.db.layer0.variable.Variable"/>
+ <externalClass className="org.simantics.db.ReadGraph"/>
+ <externalClass className="org.simantics.db.WriteGraph"/>
+ <class className="org.simantics.sysdyn.ui.validation.DependencyFunction"/>
+ </namespace>
+ <namespace path="Expressions">
+ <externalClass className="org.simantics.db.Resource"/>
+ <externalClass className="org.simantics.db.layer0.variable.Variable"/>
+ <externalClass className="org.simantics.db.ReadGraph"/>
+ <externalClass className="org.simantics.db.WriteGraph"/>
+ <class className="org.simantics.sysdyn.ui.validation.ExpressionIssueFunction"/>
+ </namespace>
+ <namespace path="Functions">
+ <externalClass className="org.simantics.db.Resource"/>
+ <externalClass className="org.simantics.db.layer0.variable.Variable"/>
+ <externalClass className="org.simantics.db.ReadGraph"/>
+ <externalClass className="org.simantics.db.WriteGraph"/>
+ <class className="org.simantics.sysdyn.ui.validation.Functions"/>
+ </namespace>
+ <namespace path="Enumerations">
+ <externalClass className="org.simantics.db.Resource"/>
+ <externalClass className="org.simantics.db.layer0.variable.Variable"/>
+ <externalClass className="org.simantics.db.ReadGraph"/>
+ <externalClass className="org.simantics.db.WriteGraph"/>
+ <class className="org.simantics.sysdyn.ui.validation.EnumerationFunction"/>
+ </namespace>
+ <namespace path="Units">
+ <externalClass className="org.simantics.db.Resource"/>
+ <externalClass className="org.simantics.db.layer0.variable.Variable"/>
+ <externalClass className="org.simantics.db.ReadGraph"/>
+ <externalClass className="org.simantics.db.WriteGraph"/>
+ <class className="org.simantics.sysdyn.ui.validation.UnitFunction"/>
+ </namespace>
+ </namespace>
+ </extension>
+ <extension
+ point="org.eclipse.ui.preferencePages">
+ <page
+ class="org.simantics.sysdyn.ui.preferences.SolverPreferencePage"
+ id="org.simantics.sysdyn.solver.preferences"
+ name="Solver">
+ </page>
+ <page
+ class="org.simantics.sysdyn.ui.preferences.ModelicaPreferencePage"
+ id="org.simantics.modelica.preferences"
+ name="Modelica">
+ </page>
+ <page
+ class="org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferencePage"
+ id="org.simantics.sysdyn.diagram.preferences"
+ name="Sysdyn Diagrams">
+ </page>
+ </extension>
+ <extension
+ point="org.eclipse.core.runtime.preferences">
+ <initializer
+ class="org.simantics.modelica.preferences.ModelicaPreferenceInitializer">
+ </initializer>
+ <initializer
+ class="org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferencesInitializer">
+ </initializer>
+ </extension>
+
+ <extension point="org.eclipse.core.expressions.definitions">
+ <definition
+ id="org.simantics.sysdyn.ui.inExpressionField">
+ <with variable="activePartId">
+ <equals
+ value="org.simantics.browsing.ui.graph.propertyView">
+ </equals>
+ </with>
+ </definition>
+ </extension>
+
+</plugin>
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.actions;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator;\r
-import org.simantics.ui.DoubleClickEvent;\r
-import org.simantics.ui.IDoubleClickAction;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.ErrorLogger;\r
-import org.simantics.utils.ui.action.PriorityAction;\r
-\r
-public class ActivateExperimentAction implements IDoubleClickAction {\r
-\r
- @Override\r
- public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {\r
- ReadGraph g = e.getGraph();\r
- final Resource experiment = ResourceAdaptionUtils.toSingleResource(e.getResource());\r
- if (experiment == null)\r
- return;\r
-\r
- if (g.isInstanceOf(experiment, SimulationResource.getInstance(g).Experiment)) {\r
- final IProject project = SimanticsUI.getProject();\r
- if (project == null)\r
- return;\r
-\r
- final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- if (experimentManager == null) {\r
- ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());\r
- return;\r
- }\r
-\r
- e.add(new PriorityAction(PriorityAction.HIGH+20) {\r
- @Override\r
- public void run() {\r
- SysdynExperimentActivator.scheduleActivation(SimanticsUI.getSession(), project, experimentManager, experiment);\r
- }\r
- });\r
- e.consume();\r
- }\r
- \r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.actions;
+
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.project.IProject;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator;
+import org.simantics.ui.DoubleClickEvent;
+import org.simantics.ui.IDoubleClickAction;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.ErrorLogger;
+import org.simantics.utils.ui.action.PriorityAction;
+
+public class ActivateExperimentAction implements IDoubleClickAction {
+
+ @Override
+ public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {
+ ReadGraph g = e.getGraph();
+ final Resource experiment = ResourceAdaptionUtils.toSingleResource(e.getResource());
+ if (experiment == null)
+ return;
+
+ if (g.isInstanceOf(experiment, SimulationResource.getInstance(g).Experiment)) {
+ final IProject project = Simantics.getProject();
+ if (project == null)
+ return;
+
+ final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ if (experimentManager == null) {
+ ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());
+ return;
+ }
+
+ e.add(new PriorityAction(PriorityAction.HIGH+20) {
+ @Override
+ public void run() {
+ SysdynExperimentActivator.scheduleActivation(Simantics.getSession(), project, experimentManager, experiment);
+ }
+ });
+ e.consume();
+ }
+
+ }
+
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.AssignIC;
+
+public class AssignICAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource experiment = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ AssignIC.handleStatic(experiment);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions;
+
+import java.util.Collection;
+import java.util.HashSet;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.modeling.ui.actions.AssignSymbolGroupsHandler;
+
+public class AssignSymbolGroupsAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource symbol = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ Collection<Resource> symbols = new HashSet<>();
+ symbols.add(symbol);
+ AssignSymbolGroupsHandler.handleStatic(symbols);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions;
+
+import java.util.Collection;
+
+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.db.layer0.adapter.ActionFactory;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.editor.OpenDiagramFromConfigurationAdapter;
+
+public class OpenDiagramEditorFromModelAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph g) throws DatabaseException {
+ if(g.isInstanceOf(model, SysdynResource.getInstance(g).SysdynModel)) {
+ openConfigurationDiagramFromModelResourceHelper(g, model);
+ }
+ }
+ });
+ }
+ };
+ }
+
+ public static void openConfigurationDiagramFromModelResourceHelper(ReadGraph g, Resource model) throws DatabaseException {
+ if(g.isInstanceOf(model, SysdynResource.getInstance(g).SysdynModel)) {
+ Layer0 L0 = Layer0.getInstance(g);
+ Collection<Resource> children = g.getObjects(model, L0.ConsistsOf);
+ Resource modelConfiguration = null;
+
+ //Find configuration resource
+ for(Resource child : children) {
+ if(g.isInstanceOf(child, SysdynResource.getInstance(g).Configuration)) {
+ modelConfiguration = child;
+ break;
+ }
+ }
+
+ if(modelConfiguration != null) {
+ OpenDiagramFromConfigurationAdapter.openEditorHandler(g, modelConfiguration);
+ }
+ }
+ }
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions;
+
+import org.eclipse.ui.PlatformUI;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.ui.DoubleClickEvent;
+import org.simantics.ui.IDoubleClickAction;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+public class OpenDiagramEditorFromModelDoubleClickAction implements IDoubleClickAction {
+
+ @Override
+ public void doubleClickEvent(DoubleClickEvent e) throws DatabaseException {
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+
+ Resource model = ResourceAdaptionUtils.toSingleResource(e.getResource());
+ if (model == null)
+ return;
+
+ ReadGraph g = e.getGraph();
+ if(g.isInstanceOf(model, SysdynResource.getInstance(g).SysdynModel)) {
+ OpenDiagramEditorFromModelAction.openConfigurationDiagramFromModelResourceHelper(g, model);
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ }
+}
\ No newline at end of file
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.ToggleResultActivation;
+
+public class ShowInChartsAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource resource = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ Resource[] resources = new Resource[]{resource};
+ ToggleResultActivation.handleStatic(resources);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.drop;\r
-\r
-import java.util.Iterator;\r
-\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.common.request.SingleObjectWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.DropActionFactory;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Action for droppin variables to charts\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ChartDropAction implements DropActionFactory {\r
-\r
- @Override\r
- public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {\r
-\r
- final Resource targetChart = AdaptionUtils.adaptToSingle(target, Resource.class);\r
- if(targetChart == null || source == null || !(source instanceof IStructuredSelection))\r
- return null;\r
- \r
- final IStructuredSelection selection = (IStructuredSelection) source;\r
-\r
- return new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- JFreeChartResource JFREE = JFreeChartResource.getInstance(graph);\r
-\r
- Iterator<?> iterator = selection.iterator();\r
- \r
- // Run through all selections and add all IndependentVariables and Inputs to the target chart\r
- while(iterator.hasNext()) {\r
-\r
- Variable variable = AdaptionUtils.adaptToSingle(iterator.next(), Variable.class);\r
- if(variable == null)\r
- continue;\r
-\r
- Resource represents = (Resource)variable.getRepresents(graph);\r
- if(represents == null || \r
- !(graph.isInstanceOf(represents, sr.IndependentVariable) || \r
- graph.isInstanceOf(represents, sr.Input)))\r
- continue;\r
-\r
- Resource plot = graph.syncRequest(new PossibleObjectWithType(targetChart, L0.ConsistsOf, JFREE.Plot));\r
- if(plot != null) {\r
- if(graph.isInstanceOf(plot, JFREE.XYPlot)) {\r
- dropToLineChart(graph, targetChart, variable);\r
- } else if(graph.isInstanceOf(plot, JFREE.CategoryPlot)) {\r
- dropToBarChart(graph, targetChart, variable);\r
- } else if(graph.isInstanceOf(plot, JFREE.PiePlot)) {\r
- dropToPieChart(graph, targetChart, variable);\r
- }\r
- }\r
- }\r
-\r
- }\r
- });\r
- }\r
- };\r
- }\r
-\r
-\r
- /**\r
- * Drop variable to a pie chart\r
- * @param graph ReadGraph\r
- * @param pieChart Pie chart resource\r
- * @param variable Dropped variable\r
- * @throws DatabaseException\r
- */\r
- private void dropToPieChart(WriteGraph graph, Resource pieChart, Variable variable) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- Resource plot = graph.syncRequest(new SingleObjectWithType(pieChart, l0.ConsistsOf, jfree.Plot));\r
- if(plot == null)\r
- return;\r
-\r
- Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
-\r
- if(dataset == null)\r
- return;\r
-\r
- // Create the series and attach it to the dataset\r
- String rvi = Variables.getRVI(graph, variable);\r
- Resource series = ChartUtils.createSeries(graph, dataset, rvi);\r
- graph.claimLiteral(series, jfree.Series_exploded, false); \r
- }\r
-\r
- /**\r
- * Drop variable to a bar chart\r
- * @param graph ReadGraph\r
- * @param barChart Bar chart resource\r
- * @param variable Dropped variable\r
- * @throws DatabaseException\r
- */\r
- private void dropToBarChart(WriteGraph graph, Resource barChart, Variable variable) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- Resource plot = graph.syncRequest(new SingleObjectWithType(barChart, l0.ConsistsOf, jfree.Plot));\r
- if(plot == null)\r
- return;\r
-\r
- Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
-\r
- if(dataset == null)\r
- return;\r
-\r
- // Create the series and attach it to the dataset\r
- String rvi = Variables.getRVI(graph, variable);\r
- ChartUtils.createSeries(graph, dataset, rvi);\r
- }\r
-\r
- /**\r
- * Drop variable to a line chart\r
- * @param graph ReadGraph\r
- * @param lineChart Line chart resource\r
- * @param variable Dropped variable\r
- * @throws DatabaseException\r
- */\r
- private void dropToLineChart(WriteGraph graph, Resource lineChart, Variable variable) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- Resource plot = graph.syncRequest(new SingleObjectWithType(lineChart, l0.ConsistsOf, jfree.Plot));\r
- if(plot == null)\r
- return;\r
-\r
- Resource rangeAxis = null;\r
- Resource dataset = null;\r
- Resource rangeAxisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
- if(rangeAxisList == null || ListUtils.toList(graph, rangeAxisList).isEmpty()) {\r
- // No range axis -> Create a new one\r
- rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);\r
- Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
- dataset = ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);\r
- } else {\r
- rangeAxis = ListUtils.toList(graph, rangeAxisList).get(0);\r
- dataset = graph.getPossibleObject(rangeAxis, jfree.Dataset_mapToRangeAxis_Inverse);\r
- }\r
-\r
- // Create the series and attach it to the dataset\r
- String rvi = Variables.getRVI(graph, variable);\r
- ChartUtils.createSeries(graph, dataset, rvi);\r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.drop;
+
+import java.util.Iterator;
+
+import org.eclipse.jface.viewers.IStructuredSelection;
+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.PossibleObjectWithType;
+import org.simantics.db.common.request.SingleObjectWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.DropActionFactory;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Action for droppin variables to charts
+ * @author Teemu Lempinen
+ *
+ */
+public class ChartDropAction implements DropActionFactory {
+
+ @Override
+ public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {
+
+ final Resource targetChart = AdaptionUtils.adaptToSingle(target, Resource.class);
+ if(targetChart == null || source == null || !(source instanceof IStructuredSelection))
+ return null;
+
+ final IStructuredSelection selection = (IStructuredSelection) source;
+
+ return new Runnable() {
+
+ @Override
+ public void run() {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 L0 = Layer0.getInstance(graph);
+ JFreeChartResource JFREE = JFreeChartResource.getInstance(graph);
+
+ Iterator<?> iterator = selection.iterator();
+
+ // Run through all selections and add all IndependentVariables and Inputs to the target chart
+ while(iterator.hasNext()) {
+
+ Variable variable = AdaptionUtils.adaptToSingle(iterator.next(), Variable.class);
+ if(variable == null)
+ continue;
+
+ Resource represents = (Resource)variable.getRepresents(graph);
+ if(represents == null ||
+ !(graph.isInstanceOf(represents, sr.IndependentVariable) ||
+ graph.isInstanceOf(represents, sr.Input)))
+ continue;
+
+ Resource plot = graph.syncRequest(new PossibleObjectWithType(targetChart, L0.ConsistsOf, JFREE.Plot));
+ if(plot != null) {
+ if(graph.isInstanceOf(plot, JFREE.XYPlot)) {
+ dropToLineChart(graph, targetChart, variable);
+ } else if(graph.isInstanceOf(plot, JFREE.CategoryPlot)) {
+ dropToBarChart(graph, targetChart, variable);
+ } else if(graph.isInstanceOf(plot, JFREE.PiePlot)) {
+ dropToPieChart(graph, targetChart, variable);
+ }
+ }
+ }
+
+ }
+ });
+ }
+ };
+ }
+
+
+ /**
+ * Drop variable to a pie chart
+ * @param graph ReadGraph
+ * @param pieChart Pie chart resource
+ * @param variable Dropped variable
+ * @throws DatabaseException
+ */
+ private void dropToPieChart(WriteGraph graph, Resource pieChart, Variable variable) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ Resource plot = graph.syncRequest(new SingleObjectWithType(pieChart, l0.ConsistsOf, jfree.Plot));
+ if(plot == null)
+ return;
+
+ Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));
+
+ if(dataset == null)
+ return;
+
+ // Create the series and attach it to the dataset
+ String rvi = Variables.getRVI(graph, variable);
+ Resource series = ChartUtils.createSeries(graph, dataset, rvi);
+ graph.claimLiteral(series, jfree.Series_exploded, false);
+ }
+
+ /**
+ * Drop variable to a bar chart
+ * @param graph ReadGraph
+ * @param barChart Bar chart resource
+ * @param variable Dropped variable
+ * @throws DatabaseException
+ */
+ private void dropToBarChart(WriteGraph graph, Resource barChart, Variable variable) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ Resource plot = graph.syncRequest(new SingleObjectWithType(barChart, l0.ConsistsOf, jfree.Plot));
+ if(plot == null)
+ return;
+
+ Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));
+
+ if(dataset == null)
+ return;
+
+ // Create the series and attach it to the dataset
+ String rvi = Variables.getRVI(graph, variable);
+ ChartUtils.createSeries(graph, dataset, rvi);
+ }
+
+ /**
+ * Drop variable to a line chart
+ * @param graph ReadGraph
+ * @param lineChart Line chart resource
+ * @param variable Dropped variable
+ * @throws DatabaseException
+ */
+ private void dropToLineChart(WriteGraph graph, Resource lineChart, Variable variable) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ Resource plot = graph.syncRequest(new SingleObjectWithType(lineChart, l0.ConsistsOf, jfree.Plot));
+ if(plot == null)
+ return;
+
+ Resource rangeAxis = null;
+ Resource dataset = null;
+ Resource rangeAxisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);
+ if(rangeAxisList == null || ListUtils.toList(graph, rangeAxisList).isEmpty()) {
+ // No range axis -> Create a new one
+ rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);
+ Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);
+ dataset = ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);
+ } else {
+ rangeAxis = ListUtils.toList(graph, rangeAxisList).get(0);
+ dataset = graph.getPossibleObject(rangeAxis, jfree.Dataset_mapToRangeAxis_Inverse);
+ }
+
+ // Create the series and attach it to the dataset
+ String rvi = Variables.getRVI(graph, variable);
+ ChartUtils.createSeries(graph, dataset, rvi);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.drop;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.DropActionFactory;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Action for moving functions and function libraries in model browser \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class FunctionDropAction implements DropActionFactory {\r
-\r
- @Override\r
- public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {\r
- Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);\r
- Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);\r
-\r
- if(t == null || s == null)\r
- return null;\r
-\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 L0 = Layer0.getInstance(g);\r
-\r
- // If target is a function, find functions parent to be the drop target\r
- if(g.isInstanceOf(t, sr.SysdynModelicaFunction))\r
- t = g.getSingleObject(t, L0.PartOf);\r
-\r
- final Resource library = t;\r
- final Resource tobemoved = s;\r
-\r
- // Libraries and model accept drops\r
- if(!(g.isInstanceOf(library, sr.SysdynModelicaFunctionLibrary) || \r
- g.isInstanceOf(library, sr.SysdynModel) ||\r
- g.isInstanceOf(library, sr.SharedFunctionOntology)))\r
- return null;\r
-\r
- // Functions and function libraries can be dropped\r
- if(!(g.isInstanceOf(tobemoved, sr.SysdynModelicaFunction) || \r
- g.isInstanceOf(tobemoved, sr.SysdynModelicaFunctionLibrary)))\r
- return null;\r
-\r
-\r
- return new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- Resource oldLib = graph.getSingleObject(tobemoved, L0.PartOf);\r
-\r
- // Remove dragged entity from its parent and add it to the new parent\r
- graph.claim(tobemoved, L0.PartOf, library);\r
- graph.deny(tobemoved, L0.PartOf, oldLib);\r
- }\r
-\r
- });\r
- }\r
- };\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.drop;
+
+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.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.DropActionFactory;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Action for moving functions and function libraries in model browser
+ * @author Teemu Lempinen
+ *
+ */
+public class FunctionDropAction implements DropActionFactory {
+
+ @Override
+ public Runnable create(ReadGraph g, Object target, Object source, int operation) throws DatabaseException {
+ Resource t = AdaptionUtils.adaptToSingle(target, Resource.class);
+ Resource s = AdaptionUtils.adaptToSingle(source, Resource.class);
+
+ if(t == null || s == null)
+ return null;
+
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 L0 = Layer0.getInstance(g);
+
+ // If target is a function, find functions parent to be the drop target
+ if(g.isInstanceOf(t, sr.SysdynModelicaFunction))
+ t = g.getSingleObject(t, L0.PartOf);
+
+ final Resource library = t;
+ final Resource tobemoved = s;
+
+ // Libraries and model accept drops
+ if(!(g.isInstanceOf(library, sr.SysdynModelicaFunctionLibrary) ||
+ g.isInstanceOf(library, sr.SysdynModel) ||
+ g.isInstanceOf(library, sr.SharedFunctionOntology)))
+ return null;
+
+ // Functions and function libraries can be dropped
+ if(!(g.isInstanceOf(tobemoved, sr.SysdynModelicaFunction) ||
+ g.isInstanceOf(tobemoved, sr.SysdynModelicaFunctionLibrary)))
+ return null;
+
+
+ return new Runnable() {
+
+ @Override
+ public void run() {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 L0 = Layer0.getInstance(graph);
+ Resource oldLib = graph.getSingleObject(tobemoved, L0.PartOf);
+
+ // Remove dragged entity from its parent and add it to the new parent
+ graph.claim(tobemoved, L0.PartOf, library);
+ graph.deny(tobemoved, L0.PartOf, oldLib);
+ }
+
+ });
+ }
+ };
+ }
+
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.exportActions;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.exports.ExportFunctionLibrary;
+
+public class ExportFunctionLibraryAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource functionLibrary = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ExportFunctionLibrary.handleStatic(functionLibrary);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.exportActions;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.exports.ExportModelHandler;
+
+public class ExportModelAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ExportModelHandler.handleStatic(model);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.exportActions;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.exports.ExportModuleHandler;
+
+public class ExportModuleAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ExportModuleHandler.handleStatic(model);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.importActions;
+
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.imports.ImportFunctionLibrary;
+
+public class ImportFunctionLibraryAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource functionLibrary = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ImportFunctionLibrary.handleStatic(functionLibrary);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.importActions;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.imports.ImportModuleHandler;
+
+public class ImportModuleAction implements ActionFactory {
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ImportModuleHandler.handleStatic(model);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import java.util.Collections;\r
-import java.util.UUID;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new bar chart to a model\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewBarChartAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource model = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
-\r
- // Chart\r
- Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,\r
- l0.HasName, "BarChart" + UUID.randomUUID().toString(),\r
- l0.HasLabel, NameUtils.findFreshLabel(graph, "Bar Chart", model),\r
- l0.PartOf, model,\r
- jfree.Chart_visibleBorder, true,\r
- jfree.Chart_borderWidth, 3,\r
- jfree.Chart_visibleLegend, false\r
- );\r
- \r
- // Border color\r
- graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
-\r
- // Title\r
- GraphUtils.create2(graph, jfree.TextTitle,\r
- l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Bar Chart Title",\r
- jfree.Title_position, jfree.Top,\r
- l0.PartOf, jfreechart);\r
- \r
- // X-axis\r
- Resource domainAxis = GraphUtils.create2(graph, jfree.CategoryAxis,\r
- l0.HasName, "CategoryAxis" + UUID.randomUUID().toString());\r
- \r
- // Y-axis\r
- Resource rangeAxis = GraphUtils.create2(graph, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString());\r
-\r
- // Renderer\r
- Resource renderer = GraphUtils.create2(graph, jfree.BarRenderer);\r
- \r
- // Dataset \r
- Resource dataset = GraphUtils.create2(graph, jfree.CategoryDataset,\r
- l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
- jfree.Dataset_mapToDomainAxis, domainAxis,\r
- jfree.Dataset_mapToRangeAxis, rangeAxis,\r
- jfree.Dataset_seriesList, ListUtils.create(graph, Collections.<Resource>emptyList()),\r
- jfree.Dataset_renderer, renderer);\r
-\r
- // Plot\r
- GraphUtils.create2(graph, jfree.CategoryPlot,\r
- l0.HasName, "Category plot" + UUID.randomUUID().toString(),\r
- l0.PartOf, jfreechart,\r
- jfree.Plot_domainAxis, domainAxis,\r
- jfree.Plot_rangeAxis, rangeAxis,\r
- jfree.Plot_rangeAxisList, ListUtils.create(graph, Collections.singletonList(rangeAxis)),\r
- l0.ConsistsOf, dataset,\r
- l0.ConsistsOf, domainAxis,\r
- l0.ConsistsOf, rangeAxis);\r
- }\r
-\r
- });\r
- }\r
- };\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import java.util.Collections;
+import java.util.UUID;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.JFreeChartResource;
+
+/**
+ * Creates a new bar chart to a model
+ * @author Teemu Lempinen
+ *
+ */
+public class NewBarChartAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ G2DResource g2d = G2DResource.getInstance(graph);
+
+ // Chart
+ Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,
+ l0.HasName, "BarChart" + UUID.randomUUID().toString(),
+ l0.HasLabel, NameUtils.findFreshLabel(graph, "Bar Chart", model),
+ l0.PartOf, model,
+ jfree.Chart_visibleBorder, true,
+ jfree.Chart_borderWidth, 3,
+ jfree.Chart_visibleLegend, false
+ );
+
+ // Border color
+ graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});
+
+ // Title
+ GraphUtils.create2(graph, jfree.TextTitle,
+ l0.HasName, "TextTitle" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Bar Chart Title",
+ jfree.Title_position, jfree.Top,
+ l0.PartOf, jfreechart);
+
+ // X-axis
+ Resource domainAxis = GraphUtils.create2(graph, jfree.CategoryAxis,
+ l0.HasName, "CategoryAxis" + UUID.randomUUID().toString());
+
+ // Y-axis
+ Resource rangeAxis = GraphUtils.create2(graph, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString());
+
+ // Renderer
+ Resource renderer = GraphUtils.create2(graph, jfree.BarRenderer);
+
+ // Dataset
+ Resource dataset = GraphUtils.create2(graph, jfree.CategoryDataset,
+ l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),
+ jfree.Dataset_mapToDomainAxis, domainAxis,
+ jfree.Dataset_mapToRangeAxis, rangeAxis,
+ jfree.Dataset_seriesList, ListUtils.create(graph, Collections.<Resource>emptyList()),
+ jfree.Dataset_renderer, renderer);
+
+ // Plot
+ GraphUtils.create2(graph, jfree.CategoryPlot,
+ l0.HasName, "Category plot" + UUID.randomUUID().toString(),
+ l0.PartOf, jfreechart,
+ jfree.Plot_domainAxis, domainAxis,
+ jfree.Plot_rangeAxis, rangeAxis,
+ jfree.Plot_rangeAxisList, ListUtils.create(graph, Collections.singletonList(rangeAxis)),
+ l0.ConsistsOf, dataset,
+ l0.ConsistsOf, domainAxis,
+ l0.ConsistsOf, rangeAxis);
+ }
+
+ });
+ }
+ };
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import java.util.Collections;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new enumeration to a model or module\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewEnumerationAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource resource = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
-\r
- // Find the configuration from...\r
- Resource configuration = null;\r
- if(g.isInstanceOf(resource, sr.Configuration)) {\r
- configuration = resource;\r
- } else if(g.isInheritedFrom(resource, sr.ModuleSymbol)) {\r
- // Module symbol\r
- Resource module = g.getPossibleObject(resource,ModelingResources.getInstance(g).SymbolToComponentType);\r
- configuration = g.getPossibleObject(module, StructuralResource2.getInstance(g).IsDefinedBy);\r
- } else {\r
- // Module instance\r
- Resource instanceOf = g.getSingleObject(resource, l0.InstanceOf);\r
- if(g.isInheritedFrom(instanceOf, sr.Module)) {\r
- configuration = g.getPossibleObject(instanceOf, StructuralResource2.getInstance(g).IsDefinedBy);\r
- } else {\r
- return;\r
- }\r
- }\r
-\r
- // Find unique name\r
- String name = NameUtils.findFreshName(g, "Enum", configuration, l0.ConsistsOf, "%s%d");\r
- \r
- // Create enumeration\r
- GraphUtils.create2(g, \r
- sr.Enumeration,\r
- l0.HasName, name,\r
- sr.Enumeration_enumerationIndexList, ListUtils.create(g, Collections.<Resource>emptyList()),\r
- l0.PartOf, configuration);\r
- }\r
- });\r
- }\r
- };\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import java.util.Collections;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Creates a new enumeration to a model or module
+ * @author Teemu Lempinen
+ *
+ */
+public class NewEnumerationAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource resource = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+
+ // Find the configuration from...
+ Resource configuration = null;
+ if(g.isInstanceOf(resource, sr.Configuration)) {
+ configuration = resource;
+ } else if(g.isInheritedFrom(resource, sr.ModuleSymbol)) {
+ // Module symbol
+ Resource module = g.getPossibleObject(resource,ModelingResources.getInstance(g).SymbolToComponentType);
+ configuration = g.getPossibleObject(module, StructuralResource2.getInstance(g).IsDefinedBy);
+ } else {
+ // Module instance
+ Resource instanceOf = g.getSingleObject(resource, l0.InstanceOf);
+ if(g.isInheritedFrom(instanceOf, sr.Module)) {
+ configuration = g.getPossibleObject(instanceOf, StructuralResource2.getInstance(g).IsDefinedBy);
+ } else {
+ return;
+ }
+ }
+
+ // Find unique name
+ String name = NameUtils.findFreshName(g, "Enum", configuration, l0.ConsistsOf, "%s%d");
+
+ // Create enumeration
+ GraphUtils.create2(g,
+ sr.Enumeration,
+ l0.HasName, name,
+ sr.Enumeration_enumerationIndexList, ListUtils.create(g, Collections.<Resource>emptyList()),
+ l0.PartOf, configuration);
+ }
+ });
+ }
+ };
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new basic experiment\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewExperimentAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource model = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- String name = NameUtils.findFreshName(graph, getNameSuggestion(), model, l0.ConsistsOf, "%s%d");\r
-\r
- Resource experiment = GraphUtils.create2(graph, getExperimentType(graph),\r
- l0.HasName, name,\r
- l0.HasLabel, name,\r
- l0.PartOf, model);\r
- \r
- configureExperiment(graph, experiment);\r
- }\r
- });\r
- }\r
- };\r
- }\r
-\r
- /**\r
- * Override to do experiment-specific alterations\r
- */\r
- protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
- \r
- }\r
- \r
- /**\r
- * Get the type of this experiment.\r
- * \r
- * @param g ReadGraph\r
- * @return The type resource of this experiment\r
- */\r
- protected Resource getExperimentType(ReadGraph g) {\r
- return SysdynResource.getInstance(g).BasicExperiment;\r
- }\r
- \r
- /**\r
- * Returns the suggested name for this experiment.\r
- * If the name has already been taken, appropriate prefix needs to be added. \r
- * \r
- * @return Suggested name for this experiment. \r
- */\r
- protected String getNameSuggestion() {\r
- return "Experiment";\r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+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.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Creates a new basic experiment
+ * @author Teemu Lempinen
+ *
+ */
+public class NewExperimentAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ String name = NameUtils.findFreshName(graph, getNameSuggestion(), model, l0.ConsistsOf, "%s%d");
+
+ Resource experiment = GraphUtils.create2(graph, getExperimentType(graph),
+ l0.HasName, name,
+ l0.HasLabel, name,
+ l0.PartOf, model);
+
+ configureExperiment(graph, experiment);
+ }
+ });
+ }
+ };
+ }
+
+ /**
+ * Override to do experiment-specific alterations
+ */
+ protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+
+ }
+
+ /**
+ * Get the type of this experiment.
+ *
+ * @param g ReadGraph
+ * @return The type resource of this experiment
+ */
+ protected Resource getExperimentType(ReadGraph g) {
+ return SysdynResource.getInstance(g).BasicExperiment;
+ }
+
+ /**
+ * Returns the suggested name for this experiment.
+ * If the name has already been taken, appropriate prefix needs to be added.
+ *
+ * @return Suggested name for this experiment.
+ */
+ protected String getNameSuggestion() {
+ return "Experiment";
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new modelica function to a model, function library or shared function library.\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewFunctionAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource resource = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(g);\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
-\r
- Resource library = null;\r
- if(g.isInstanceOf(resource, sr.SysdynModel) || g.isInstanceOf(resource, l0.Library))\r
- library = resource;\r
- else if (g.isInstanceOf(resource, sr.SysdynModelicaFunction))\r
- library = g.getPossibleObject(resource, l0.PartOf);\r
-\r
- if(library == null)\r
- return;\r
-\r
-\r
- String name = NameUtils.findFreshName(g, "Function", library, l0.ConsistsOf, "%s%d");\r
-\r
- GraphUtils.create2(g, sr.SysdynModelicaFunction,\r
- l0.HasName, name,\r
- l0.HasDescription, "",\r
- sr.SysdynModelicaFunction_modelicaFunctionCode, "",\r
- l0.PartOf, library);\r
- }\r
- });\r
-\r
- }\r
- };\r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Creates a new modelica function to a model, function library or shared function library.
+ * @author Teemu Lempinen
+ *
+ */
+public class NewFunctionAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource resource = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(g);
+ SysdynResource sr = SysdynResource.getInstance(g);
+
+ Resource library = null;
+ if(g.isInstanceOf(resource, sr.SysdynModel) || g.isInstanceOf(resource, l0.Library))
+ library = resource;
+ else if (g.isInstanceOf(resource, sr.SysdynModelicaFunction))
+ library = g.getPossibleObject(resource, l0.PartOf);
+
+ if(library == null)
+ return;
+
+
+ String name = NameUtils.findFreshName(g, "Function", library, l0.ConsistsOf, "%s%d");
+
+ GraphUtils.create2(g, sr.SysdynModelicaFunction,
+ l0.HasName, name,
+ l0.HasDescription, "",
+ sr.SysdynModelicaFunction_modelicaFunctionCode, "",
+ l0.PartOf, library);
+ }
+ });
+
+ }
+ };
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ResourceNotFoundException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new function library\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewFunctionLibraryAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource resource = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
- createLibrary(resource, false);\r
- }\r
- };\r
- }\r
- \r
- /**\r
- * Create a new Library to the selected root or to SharedOntologies\r
- * \r
- * @param libraryLocation Resource of the model or other \r
- * library where the new library will be added.\r
- * @param shared is the library a shared library\r
- */\r
- protected static void createLibrary(final Resource libraryLocation, final boolean shared) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(g);\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
-\r
- // Libraries can be created to model, function library and shared function library\r
- if(!(g.isInstanceOf(libraryLocation, sr.SysdynModel) ||\r
- g.isInstanceOf(libraryLocation, sr.SysdynModelicaFunctionLibrary) ||\r
- g.isInstanceOf(libraryLocation, sr.SharedFunctionOntology)))\r
- return;\r
-\r
- Resource root = libraryLocation;\r
-\r
- String name = "FunctionLibrary";\r
- Resource libraryType = sr.SysdynModelicaFunctionLibrary;\r
- \r
- if(shared) {\r
- \r
- try {\r
- root = g.getResource("http://SharedOntologies");\r
- } catch (ResourceNotFoundException e) {\r
- root = g.getResource("http:/");\r
- root = GraphUtils.create2(g, l0.Library, \r
- l0.HasName, "SharedOntologies",\r
- l0.PartOf, root);\r
- }\r
- \r
- name = "Shared" + name;\r
- libraryType = sr.SharedFunctionOntology;\r
- }\r
-\r
- name = NameUtils.findFreshName(g, name, root, l0.ConsistsOf, "%s%d");\r
- \r
- Resource functionLibrary = GraphUtils.create2(g, libraryType,\r
- l0.HasName, name,\r
- l0.HasDescription, "",\r
- l0.PartOf, root);\r
- \r
- if(shared)\r
- g.claim(libraryLocation, l0.IsLinkedTo, functionLibrary);\r
- }\r
- });\r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.ResourceNotFoundException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Creates a new function library
+ * @author Teemu Lempinen
+ *
+ */
+public class NewFunctionLibraryAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource resource = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ createLibrary(resource, false);
+ }
+ };
+ }
+
+ /**
+ * Create a new Library to the selected root or to SharedOntologies
+ *
+ * @param libraryLocation Resource of the model or other
+ * library where the new library will be added.
+ * @param shared is the library a shared library
+ */
+ protected static void createLibrary(final Resource libraryLocation, final boolean shared) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(g);
+ SysdynResource sr = SysdynResource.getInstance(g);
+
+ // Libraries can be created to model, function library and shared function library
+ if(!(g.isInstanceOf(libraryLocation, sr.SysdynModel) ||
+ g.isInstanceOf(libraryLocation, sr.SysdynModelicaFunctionLibrary) ||
+ g.isInstanceOf(libraryLocation, sr.SharedFunctionOntology)))
+ return;
+
+ Resource root = libraryLocation;
+
+ String name = "FunctionLibrary";
+ Resource libraryType = sr.SysdynModelicaFunctionLibrary;
+
+ if(shared) {
+
+ try {
+ root = g.getResource("http://SharedOntologies");
+ } catch (ResourceNotFoundException e) {
+ root = g.getResource("http:/");
+ root = GraphUtils.create2(g, l0.Library,
+ l0.HasName, "SharedOntologies",
+ l0.PartOf, root);
+ }
+
+ name = "Shared" + name;
+ libraryType = sr.SharedFunctionOntology;
+ }
+
+ name = NameUtils.findFreshName(g, name, root, l0.ConsistsOf, "%s%d");
+
+ Resource functionLibrary = GraphUtils.create2(g, libraryType,
+ l0.HasName, name,
+ l0.HasDescription, "",
+ l0.PartOf, root);
+
+ if(shared)
+ g.claim(libraryLocation, l0.IsLinkedTo, functionLibrary);
+ }
+ });
+ }
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.newActions;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.ui.handlers.newComponents.NewGameExperimentNodeHandler;
+
+public class NewGameExperimentAction extends NewExperimentAction {
+
+ private NewGameExperimentNodeHandler handler = null;
+
+ public NewGameExperimentAction(){
+ this.handler = new NewGameExperimentNodeHandler();
+ }
+
+ protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+ this.handler.configureExperiment(graph, experiment);
+ }
+
+ protected Resource getExperimentType(ReadGraph g) {
+ return this.handler.getExperimentType(g);
+ }
+
+ protected String getNameSuggestion() {
+ return this.handler.getNameSuggestion();
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import java.util.UUID;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Create a new history data\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewHistoryDataAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource experiment = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- if(!graph.isInstanceOf(experiment, sr.Experiment))\r
- return; // Not called from an experiment\r
-\r
- Resource model = graph.getPossibleObject(experiment, l0.PartOf);\r
- // Create the history dataset\r
- GraphUtils.create2(graph, \r
- sr.HistoryDataset,\r
- l0.HasName, "HistoryDataset" + UUID.randomUUID().toString(),\r
- l0.HasLabel, NameUtils.findFreshLabel(graph, "History Dataset", experiment),\r
- sr.Experiment_result_Inverse, experiment, \r
- sr.HistoryDataset_columns, Boolean.TRUE,\r
- l0.PartOf, model);\r
- }\r
- });\r
- }\r
- };\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import java.util.UUID;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Create a new history data
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewHistoryDataAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource experiment = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ if(!graph.isInstanceOf(experiment, sr.Experiment))
+ return; // Not called from an experiment
+
+ Resource model = graph.getPossibleObject(experiment, l0.PartOf);
+ // Create the history dataset
+ GraphUtils.create2(graph,
+ sr.HistoryDataset,
+ l0.HasName, "HistoryDataset" + UUID.randomUUID().toString(),
+ l0.HasLabel, NameUtils.findFreshLabel(graph, "History Dataset", experiment),
+ sr.Experiment_result_Inverse, experiment,
+ sr.HistoryDataset_columns, Boolean.TRUE,
+ l0.PartOf, model);
+ }
+ });
+ }
+ };
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.UUID;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new line chart\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewLineChartAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource model = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
-\r
- // Chart\r
- Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,\r
- l0.HasName, "Chart" + UUID.randomUUID().toString(),\r
- l0.HasLabel, NameUtils.findFreshLabel(graph, "Chart", model),\r
- l0.PartOf, model,\r
- jfree.Chart_visibleBorder, true,\r
- jfree.Chart_borderWidth, 3);\r
- graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
-\r
- // Title\r
- GraphUtils.create2(graph, jfree.TextTitle,\r
- l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Chart Title",\r
- jfree.Title_position, jfree.Top,\r
- l0.PartOf, jfreechart);\r
-\r
- // X-axis\r
- Resource domainAxis = GraphUtils.create2(graph, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString());\r
- \r
- // Y-axis\r
- Resource rangeAxis = GraphUtils.create2(graph, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Y-axis");\r
- \r
- // Renderer\r
- Resource renderer = GraphUtils.create2(graph, jfree.XYLineRenderer);\r
-\r
- // Dataset\r
- Resource dataset = GraphUtils.create2(graph, jfree.XYDataset,\r
- l0.HasName, "XYDataset" + UUID.randomUUID().toString(),\r
- jfree.Dataset_mapToDomainAxis, domainAxis,\r
- jfree.Dataset_mapToRangeAxis, rangeAxis,\r
- jfree.Dataset_seriesList, ListUtils.create(graph, new ArrayList<Resource>()),\r
- jfree.Dataset_renderer, renderer);\r
-\r
- // Plot\r
- GraphUtils.create2(graph, jfree.XYPlot,\r
- l0.HasName, "XYPlot" + UUID.randomUUID().toString(),\r
- l0.PartOf, jfreechart,\r
- jfree.Plot_domainAxis, domainAxis,\r
- jfree.Plot_rangeAxis, rangeAxis,\r
- jfree.Plot_rangeAxisList, ListUtils.create(graph, Collections.singletonList(rangeAxis)),\r
- l0.ConsistsOf, dataset,\r
- l0.ConsistsOf, domainAxis,\r
- l0.ConsistsOf, rangeAxis);\r
- }\r
-\r
- });\r
- }\r
- };\r
- }\r
-\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.UUID;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.JFreeChartResource;
+
+/**
+ * Creates a new line chart
+ * @author Teemu Lempinen
+ *
+ */
+public class NewLineChartAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ G2DResource g2d = G2DResource.getInstance(graph);
+
+ // Chart
+ Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,
+ l0.HasName, "Chart" + UUID.randomUUID().toString(),
+ l0.HasLabel, NameUtils.findFreshLabel(graph, "Chart", model),
+ l0.PartOf, model,
+ jfree.Chart_visibleBorder, true,
+ jfree.Chart_borderWidth, 3);
+ graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});
+
+ // Title
+ GraphUtils.create2(graph, jfree.TextTitle,
+ l0.HasName, "TextTitle" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Chart Title",
+ jfree.Title_position, jfree.Top,
+ l0.PartOf, jfreechart);
+
+ // X-axis
+ Resource domainAxis = GraphUtils.create2(graph, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString());
+
+ // Y-axis
+ Resource rangeAxis = GraphUtils.create2(graph, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Y-axis");
+
+ // Renderer
+ Resource renderer = GraphUtils.create2(graph, jfree.XYLineRenderer);
+
+ // Dataset
+ Resource dataset = GraphUtils.create2(graph, jfree.XYDataset,
+ l0.HasName, "XYDataset" + UUID.randomUUID().toString(),
+ jfree.Dataset_mapToDomainAxis, domainAxis,
+ jfree.Dataset_mapToRangeAxis, rangeAxis,
+ jfree.Dataset_seriesList, ListUtils.create(graph, new ArrayList<Resource>()),
+ jfree.Dataset_renderer, renderer);
+
+ // Plot
+ GraphUtils.create2(graph, jfree.XYPlot,
+ l0.HasName, "XYPlot" + UUID.randomUUID().toString(),
+ l0.PartOf, jfreechart,
+ jfree.Plot_domainAxis, domainAxis,
+ jfree.Plot_rangeAxis, rangeAxis,
+ jfree.Plot_rangeAxisList, ListUtils.create(graph, Collections.singletonList(rangeAxis)),
+ l0.ConsistsOf, dataset,
+ l0.ConsistsOf, domainAxis,
+ l0.ConsistsOf, rangeAxis);
+ }
+
+ });
+ }
+ };
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.common.utils.OrderedSetUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.db.layer0.adapter.Template;\r
-import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-\r
-/**\r
- * Creates a new module type\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewModuleTypeAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource model = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
- Layer0X L0X = Layer0X.getInstance(g);\r
- ModelingResources mr = ModelingResources.getInstance(g);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
-\r
- String name = NameUtils.findFreshName(g, "ModuleType", model, l0.ConsistsOf, "%s%d");\r
-\r
- Resource moduleType = g.newResource();\r
- g.claimLiteral(moduleType, l0.HasName, name);\r
- g.claim(moduleType, l0.Inherits, sr.Module);\r
- g.claim(moduleType, l0.PartOf, model);\r
-\r
-\r
-\r
- Resource configuration = GraphUtils.create2(g, \r
- sr.Configuration,\r
- l0.HasName, name + "Configuration",\r
- l0.PartOf, moduleType);\r
-\r
- g.claim(moduleType, sr2.IsDefinedBy , configuration);\r
-\r
- Resource diagram = g.newResource();\r
- g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,\r
- ArrayMap\r
- .keys("", "diagram", "name")\r
- .values(configuration, diagram, "Diagrammi")\r
- );\r
-\r
-\r
- // Remove default mapping and add sysdyn mapping\r
- for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {\r
- if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {\r
- g.deny(diagram, L0X.HasTrigger, trigger);\r
- }\r
- }\r
-\r
- Resource mapping = g.newResource();\r
- g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);\r
- g.claim(diagram, L0X.HasTrigger, mapping);\r
-\r
- Resource moduleSymbol = g.newResource();\r
- g.claimLiteral(moduleSymbol, l0.HasName, name + " Symbol");\r
- g.claimLiteral(moduleSymbol, l0.HasLabel, name + " Symbol");\r
- g.claim(moduleSymbol, l0.Inherits, sr.ModuleSymbol);\r
- g.claim(moduleSymbol, mr.SymbolToComponentType, moduleType);\r
- g.claim(moduleSymbol, l0.PartOf, moduleType);\r
-\r
- Resource terminal = g.newResource();\r
- g.claim(terminal, l0.InstanceOf, sr.SysdynTerminal);\r
- Resource relation = createTerminalRelation(g, moduleSymbol, sr.IsHeadOfTerminal, sr.Variable_isHeadOf);\r
- DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal, relation); \r
-\r
- Resource terminal2 = g.newResource();\r
- g.claim(terminal2, l0.InstanceOf, sr.SysdynTerminal);\r
- relation = createTerminalRelation(g, moduleSymbol, sr.IsTailOfTerminal, sr.Variable_isTailOf);\r
- DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal2, relation);\r
-\r
- g.claim(moduleSymbol, sr2.IsDefinedBy, OrderedSetUtils.create(g, sr2.Composite, terminal, terminal2));\r
-\r
-\r
-\r
- }\r
- });\r
- }\r
- };\r
- }\r
-\r
- public static Resource createTerminalRelation(WriteGraph graph, Resource symbol, Resource connectionRelation, Resource configurationRelation) throws DatabaseException {\r
- StructuralResource2 STR = StructuralResource2.getInstance(graph);\r
- ModelingResources MOD = ModelingResources.getInstance(graph);\r
- Layer0 L0 = Layer0.getInstance(graph);\r
-\r
-\r
- Resource terminalRelation = null;\r
- terminalRelation = GraphUtils.create(graph,\r
- MOD.DiagramConnectionRelationToConnectionRelation, configurationRelation,\r
- L0.PartOf, symbol,\r
- L0.HasName, NameUtils.getSafeName(graph, connectionRelation)\r
- );\r
-\r
- graph.claim(terminalRelation, L0.SubrelationOf, null, connectionRelation);\r
- Resource inverse = GraphUtils.create(graph,\r
- L0.PartOf, terminalRelation, \r
- L0.HasName, "Inverse");\r
-\r
- graph.claim(inverse, L0.SubrelationOf, null, STR.Connects);\r
- graph.claim(terminalRelation, L0.InverseOf, inverse);\r
-\r
- return terminalRelation;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.common.utils.OrderedSetUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.db.layer0.adapter.Template;
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.operation.Layer0X;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.datastructures.ArrayMap;
+
+/**
+ * Creates a new module type
+ * @author Teemu Lempinen
+ *
+ */
+public class NewModuleTypeAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+ Layer0X L0X = Layer0X.getInstance(g);
+ ModelingResources mr = ModelingResources.getInstance(g);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(g);
+
+ String name = NameUtils.findFreshName(g, "ModuleType", model, l0.ConsistsOf, "%s%d");
+
+ Resource moduleType = g.newResource();
+ g.claimLiteral(moduleType, l0.HasName, name);
+ g.claim(moduleType, l0.Inherits, sr.Module);
+ g.claim(moduleType, l0.PartOf, model);
+
+
+
+ Resource configuration = GraphUtils.create2(g,
+ sr.Configuration,
+ l0.HasName, name + "Configuration",
+ l0.PartOf, moduleType);
+
+ g.claim(moduleType, sr2.IsDefinedBy , configuration);
+
+ Resource diagram = g.newResource();
+ g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,
+ ArrayMap
+ .keys("", "diagram", "name")
+ .values(configuration, diagram, "Diagrammi")
+ );
+
+
+ // Remove default mapping and add sysdyn mapping
+ for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {
+ if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {
+ g.deny(diagram, L0X.HasTrigger, trigger);
+ }
+ }
+
+ Resource mapping = g.newResource();
+ g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);
+ g.claim(diagram, L0X.HasTrigger, mapping);
+
+ Resource moduleSymbol = g.newResource();
+ g.claimLiteral(moduleSymbol, l0.HasName, name + " Symbol");
+ g.claimLiteral(moduleSymbol, l0.HasLabel, name + " Symbol");
+ g.claim(moduleSymbol, l0.Inherits, sr.ModuleSymbol);
+ g.claim(moduleSymbol, l0.InstanceOf, sr.ModuleSymbol);
+ g.claim(moduleSymbol, mr.SymbolToComponentType, moduleType);
+ g.claim(moduleSymbol, l0.PartOf, moduleType);
+
+ Resource terminal = g.newResource();
+ g.claim(terminal, l0.InstanceOf, sr.SysdynTerminal);
+ Resource relation = createTerminalRelation(g, moduleSymbol, sr.IsHeadOfTerminal, sr.Variable_isHeadOf);
+ DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal, relation);
+
+ Resource terminal2 = g.newResource();
+ g.claim(terminal2, l0.InstanceOf, sr.SysdynTerminal);
+ relation = createTerminalRelation(g, moduleSymbol, sr.IsTailOfTerminal, sr.Variable_isTailOf);
+ DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal2, relation);
+
+ g.claim(moduleSymbol, sr2.IsDefinedBy, OrderedSetUtils.create(g, sr2.Composite, terminal, terminal2));
+
+
+
+ }
+ });
+ }
+ };
+ }
+
+ public static Resource createTerminalRelation(WriteGraph graph, Resource symbol, Resource connectionRelation, Resource configurationRelation) throws DatabaseException {
+ StructuralResource2 STR = StructuralResource2.getInstance(graph);
+ ModelingResources MOD = ModelingResources.getInstance(graph);
+ Layer0 L0 = Layer0.getInstance(graph);
+
+
+ Resource terminalRelation = null;
+ terminalRelation = GraphUtils.create(graph,
+ MOD.DiagramConnectionRelationToConnectionRelation, configurationRelation,
+ L0.PartOf, symbol,
+ L0.HasName, NameUtils.getSafeName(graph, connectionRelation)
+ );
+
+ graph.claim(terminalRelation, L0.SubrelationOf, null, connectionRelation);
+ Resource inverse = GraphUtils.create(graph,
+ L0.PartOf, terminalRelation,
+ L0.HasName, "Inverse");
+
+ graph.claim(inverse, L0.SubrelationOf, null, STR.Connects);
+ graph.claim(terminalRelation, L0.InverseOf, inverse);
+
+ return terminalRelation;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import java.util.Collections;\r
-import java.util.UUID;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new pie chart\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewPieChartAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource model = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
-\r
- // Chart\r
- Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,\r
- l0.HasName, "PieChart" + UUID.randomUUID().toString(),\r
- l0.HasLabel, NameUtils.findFreshLabel(graph, "Pie Chart", model),\r
- l0.PartOf, model,\r
- jfree.Chart_visibleBorder, true,\r
- jfree.Chart_borderWidth, 3);\r
- graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
-\r
- // Title\r
- GraphUtils.create2(graph, jfree.TextTitle,\r
- l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Pie Chart Title",\r
- jfree.Title_position, jfree.Top,\r
- l0.PartOf, jfreechart);\r
- \r
- // Dataset\r
- Resource dataset = GraphUtils.create2(graph, jfree.PieDataset,\r
- l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
- jfree.Dataset_seriesList, ListUtils.create(graph, Collections.<Resource>emptyList())\r
- );\r
-\r
- // Plot\r
- GraphUtils.create2(graph, jfree.PiePlot,\r
- l0.HasName, "PiePlot" + UUID.randomUUID().toString(),\r
- l0.PartOf, jfreechart,\r
- l0.ConsistsOf, dataset\r
- );\r
- }\r
-\r
- });\r
- }\r
- };\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import java.util.Collections;
+import java.util.UUID;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.JFreeChartResource;
+
+/**
+ * Creates a new pie chart
+ * @author Teemu Lempinen
+ *
+ */
+public class NewPieChartAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ G2DResource g2d = G2DResource.getInstance(graph);
+
+ // Chart
+ Resource jfreechart = GraphUtils.create2(graph, jfree.Chart,
+ l0.HasName, "PieChart" + UUID.randomUUID().toString(),
+ l0.HasLabel, NameUtils.findFreshLabel(graph, "Pie Chart", model),
+ l0.PartOf, model,
+ jfree.Chart_visibleBorder, true,
+ jfree.Chart_borderWidth, 3);
+ graph.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});
+
+ // Title
+ GraphUtils.create2(graph, jfree.TextTitle,
+ l0.HasName, "TextTitle" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Pie Chart Title",
+ jfree.Title_position, jfree.Top,
+ l0.PartOf, jfreechart);
+
+ // Dataset
+ Resource dataset = GraphUtils.create2(graph, jfree.PieDataset,
+ l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),
+ jfree.Dataset_seriesList, ListUtils.create(graph, Collections.<Resource>emptyList())
+ );
+
+ // Plot
+ GraphUtils.create2(graph, jfree.PiePlot,
+ l0.HasName, "PiePlot" + UUID.randomUUID().toString(),
+ l0.PartOf, jfreechart,
+ l0.ConsistsOf, dataset
+ );
+ }
+
+ });
+ }
+ };
+ }
+
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.newActions;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityAnalysisExperimentNodeHandler;
+
+public class NewSensitivityAnalysisExperimentAction extends NewExperimentAction {
+
+ private NewSensitivityAnalysisExperimentNodeHandler handler = null;
+
+ public NewSensitivityAnalysisExperimentAction(){
+ this.handler = new NewSensitivityAnalysisExperimentNodeHandler();
+ }
+
+ protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+ this.handler.configureExperiment(graph, experiment);
+ }
+
+ protected Resource getExperimentType(ReadGraph g) {
+ return this.handler.getExperimentType(g);
+ }
+
+ protected String getNameSuggestion() {
+ return this.handler.getNameSuggestion();
+ }
+
+}
--- /dev/null
+package org.simantics.sysdyn.ui.browser.actions.newActions;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.db.Resource;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.sysdyn.ui.handlers.newComponents.NewSensitivityChartHandler;
+
+public class NewSensitivityChartAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource model = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+ try {
+ NewSensitivityChartHandler.handleStatic(model);
+ } catch (ExecutionException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.ActionFactory;\r
-import org.simantics.sysdyn.utils.SheetUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new spreadsheet to a book\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewSheetAction implements ActionFactory{\r
-\r
- @Override\r
- public Runnable create(Object target) {\r
- if(!(target instanceof Resource))\r
- return null;\r
- final Resource book = (Resource)target;\r
-\r
- return new Runnable() {\r
- @Override\r
- public void run() {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50});\r
- }\r
- \r
- });\r
- }\r
- };\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.ActionFactory;
+import org.simantics.spreadsheet.util.SpreadsheetUtils;
+
+/**
+ * Creates a new spreadsheet to a book
+ * @author Teemu Lempinen
+ *
+ */
+public class NewSheetAction implements ActionFactory{
+
+ @Override
+ public Runnable create(Object target) {
+ if(!(target instanceof Resource))
+ return null;
+ final Resource book = (Resource)target;
+
+ return new Runnable() {
+ @Override
+ public void run() {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SpreadsheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50});
+ }
+
+ });
+ }
+ };
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.newActions;\r
-\r
-import java.awt.Color;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-/**\r
- * Creates a new simulation playback experiment\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewSimulationPlaybackExperimentAction extends NewExperimentAction {\r
- \r
- protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- Resource defaultGradient = GraphUtils.create2(graph, g2d.ColorGradient);\r
- graph.claim(experiment, g2d.HasColorGradient, defaultGradient);\r
-\r
- Resource placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
- g2d.HasGradientPosition, 0.0);\r
- graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(0, 62, 133).getColorComponents(new float[4]));\r
- graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
- \r
- placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
- g2d.HasGradientPosition, 1.0);\r
- graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(255, 230, 0).getColorComponents(new float[4]));\r
- graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
- }\r
-\r
- protected Resource getExperimentType(ReadGraph g) {\r
- return SysdynResource.getInstance(g).PlaybackExperiment;\r
- }\r
-\r
- protected String getNameSuggestion() {\r
- return "Playback Experiment";\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.newActions;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.ui.handlers.newComponents.NewPlaybackExperimentNodeHandler;
+
+/**
+ * Creates a new simulation playback experiment
+ * @author Teemu Lempinen
+ *
+ */
+public class NewSimulationPlaybackExperimentAction extends NewExperimentAction {
+
+ private NewPlaybackExperimentNodeHandler handler = null;
+
+ public NewSimulationPlaybackExperimentAction() {
+ this.handler = new NewPlaybackExperimentNodeHandler();
+ }
+
+ protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+ this.handler.configureExperiment(graph, experiment);
+ }
+
+ protected Resource getExperimentType(ReadGraph g) {
+ return this.handler.getExperimentType(g);
+ }
+
+ protected String getNameSuggestion() {
+ return this.handler.getNameSuggestion();
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.actions.remove;
+
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.impl.AbstractRemover;
+import org.simantics.db.layer0.adapter.impl.EntityRemover;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ *
+ * @author Miro Eklund
+ *
+ */
+public class ModuleSymbolRemover extends AbstractRemover {
+
+ public ModuleSymbolRemover(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void remove(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+
+ Layer0 L0 = Layer0.getInstance(g);
+ SysdynResource sr = SysdynResource.getInstance(g);
+
+ //We need to remove the Module object, not just the symbol.
+ //Thus, if the resource is the symbol, find the parent Module first
+ if(g.isInstanceOf(resource, sr.ModuleSymbol)) {
+ Resource module = g.getPossibleObject(resource, L0.PartOf);
+ if(module != null) {
+ EntityRemover.remove(g, module, false); //Remove Module instead - was of type ModuleSymbol
+ } else {
+ EntityRemover.remove(g, resource, false);
+ }
+ } else {
+ EntityRemover.remove(g, resource, false); //Remove resource - not of type ModuleSymbol
+ }
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + resource;
+ }
+}
+++ /dev/null
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.actions.remove;\r
-\r
-import java.util.Map;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.Remover;\r
-import org.simantics.modeling.ui.modelBrowser.handlers.DeleteNodeHandler;\r
-\r
-/**\r
- * Remover for module type nodes. Not functioning - {@link DeleteNodeHandler} prevents deleting other than entityNodes\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ModuleTypeRemover implements Remover {\r
-\r
- private Resource resource;\r
- \r
- public ModuleTypeRemover(ReadGraph graph, Resource resource) {\r
- this.resource = resource;\r
- }\r
- \r
- @Override\r
- public String canRemove(ReadGraph graph, Map<Object, Object> aux) throws DatabaseException {\r
- return null;\r
- }\r
-\r
- @Override\r
- public void remove(WriteGraph graph) throws DatabaseException {\r
- System.out.println("Delete resource " + resource);\r
- }\r
-\r
-}\r
-package org.simantics.sysdyn.ui.browser.labelrules;\r
-\r
-import java.util.Collections;\r
-import java.util.Map;\r
-\r
-import org.simantics.browsing.ui.common.ColumnKeys;\r
-import org.simantics.browsing.ui.model.labels.LabelRule;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.modeling.ModelingResources;\r
-\r
-public class ModuleTypeLabelRule implements LabelRule {\r
- public static final ModuleTypeLabelRule INSTANCE = new ModuleTypeLabelRule();\r
-\r
- @Override\r
- public boolean isCompatible(Class<?> contentType) {\r
- return contentType.equals(Resource.class);\r
- }\r
-\r
- @Override\r
- public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
- Resource symbol = (Resource)content;\r
- Resource component = graph.getSingleObject(symbol, ModelingResources.getInstance(graph).SymbolToComponentType);\r
- \r
- return Collections.singletonMap(ColumnKeys.SINGLE, \r
- NameUtils.getSafeName(graph, component)\r
- );\r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.browser.labelrules;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.simantics.browsing.ui.common.ColumnKeys;
+import org.simantics.browsing.ui.model.labels.LabelRule;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.modeling.ModelingResources;
+
+public class ModuleTypeLabelRule implements LabelRule {
+ public static final ModuleTypeLabelRule INSTANCE = new ModuleTypeLabelRule();
+
+ @Override
+ public boolean isCompatible(Class<?> contentType) {
+ return contentType.equals(Resource.class);
+ }
+
+ @Override
+ public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {
+ Resource symbol = (Resource)content;
+ Resource component = graph.getPossibleObject(symbol, ModelingResources.getInstance(graph).SymbolToComponentType);
+
+ if(component != null) {
+ return Collections.singletonMap(ColumnKeys.SINGLE, NameUtils.getSafeName(graph, component));
+ } else {
+ return Collections.emptyMap();
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.labelrules;\r
-\r
-import java.util.Collections;\r
-import java.util.Map;\r
-\r
-import org.simantics.browsing.ui.common.ColumnKeys;\r
-import org.simantics.browsing.ui.model.labels.LabelRule;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class VariableNameLabelRule implements LabelRule {\r
- public static final ModuleTypeLabelRule INSTANCE = new ModuleTypeLabelRule();\r
-\r
- @Override\r
- public boolean isCompatible(Class<?> contentType) {\r
- return contentType.equals(Variable.class);\r
- }\r
-\r
- @Override\r
- public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {\r
- Variable var = AdaptionUtils.adaptToSingle(content, Variable.class);\r
- return Collections.singletonMap(ColumnKeys.SINGLE, \r
- var != null ? var.getName(graph) : "No variable"\r
- );\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.labelrules;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.simantics.browsing.ui.common.ColumnKeys;
+import org.simantics.browsing.ui.model.labels.LabelRule;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.ui.AdaptionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * VariableNameLabelRule for Sysdyn (Auxiliary, Stock, Valve, etc.)
+ * @author Teemu Lempinen, Miro Eklund
+ *
+ */
+public class VariableNameLabelRule implements LabelRule {
+
+ private static Logger LOGGER = LoggerFactory.getLogger(VariableNameLabelRule.class);
+
+ public static final ModuleTypeLabelRule INSTANCE = new ModuleTypeLabelRule();
+
+ @Override
+ public boolean isCompatible(Class<?> contentType) {
+ return contentType.equals(Variable.class);
+ }
+
+ @Override
+ public Map<String, String> getLabel(ReadGraph graph, Object content) throws DatabaseException {
+ Variable var = AdaptionUtils.adaptToSingle(content, Variable.class);
+ return Collections.singletonMap(ColumnKeys.SINGLE,
+ var != null ? (var.getName(graph) + possibleTypeAsString(graph, var)) : "No variable"
+ );
+ }
+
+ private static String possibleTypeAsString(ReadGraph graph, Variable var) throws DatabaseException {
+ try {
+ Layer0 L0 = Layer0.getInstance(graph);
+ String type = graph.getPossibleRelatedValue(var.getType(graph), L0.HasName);
+ return " : " + type;
+ } catch (NullPointerException | DatabaseException e) {
+ LOGGER.error("Failed to find type of resource", e);
+ }
+ return "";
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import java.util.Iterator;\r
-\r
-import org.eclipse.core.runtime.IAdaptable;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public abstract class AbstractChartNode<T> extends AbstractNode<Resource> implements IDropTargetNode, IDeletableNode {\r
-\r
- public AbstractChartNode(Resource data) {\r
- super(data);\r
- }\r
-\r
-\r
- /**\r
- * Add variable to this chart, if the dropped element(s) can be adapted to a {@link Variable} \r
- */\r
- @Override\r
- public void drop(Object data) {\r
- IStructuredSelection selection = (IStructuredSelection)data;\r
- Iterator<?> iterator = selection.iterator();\r
- while(iterator.hasNext()) {\r
- Object o = iterator.next();\r
- if(o instanceof IAdaptable) {\r
- Variable v = (Variable) ((IAdaptable)o).getAdapter(Variable.class);\r
- if(v != null) {\r
- addVariableToChart(v);\r
- }\r
- }\r
- }\r
- }\r
-\r
-\r
- /**\r
- * Adds a variable to this chart and map it to the first rangeAxis\r
- * @param variable\r
- */\r
- protected abstract void addVariableToChart(final Variable variable);\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- graph.markUndoPoint();\r
- String chartName = graph.getRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);\r
- RemoverUtil.remove(graph, data);\r
- Layer0Utils.addCommentMetadata(graph, "Removed chart '" + chartName +"' " + data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
-\r
- }\r
-\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.browser.nodes;
+
+import java.util.Iterator;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IDropTargetNode;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public abstract class AbstractChartNode<T> extends AbstractNode<Resource> implements IDropTargetNode, IDeletableNode {
+
+ public AbstractChartNode(Resource data) {
+ super(data);
+ }
+
+
+ /**
+ * Add variable to this chart, if the dropped element(s) can be adapted to a {@link Variable}
+ */
+ @Override
+ public void drop(Object data) {
+ IStructuredSelection selection = (IStructuredSelection)data;
+ Iterator<?> iterator = selection.iterator();
+ while(iterator.hasNext()) {
+ Object o = iterator.next();
+ if(o instanceof IAdaptable) {
+ Variable v = (Variable) ((IAdaptable)o).getAdapter(Variable.class);
+ if(v != null) {
+ addVariableToChart(v);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Adds a variable to this chart and map it to the first rangeAxis
+ * @param variable
+ */
+ protected abstract void addVariableToChart(final Variable variable);
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ graph.markUndoPoint();
+ String chartName = graph.getRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);
+ RemoverUtil.remove(graph, data);
+ Layer0Utils.addCommentMetadata(graph, "Removed chart '" + chartName +"' " + data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.Simantics;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.primitiverequest.PossibleObject;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.Logger;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class AnnotationType extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
-\r
- public AnnotationType(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- RemoverUtil.remove(graph, data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
-\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- Session session = Simantics.getSession();\r
- try {\r
- Resource relation = session.syncRequest(new PossibleObject(data, session.getService(Layer0.class).HasRange_Inverse));\r
- if(relation != null)\r
- return new LabelModifier(session, relation, session.getService(Layer0.class).HasName);\r
- } catch (Exception e) {\r
- Logger.defaultLogError(e);\r
- }\r
- return null;\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.primitiverequest.PossibleObject;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.Logger;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class AnnotationType extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {
+
+ public AnnotationType(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ RemoverUtil.remove(graph, data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ Session session = Simantics.getSession();
+ try {
+ Resource relation = session.syncRequest(new PossibleObject(data, session.getService(Layer0.class).HasRange_Inverse));
+ if(relation != null)
+ return new LabelModifier(session, relation, session.getService(Layer0.class).HasName);
+ } catch (Exception e) {
+ Logger.defaultLogError(e);
+ }
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.Simantics;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class AnnotationValue extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
-\r
- public AnnotationValue(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- RemoverUtil.remove(graph, data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
-\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- Session session = Simantics.getSession();\r
- return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class AnnotationValue extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {
+
+ public AnnotationValue(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ RemoverUtil.remove(graph, data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ Session session = Simantics.getSession();
+ return new LabelModifier(session, data, session.getService(Layer0.class).HasName);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.common.request.SingleObjectWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Bar chart node\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class BarChartNode extends AbstractChartNode<Resource> {\r
-\r
- public BarChartNode(Resource data) {\r
- super(data);\r
- }\r
- \r
- \r
- /**\r
- * Adds a variable to this chart\r
- * @param variable\r
- */\r
- @Override\r
- protected void addVariableToChart(final Variable variable) {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));\r
- if(plot == null)\r
- return;\r
-\r
- Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
- \r
- if(dataset == null)\r
- return;\r
- \r
- // Create the series and attach it to the dataset\r
- String rvi = Variables.getRVI(graph, variable);\r
- ChartUtils.createSeries(graph, dataset, rvi);\r
- }\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.PossibleObjectWithType;
+import org.simantics.db.common.request.SingleObjectWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+
+/**
+ * Bar chart node
+ * @author Teemu Lempinen
+ *
+ */
+public class BarChartNode extends AbstractChartNode<Resource> {
+
+ public BarChartNode(Resource data) {
+ super(data);
+ }
+
+
+ /**
+ * Adds a variable to this chart
+ * @param variable
+ */
+ @Override
+ protected void addVariableToChart(final Variable variable) {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));
+ if(plot == null)
+ return;
+
+ Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));
+
+ if(dataset == null)
+ return;
+
+ // Create the series and attach it to the dataset
+ String rvi = Variables.getRVI(graph, variable);
+ ChartUtils.createSeries(graph, dataset, rvi);
+ }
+ });
+ }
+
+}
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class EnumerationNode extends VariableNode<Resource> implements IModifiableNode, IDeletableNode {\r
-\r
- public EnumerationNode(Resource resource) {\r
- super(resource);\r
- }\r
- \r
- public EnumerationNode(Variable variable, Resource represents) {\r
- super(variable, represents);\r
- }\r
- \r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- \r
- final Session session = SimanticsUI.getSession();\r
- LabelModifier modifier = new LabelModifier(session, data, session.getService(Layer0.class).HasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (!new VariableNameValidator().isValid(data, label))\r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
- \r
- @Override\r
- public void modify(final String label) {\r
- try {\r
- session.syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph)\r
- throws DatabaseException {\r
-\r
- String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);\r
- if(!originalName.equals(label)) {\r
- Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);\r
- new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);\r
- graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- super.modify(label);\r
- }\r
- };\r
- return modifier;\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- graph.markUndoPoint();\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for(Resource redeclaration : graph.getObjects(data, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
- graph.deny(redeclaration, sr.Module_redeclaration_Inverse);\r
- }\r
- \r
- for(Resource redeclaration : graph.getObjects(data, sr.Redeclaration_replacingEnumeration_Inverse)) {\r
- graph.deny(redeclaration, sr.Module_redeclaration_Inverse);\r
- }\r
- \r
- Layer0 L0 = Layer0.getInstance(graph);\r
- Resource conf = graph.getPossibleObject(data, L0.PartOf);\r
- for(Resource var : graph.syncRequest(new ObjectsWithType(conf, L0.ConsistsOf, sr.Variable))) {\r
- Resource arrayIndexes = graph.getPossibleObject(var, sr.Variable_arrayIndexesList);\r
- if(arrayIndexes != null) {\r
- if(ListUtils.getNode(graph, arrayIndexes, data) != null) {\r
- ListUtils.removeElement(graph, arrayIndexes, data);\r
- }\r
- }\r
- }\r
- \r
- String enumerationName = graph.getPossibleRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);\r
- RemoverUtil.remove(graph, data);\r
- Layer0Utils.addCommentMetadata(graph, "Removed Enumeration " + enumerationName + " "+ data.toString());\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class EnumerationNode extends VariableNode<Resource> implements IModifiableNode, IDeletableNode {
+
+ public EnumerationNode(Resource resource) {
+ super(resource);
+ }
+
+ public EnumerationNode(Variable variable, Resource represents) {
+ super(variable, represents);
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+
+ final Session session = Simantics.getSession();
+ LabelModifier modifier = new LabelModifier(session, data, session.getService(Layer0.class).HasName) {
+ @Override
+ public String isValid(String label) {
+ if (!new VariableNameValidator().isValid(data, label))
+ return "Not valid";
+ else
+ return null;
+ }
+
+ @Override
+ public void modify(final String label) {
+ try {
+ session.syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph)
+ throws DatabaseException {
+
+ String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);
+ if(!originalName.equals(label)) {
+ Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);
+ new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);
+ graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ super.modify(label);
+ }
+ };
+ return modifier;
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ graph.markUndoPoint();
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for(Resource redeclaration : graph.getObjects(data, sr.Redeclaration_replacedEnumeration_Inverse)) {
+ graph.deny(redeclaration, sr.Module_redeclaration_Inverse);
+ }
+
+ for(Resource redeclaration : graph.getObjects(data, sr.Redeclaration_replacingEnumeration_Inverse)) {
+ graph.deny(redeclaration, sr.Module_redeclaration_Inverse);
+ }
+
+ Layer0 L0 = Layer0.getInstance(graph);
+ Resource conf = graph.getPossibleObject(data, L0.PartOf);
+ for(Resource var : graph.syncRequest(new ObjectsWithType(conf, L0.ConsistsOf, sr.Variable))) {
+ Resource arrayIndexes = graph.getPossibleObject(var, sr.Variable_arrayIndexesList);
+ if(arrayIndexes != null) {
+ if(ListUtils.getNode(graph, arrayIndexes, data) != null) {
+ ListUtils.removeElement(graph, arrayIndexes, data);
+ }
+ }
+ }
+
+ String enumerationName = graph.getPossibleRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);
+ RemoverUtil.remove(graph, data);
+ Layer0Utils.addCommentMetadata(graph, "Removed Enumeration " + enumerationName + " "+ data.toString());
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import java.util.Collection;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ErrorLogger;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class ExperimentNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode{\r
-\r
- public ExperimentNode(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public boolean handleDoubleClick() {\r
- if (data == null)\r
- return false;\r
- IProject project = SimanticsUI.getProject();\r
- IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- if (experimentManager == null) {\r
- ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());\r
- return false;\r
- }\r
- SysdynExperimentActivator.scheduleActivation(SimanticsUI.getSession(), project, experimentManager, data);\r
- return true;\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
- @Override\r
- public String isValid(String label) {\r
- if (label.isEmpty())\r
- return "Empty label not allowed";\r
- return null;\r
- }\r
- };\r
- return modifier;\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- Collection<Resource> results = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_result);\r
- if(results != null)\r
- for(Resource result : results) \r
- SimulationResultNode.unlinkResult(graph, result);\r
- Collection<Resource> resultSets = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_resultSet);\r
- if(resultSets != null)\r
- for(Resource resultSet : resultSets) \r
- SimulationResultSetNode.unlinkResultSet(graph, resultSet);\r
- String ontologyName = graph.getPossibleRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);\r
- RemoverUtil.remove(graph, data);\r
- Layer0Utils.addCommentMetadata(graph, "Removed experiment " + ontologyName + " "+ data.toString());\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.browser.nodes;
+
+import java.util.Collection;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.project.IProject;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.handlers.SysdynExperimentActivator;
+import org.simantics.utils.ui.ErrorLogger;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class ExperimentNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode{
+
+ public ExperimentNode(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public boolean handleDoubleClick() {
+ if (data == null)
+ return false;
+ IProject project = Simantics.getProject();
+ IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ if (experimentManager == null) {
+ ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());
+ return false;
+ }
+ SysdynExperimentActivator.scheduleActivation(Simantics.getSession(), project, experimentManager, data);
+ return true;
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), data) {
+ @Override
+ public String isValid(String label) {
+ if (label.isEmpty())
+ return "Empty label not allowed";
+ return null;
+ }
+ };
+ return modifier;
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ Collection<Resource> results = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_result);
+ if(results != null)
+ for(Resource result : results)
+ SimulationResultNode.unlinkResult(graph, result);
+ Collection<Resource> resultSets = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_resultSet);
+ if(resultSets != null)
+ for(Resource resultSet : resultSets)
+ SimulationResultSetNode.unlinkResultSet(graph, resultSet);
+ String ontologyName = graph.getPossibleRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);
+ RemoverUtil.remove(graph, data);
+ Layer0Utils.addCommentMetadata(graph, "Removed experiment " + ontologyName + " "+ data.toString());
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
- * in Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import java.util.Collection;\r
-\r
-import org.eclipse.core.expressions.PropertyTester;\r
-import org.eclipse.ui.IEditorPart;\r
-import org.eclipse.ui.IWorkbenchPage;\r
-import org.simantics.DatabaseJob;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.request.PossibleModel;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
-import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * This class tests whether the export functionality is active\r
- * \r
- * @author Tuomas Miettinen\r
- * @author Tuukka Lehtonen\r
- */\r
-public class ExportTester extends PropertyTester {\r
-\r
- @Override\r
- public boolean test(Object receiver, final String property, final Object[] args, final Object expectedValue) {\r
- // Find the resource from the receiver.\r
- Resource inputResource = ResourceAdaptionUtils.toSingleResource(receiver);\r
- if (inputResource == null) {\r
- @SuppressWarnings("rawtypes")\r
- Collection<AbstractNode> a = AdaptionUtils.adaptToCollection(receiver, AbstractNode.class);\r
- if (a.size() > 1) // Multiple selections.\r
- return false;\r
- if (a.size() == 1)\r
- inputResource = (Resource)a.iterator().next().data;\r
- }\r
- if (inputResource == null) {\r
- \r
- IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();\r
- IEditorPart editor = page.getActiveEditor();\r
- if (editor instanceof DiagramEditor) {\r
- inputResource = ((DiagramEditor)editor).getInputResource();\r
- } else {\r
- return false;\r
- }\r
- }\r
- final Resource resource = inputResource;\r
-\r
- Session session = SimanticsUI.peekSession();\r
- if (session == null)\r
- return false;\r
-\r
- if (DatabaseJob.inProgress())\r
- return false;\r
-\r
- // Check if we can get the model of the resource.\r
- try {\r
- return session.syncRequest(new Read<Boolean>() {\r
- @Override\r
- public Boolean perform(ReadGraph g) throws DatabaseException {\r
- if (g.sync(new PossibleModel(resource)) != null) {\r
- return true;\r
- }\r
- return false;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- // Purposefully not logging these exceptions, there might be way too\r
- // many even under normal circumstances.\r
- // TODO: add debug tracing options controlling the printing of these exceptions\r
- return false;\r
- }\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.nodes;
+
+import java.util.Collection;
+
+import org.eclipse.core.expressions.PropertyTester;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IWorkbenchPage;
+import org.simantics.DatabaseJob;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.request.PossibleModel;
+import org.simantics.db.request.Read;
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * This class tests whether the export functionality is active
+ *
+ * @author Tuomas Miettinen
+ * @author Tuukka Lehtonen
+ */
+public class ExportTester extends PropertyTester {
+
+ @Override
+ public boolean test(Object receiver, final String property, final Object[] args, final Object expectedValue) {
+ // Find the resource from the receiver.
+ Resource inputResource = ResourceAdaptionUtils.toSingleResource(receiver);
+ if (inputResource == null) {
+ @SuppressWarnings("rawtypes")
+ Collection<AbstractNode> a = AdaptionUtils.adaptToCollection(receiver, AbstractNode.class);
+ if (a.size() > 1) // Multiple selections.
+ return false;
+ if (a.size() == 1)
+ inputResource = (Resource)a.iterator().next().data;
+ }
+ if (inputResource == null) {
+
+ IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();
+ IEditorPart editor = page.getActiveEditor();
+ if (editor instanceof DiagramEditor) {
+ inputResource = ((DiagramEditor)editor).getInputResource();
+ } else {
+ return false;
+ }
+ }
+ final Resource resource = inputResource;
+
+ Session session = Simantics.peekSession();
+ if (session == null)
+ return false;
+
+ if (DatabaseJob.inProgress())
+ return false;
+
+ // Check if we can get the model of the resource.
+ try {
+ return session.syncRequest(new Read<Boolean>() {
+ @Override
+ public Boolean perform(ReadGraph g) throws DatabaseException {
+ if (g.sync(new PossibleModel(resource)) != null) {
+ return true;
+ }
+ return false;
+ }
+ });
+ } catch (DatabaseException e) {
+ // Purposefully not logging these exceptions, there might be way too
+ // many even under normal circumstances.
+ // TODO: add debug tracing options controlling the printing of these exceptions
+ return false;
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.Simantics;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.FunctionLibraryNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-public class FunctionLibraryNode<T> extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode, IDropTargetNode {\r
-\r
- \r
- public FunctionLibraryNode(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- try {\r
- Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName;\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data, hasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (!new FunctionLibraryNameValidator().isValid(data, label))\r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
- };\r
- return modifier;\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return null;\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- graph.markUndoPoint();\r
- Layer0Utils.addCommentMetadata(graph, "Removed " + NameUtils.getSafeName(graph, data));\r
- RemoverUtil.remove(graph, data);\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void drop(Object data) {\r
- final Resource[] resources = ResourceAdaptionUtils.toResources(data);\r
- final Resource library = this.data;\r
- if(resources.length > 0) {\r
- Simantics.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- // Fixing #5196\r
- // Prevent dropping functions to immutable function libraries such as Built-in Functions, Modelica Array Functions etc.\r
- if (graph.isImmutable(library))\r
- return;\r
- \r
- for(Resource tobeMoved : resources) {\r
- if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||\r
- graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {\r
- graph.deny(tobeMoved, l0.PartOf);\r
- graph.claim(tobeMoved, l0.PartOf, library);\r
- }\r
- }\r
- }\r
- });\r
- }\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IDropTargetNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.utils.FunctionLibraryNameValidator;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+public class FunctionLibraryNode<T> extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode, IDropTargetNode {
+
+
+ public FunctionLibraryNode(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ try {
+ Resource hasName = Layer0.getInstance(Simantics.getSession()).HasName;
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), data, hasName) {
+ @Override
+ public String isValid(String label) {
+ if (!new FunctionLibraryNameValidator().isValid(data, label))
+ return "Not valid";
+ else
+ return null;
+ }
+ };
+ return modifier;
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ graph.markUndoPoint();
+ Layer0Utils.addCommentMetadata(graph, "Removed " + NameUtils.getSafeName(graph, data));
+ RemoverUtil.remove(graph, data);
+ }
+ });
+ }
+
+ @Override
+ public void drop(Object data) {
+ final Resource[] resources = ResourceAdaptionUtils.toResources(data);
+ final Resource library = this.data;
+ if(resources.length > 0) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ // Fixing #5196
+ // Prevent dropping functions to immutable function libraries such as Built-in Functions, Modelica Array Functions etc.
+ if (graph.isImmutable(library))
+ return;
+
+ for(Resource tobeMoved : resources) {
+ if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||
+ graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {
+ graph.deny(tobeMoved, l0.PartOf);
+ graph.claim(tobeMoved, l0.PartOf, library);
+ }
+ }
+ }
+ });
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class HistoryDataNode extends SimulationResultNode<Resource> {\r
-\r
- public HistoryDataNode(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- RemoverUtil.remove(graph, data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- }\r
- \r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class HistoryDataNode extends SimulationResultNode<Resource> {
+
+ public HistoryDataNode(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ RemoverUtil.remove(graph, data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class InitialCondition extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
-\r
- public InitialCondition(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- RemoverUtil.remove(graph, data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
-\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- Session session = SimanticsUI.getSession();\r
- return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class InitialCondition extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {
+
+ public InitialCondition(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ RemoverUtil.remove(graph, data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ Session session = Simantics.getSession();
+ return new LabelModifier(session, data, session.getService(Layer0.class).HasName);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.Simantics;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class Library extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
-\r
- public Library(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- RemoverUtil.remove(graph, data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
-\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- Session session = Simantics.getSession();\r
- return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class Library extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {
+
+ public Library(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ RemoverUtil.remove(graph, data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ Session session = Simantics.getSession();
+ return new LabelModifier(session, data, session.getService(Layer0.class).HasName);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.SingleObjectWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Node representing a line chart\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class LineChartNode extends AbstractChartNode<Resource> {\r
-\r
- public LineChartNode(Resource data) {\r
- super(data);\r
- }\r
-\r
- /**\r
- * Adds a variable to this chart and map it to the first rangeAxis\r
- * @param variable\r
- */\r
- @Override\r
- protected void addVariableToChart(final Variable variable) {\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));\r
- if(plot == null)\r
- return;\r
-\r
- Resource rangeAxis = null;\r
- Resource dataset = null;\r
- Resource rangeAxisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);\r
- if(rangeAxisList == null || ListUtils.toList(graph, rangeAxisList).isEmpty()) {\r
- // No range axis -> Create a new one\r
- rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);\r
- Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);\r
- dataset = ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);\r
- } else {\r
- rangeAxis = ListUtils.toList(graph, rangeAxisList).get(0);\r
- dataset = graph.getPossibleObject(rangeAxis, jfree.Dataset_mapToRangeAxis_Inverse);\r
- }\r
- \r
- // Create the series and attach it to the dataset\r
- String rvi = Variables.getRVI(graph, variable);\r
- ChartUtils.createSeries(graph, dataset, rvi);\r
- }\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.SingleObjectWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+
+/**
+ * Node representing a line chart
+ * @author Teemu Lempinen
+ *
+ */
+public class LineChartNode extends AbstractChartNode<Resource> {
+
+ public LineChartNode(Resource data) {
+ super(data);
+ }
+
+ /**
+ * Adds a variable to this chart and map it to the first rangeAxis
+ * @param variable
+ */
+ @Override
+ protected void addVariableToChart(final Variable variable) {
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));
+ if(plot == null)
+ return;
+
+ Resource rangeAxis = null;
+ Resource dataset = null;
+ Resource rangeAxisList = graph.getPossibleObject(plot, jfree.Plot_rangeAxisList);
+ if(rangeAxisList == null || ListUtils.toList(graph, rangeAxisList).isEmpty()) {
+ // No range axis -> Create a new one
+ rangeAxis = ChartUtils.createNumberRangeAxis(graph, plot);
+ Resource domainAxis = graph.getPossibleObject(plot, jfree.Plot_domainAxis);
+ dataset = ChartUtils.createXYDataset(graph, plot, domainAxis, rangeAxis);
+ } else {
+ rangeAxis = ListUtils.toList(graph, rangeAxisList).get(0);
+ dataset = graph.getPossibleObject(rangeAxis, jfree.Dataset_mapToRangeAxis_Inverse);
+ }
+
+ // Create the series and attach it to the dataset
+ String rvi = Variables.getRVI(graph, variable);
+ ChartUtils.createSeries(graph, dataset, rvi);
+ }
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.Simantics;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.db.request.Write;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.ModelNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class ModelNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {\r
-\r
- Listener<String> configurationNameSynchronizer;\r
- private boolean disposed = false;\r
- \r
- public ModelNode(Resource resource) {\r
- super(resource);\r
- \r
- // Not the best solution for name sync\r
- configurationNameSynchronizer = new Listener<String>() {\r
-\r
- @Override\r
- public void execute(final String result) {\r
- if (result == null)\r
- return;\r
- Simantics.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SimulationResource sim = SimulationResource.getInstance(graph);\r
- Resource configuration = graph.getPossibleObject(data, sim.HasConfiguration);\r
- \r
- String label = graph.getPossibleRelatedValue2(configuration, l0.HasLabel, Bindings.STRING);\r
- if (label != null)\r
- return;\r
- \r
- graph.claimLiteral(configuration, l0.HasLabel, result);\r
- Layer0Utils.addCommentMetadata(graph, "Created ModelNode to model browser for model " + result);\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
- };\r
- \r
- SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- return graph.getPossibleRelatedValue(data, Layer0.getInstance(graph).HasLabel);\r
- }\r
- \r
- }, configurationNameSynchronizer);\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
- @Override\r
- public String isValid(String label) {\r
- if (!new ModelNameValidator().isValid(data, label))\r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
- \r
- @Override\r
- protected Write getWriteRequest(final String label) {\r
- return new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- String oldName = g.getPossibleRelatedValue2(data, l0.HasLabel, Bindings.STRING);\r
- g.claimLiteral(data, l0.HasLabel, label);\r
- String safeName = NameUtils.findFreshName(g, label, g.getSingleObject(data, l0.PartOf), l0.ConsistsOf, "%s%d");\r
- g.claimLiteral(data, l0.HasName, safeName);\r
- Layer0Utils.addCommentMetadata(g, "Renamed model " + oldName + " to " + label + " " + data.toString());\r
- }\r
- };\r
- }\r
- };\r
- return modifier;\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- disposed = true;\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- \r
- graph.markUndoPoint();\r
- \r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- for(Resource r : graph.getObjects(data, l0.ConsistsOf))\r
- if(graph.isInstanceOf(r, SysdynResource.getInstance(graph).Result))\r
- SimulationResultNode.deleteResultFiles(graph, r);\r
-\r
- String modelName = graph.getPossibleRelatedValue2(data, l0.HasName, Bindings.STRING);\r
- String modelResource = data.toString();\r
- RemoverUtil.remove(graph, data);\r
- \r
- Layer0Utils.addCommentMetadata(graph, "Removed model '" + modelName +"' " + modelResource);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- }\r
- \r
- }\r
-\r
- @Override\r
- public boolean handleDoubleClick() {\r
- return false;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+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.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.db.request.Write;
+import org.simantics.layer0.Layer0;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.utils.ModelNameValidator;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class ModelNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {
+
+ Listener<String> configurationNameSynchronizer;
+ private boolean disposed = false;
+
+ public ModelNode(Resource resource) {
+ super(resource);
+
+ // Not the best solution for name sync
+ configurationNameSynchronizer = new Listener<String>() {
+
+ @Override
+ public void execute(final String result) {
+ if (result == null)
+ return;
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SimulationResource sim = SimulationResource.getInstance(graph);
+ Resource configuration = graph.getPossibleObject(data, sim.HasConfiguration);
+
+ String label = graph.getPossibleRelatedValue2(configuration, l0.HasLabel, Bindings.STRING);
+ if (label != null)
+ return;
+
+ graph.claimLiteral(configuration, l0.HasLabel, result);
+ Layer0Utils.addCommentMetadata(graph, "Created ModelNode to model browser for model " + result);
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+ };
+
+ Simantics.getSession().asyncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ return graph.getPossibleRelatedValue(data, Layer0.getInstance(graph).HasLabel);
+ }
+
+ }, configurationNameSynchronizer);
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), data) {
+ @Override
+ public String isValid(String label) {
+ if (!new ModelNameValidator().isValid(data, label))
+ return "Not valid";
+ else
+ return null;
+ }
+
+ @Override
+ protected Write getWriteRequest(final String label) {
+ return new WriteRequest() {
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ String oldName = g.getPossibleRelatedValue2(data, l0.HasLabel, Bindings.STRING);
+ g.claimLiteral(data, l0.HasLabel, label);
+ String safeName = NameUtils.findFreshName(g, label, g.getSingleObject(data, l0.PartOf), l0.ConsistsOf, "%s%d");
+ g.claimLiteral(data, l0.HasName, safeName);
+ Layer0Utils.addCommentMetadata(g, "Renamed model " + oldName + " to " + label + " " + data.toString());
+ }
+ };
+ }
+ };
+ return modifier;
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ disposed = true;
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+
+ graph.markUndoPoint();
+
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ for(Resource r : graph.getObjects(data, l0.ConsistsOf))
+ if(graph.isInstanceOf(r, SysdynResource.getInstance(graph).Result))
+ SimulationResultNode.deleteResultFiles(graph, r);
+
+ String modelName = graph.getPossibleRelatedValue2(data, l0.HasName, Bindings.STRING);
+ String modelResource = data.toString();
+ RemoverUtil.remove(graph, data);
+
+ Layer0Utils.addCommentMetadata(graph, "Removed model '" + modelName +"' " + modelResource);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
+ @Override
+ public boolean handleDoubleClick() {
+ return false;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.PasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ModuleNode extends ConfigurationNode<Resource> implements IModifiableNode {\r
-\r
- Resource configuration;\r
- \r
- public ModuleNode(Resource resource) {\r
- super(resource);\r
- \r
-\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- Resource type = graph.getPossibleObject(data, Layer0.getInstance(graph).InstanceOf);\r
- configuration = graph.getPossibleObject(type, StructuralResource2.getInstance(graph).IsDefinedBy); \r
- }\r
- });\r
- }\r
- \r
- public ModuleNode(Variable variable, Resource represents) {\r
- super(variable, represents);\r
- \r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- Resource type = graph.getPossibleObject(data, Layer0.getInstance(graph).InstanceOf);\r
- configuration = graph.getPossibleObject(type, StructuralResource2.getInstance(graph).IsDefinedBy); \r
- }\r
- });\r
- }\r
- \r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public Object getAdapter(Class adapter) {\r
- if(PasteHandler.class == adapter && configuration != null) \r
- return new DefaultPasteHandler(configuration);\r
- return super.getAdapter(adapter);\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- try {\r
- final Session session = SimanticsUI.getSession();\r
- Resource hasName = Layer0.getInstance(session).HasName;\r
- LabelModifier modifier = new LabelModifier(session, data, hasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (!new VariableNameValidator().isValid(data, label))\r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
- \r
- @Override\r
- public void modify(final String label) {\r
- try {\r
- session.syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph)\r
- throws DatabaseException {\r
-\r
- String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);\r
- if(!originalName.equals(label)) {\r
- Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);\r
- new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);\r
- graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- super.modify(label);\r
- }\r
- };\r
- return modifier;\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return null;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.PasteHandler;
+import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.layer0.Layer0;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;
+
+public class ModuleNode extends ConfigurationNode<Resource> implements IModifiableNode {
+
+ Resource configuration;
+
+ public ModuleNode(Resource resource) {
+ super(resource);
+
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ Resource type = graph.getPossibleObject(data, Layer0.getInstance(graph).InstanceOf);
+ configuration = graph.getPossibleObject(type, StructuralResource2.getInstance(graph).IsDefinedBy);
+ }
+ });
+ }
+
+ public ModuleNode(Variable variable, Resource represents) {
+ super(variable, represents);
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ Resource type = graph.getPossibleObject(data, Layer0.getInstance(graph).InstanceOf);
+ configuration = graph.getPossibleObject(type, StructuralResource2.getInstance(graph).IsDefinedBy);
+ }
+ });
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public Object getAdapter(Class adapter) {
+ if(PasteHandler.class == adapter && configuration != null)
+ return new DefaultPasteHandler(configuration);
+ return super.getAdapter(adapter);
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ try {
+ final Session session = Simantics.getSession();
+ Resource hasName = Layer0.getInstance(session).HasName;
+ LabelModifier modifier = new LabelModifier(session, data, hasName) {
+ @Override
+ public String isValid(String label) {
+ if (!new VariableNameValidator().isValid(data, label))
+ return "Not valid";
+ else
+ return null;
+ }
+
+ @Override
+ public void modify(final String label) {
+ try {
+ session.syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph)
+ throws DatabaseException {
+
+ String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);
+ if(!originalName.equals(label)) {
+ Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);
+ new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);
+ graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ super.modify(label);
+ }
+ };
+ return modifier;
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import java.util.Collection;\r
-\r
-import org.eclipse.jface.dialogs.MessageDialog;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
-import org.simantics.db.exception.ServiceException;\r
-import org.simantics.db.layer0.adapter.PasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.issues.ontology.IssueResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.ui.utils.ModuleTypeNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ModuleTypeNode extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
-\r
- \r
- Listener<String> configurationNameSynchronizer;\r
- private boolean disposed = false;\r
- private Resource configuration;\r
- \r
- public ModuleTypeNode(Resource resource) {\r
- super(resource);\r
-\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
- Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);\r
- configuration = graph.getPossibleObject(type, sr2.IsDefinedBy); \r
- }\r
- });\r
- \r
- // Not the best solution for name sync\r
- configurationNameSynchronizer = new Listener<String>() {\r
-\r
- @Override\r
- public void execute(final String result) {\r
- if(result == null)\r
- return; \r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- if(configuration != null) {\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- String currentLabel = graph.getRelatedValue2(configuration, L0.HasLabel, Bindings.STRING);\r
- if (!currentLabel.equals(result))\r
- graph.claimLiteral(configuration, L0.HasLabel, result);\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
- };\r
- \r
- SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);\r
- return (String) (type != null ? graph.getRelatedValue(type, l0.HasName) : null);\r
- }\r
- \r
- }, configurationNameSynchronizer);\r
- \r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- Modifier modifier = null;\r
- try {\r
- modifier = SimanticsUI.getSession().syncRequest(new Read<Modifier>() {\r
-\r
- @Override\r
- public Modifier perform(ReadGraph graph) throws ManyObjectsForFunctionalRelationException, ServiceException {\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);\r
-\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), type, l0.HasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (!new ModuleTypeNameValidator().isValid(data, label))\r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
- };\r
-\r
-\r
- return modifier;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- return modifier;\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- disposed = true;\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException{\r
- graph.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- StructuralResource2 st = StructuralResource2.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
-\r
- Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);\r
- Resource model = graph.getSingleObject(type, l0.PartOf);\r
- Resource modelConfiguration = graph.getSingleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
- if (!graph.syncRequest(new ObjectsWithType(modelConfiguration, l0.ConsistsOf, type)).isEmpty()) {\r
- throw new ModuleDeleteException("The module is used at the model configuration");\r
- }\r
- Collection<Resource> moduleTypes = graph.syncRequest(new ObjectsWithType(model, l0.ConsistsOf, st.ComponentType));\r
- for(Resource r : moduleTypes) {\r
- Resource configuration = graph.getPossibleObject(r, st.IsDefinedBy);\r
- if(configuration != null && !graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, type)).isEmpty()) {\r
- throw new ModuleDeleteException("The module is used at another module: " + graph.getRelatedValue(r, l0.HasName));\r
- }\r
- }\r
- \r
- IssueResource ISSUE = IssueResource.getInstance(graph);\r
- // Remove issues\r
- for(Resource issueSource : graph.syncRequest(new ObjectsWithType(type, l0.ConsistsOf, ISSUE.Sources_DependencyTracker))) {\r
- for(Resource issue : graph.syncRequest(new ObjectsWithType(issueSource, ISSUE.IssueSource_Manages, ISSUE.Issue))) {\r
- RemoverUtil.remove(graph, issue);\r
- }\r
- }\r
- Layer0Utils.addCommentMetadata(graph, "Removed Module Type " + graph.getRelatedValue2(type, l0.HasName, Bindings.STRING) + " " + type.toString());\r
- RemoverUtil.remove(graph, type);\r
- }\r
- });\r
- } catch (ModuleDeleteException e) {\r
- Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
- MessageDialog dialog = new MessageDialog(shell, "Unable to delete", null, e.message, SWT.ERROR,\r
- new String[] { "OK" }, 0);\r
- dialog.create();\r
- dialog.open();\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- private class ModuleDeleteException extends DatabaseException {\r
- private static final long serialVersionUID = 4076002781765246919L;\r
- String message;\r
- \r
- public ModuleDeleteException(String message) {\r
- this.message = message;\r
- }\r
- }\r
- \r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public Object getAdapter(Class adapter) {\r
- if(PasteHandler.class == adapter && configuration != null) \r
- return new DefaultPasteHandler(configuration);\r
- return super.getAdapter(adapter);\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.browser.nodes;
+
+import java.util.Collection;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.PlatformUI;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+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.ObjectsWithType;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
+import org.simantics.db.exception.ServiceException;
+import org.simantics.db.layer0.adapter.PasteHandler;
+import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.issues.ontology.IssueResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.ui.utils.ModuleTypeNameValidator;
+
+public class ModuleTypeNode extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {
+
+
+ Listener<String> configurationNameSynchronizer;
+ private boolean disposed = false;
+ private Resource configuration;
+
+ public ModuleTypeNode(Resource resource) {
+ super(resource);
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+ Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);
+ configuration = graph.getPossibleObject(type, sr2.IsDefinedBy);
+ }
+ });
+
+ // Not the best solution for name sync
+ configurationNameSynchronizer = new Listener<String>() {
+
+ @Override
+ public void execute(final String result) {
+ if(result == null)
+ return;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ if(configuration != null) {
+ Layer0 L0 = Layer0.getInstance(graph);
+ String currentLabel = graph.getRelatedValue2(configuration, L0.HasLabel, Bindings.STRING);
+ if (!currentLabel.equals(result))
+ graph.claimLiteral(configuration, L0.HasLabel, result);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+ };
+
+ Simantics.getSession().asyncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);
+ return (String) (type != null ? graph.getRelatedValue(type, l0.HasName) : null);
+ }
+
+ }, configurationNameSynchronizer);
+
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ Modifier modifier = null;
+ try {
+ modifier = Simantics.getSession().syncRequest(new Read<Modifier>() {
+
+ @Override
+ public Modifier perform(ReadGraph graph) throws ManyObjectsForFunctionalRelationException, ServiceException {
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);
+
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), type, l0.HasName) {
+ @Override
+ public String isValid(String label) {
+ if (!new ModuleTypeNameValidator().isValid(data, label))
+ return "Not valid";
+ else
+ return null;
+ }
+ };
+
+
+ return modifier;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ return modifier;
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ disposed = true;
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException{
+ graph.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(graph);
+ StructuralResource2 st = StructuralResource2.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+
+ Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);
+ Resource model = graph.getSingleObject(type, l0.PartOf);
+ Resource modelConfiguration = graph.getSingleObject(model, SimulationResource.getInstance(graph).HasConfiguration);
+ if (!graph.syncRequest(new ObjectsWithType(modelConfiguration, l0.ConsistsOf, type)).isEmpty()) {
+ throw new ModuleDeleteException("The module is used at the model configuration");
+ }
+ Collection<Resource> moduleTypes = graph.syncRequest(new ObjectsWithType(model, l0.ConsistsOf, st.ComponentType));
+ for(Resource r : moduleTypes) {
+ Resource configuration = graph.getPossibleObject(r, st.IsDefinedBy);
+ if(configuration != null && !graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, type)).isEmpty()) {
+ throw new ModuleDeleteException("The module is used at another module: " + graph.getRelatedValue(r, l0.HasName));
+ }
+ }
+
+ IssueResource ISSUE = IssueResource.getInstance(graph);
+ // Remove issues
+ for(Resource issueSource : graph.syncRequest(new ObjectsWithType(type, l0.ConsistsOf, ISSUE.Sources_DependencyTracker))) {
+ for(Resource issue : graph.syncRequest(new ObjectsWithType(issueSource, ISSUE.IssueSource_Manages, ISSUE.Issue))) {
+ RemoverUtil.remove(graph, issue);
+ }
+ }
+ Layer0Utils.addCommentMetadata(graph, "Removed Module Type " + graph.getRelatedValue2(type, l0.HasName, Bindings.STRING) + " " + type.toString());
+ RemoverUtil.remove(graph, type);
+ }
+ });
+ } catch (ModuleDeleteException e) {
+ Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
+ MessageDialog dialog = new MessageDialog(shell, "Unable to delete", null, e.message, SWT.ERROR,
+ new String[] { "OK" }, 0);
+ dialog.create();
+ dialog.open();
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private class ModuleDeleteException extends DatabaseException {
+ private static final long serialVersionUID = 4076002781765246919L;
+ String message;
+
+ public ModuleDeleteException(String message) {
+ this.message = message;
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public Object getAdapter(Class adapter) {
+ if(PasteHandler.class == adapter && configuration != null)
+ return new DefaultPasteHandler(configuration);
+ return super.getAdapter(adapter);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.common.request.SingleObjectWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Node for pie charts\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class PieChartNode extends AbstractChartNode<Resource> {\r
-\r
- public PieChartNode(Resource data) {\r
- super(data);\r
- }\r
-\r
- /**\r
- * Adds a variable to this chart\r
- * @param variable\r
- */\r
- @Override\r
- protected void addVariableToChart(final Variable variable) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));\r
- if(plot == null)\r
- return;\r
-\r
- Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));\r
- \r
- if(dataset == null)\r
- return;\r
- \r
- // Create the series and attach it to the dataset\r
- String rvi = Variables.getRVI(graph, variable);\r
- Resource series = ChartUtils.createSeries(graph, dataset, rvi);\r
- graph.claimLiteral(series, jfree.Series_exploded, false);\r
- }\r
- }); \r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.PossibleObjectWithType;
+import org.simantics.db.common.request.SingleObjectWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.JFreeChartResource;
+
+/**
+ * Node for pie charts
+ * @author Teemu Lempinen
+ *
+ */
+public class PieChartNode extends AbstractChartNode<Resource> {
+
+ public PieChartNode(Resource data) {
+ super(data);
+ }
+
+ /**
+ * Adds a variable to this chart
+ * @param variable
+ */
+ @Override
+ protected void addVariableToChart(final Variable variable) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ Resource plot = graph.syncRequest(new SingleObjectWithType(data, l0.ConsistsOf, jfree.Plot));
+ if(plot == null)
+ return;
+
+ Resource dataset = graph.syncRequest(new PossibleObjectWithType(plot, l0.ConsistsOf, jfree.Dataset));
+
+ if(dataset == null)
+ return;
+
+ // Create the series and attach it to the dataset
+ String rvi = Variables.getRVI(graph, variable);
+ Resource series = ChartUtils.createSeries(graph, dataset, rvi);
+ graph.claimLiteral(series, jfree.Series_exploded, false);
+ }
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class SCLModule extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
-\r
- public SCLModule(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- String ontologyName = graph.getPossibleRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);\r
- RemoverUtil.remove(graph, data);\r
- Layer0Utils.addCommentMetadata(graph, "Removed SCL Module " + ontologyName + " "+ data.toString());\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- } \r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- Session session = SimanticsUI.getSession();\r
- return new LabelModifier(session, data, session.getService(Layer0.class).HasName);\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class SCLModule extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {
+
+ public SCLModule(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ String ontologyName = graph.getPossibleRelatedValue2(data, Layer0.getInstance(graph).HasName, Bindings.STRING);
+ RemoverUtil.remove(graph, data);
+ Layer0Utils.addCommentMetadata(graph, "Removed SCL Module " + ontologyName + " "+ data.toString());
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ Session session = Simantics.getSession();
+ return new LabelModifier(session, data, session.getService(Layer0.class).HasName);
+ }
+
+}
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.eclipse.ui.PartInitException;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.RVI;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.ui.utils.SheetNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.workbench.ResourceEditorInput2;\r
-import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
-\r
-public class SheetNode extends AbstractNode<Resource> implements IModifiableNode, IDoubleClickableNode {\r
-\r
- public SheetNode(Resource data) {\r
- super(data);\r
- }\r
- \r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- \r
- Session session = SimanticsUI.getSession();\r
- LabelModifier modifier = new LabelModifier(session, data, session.getService(Layer0.class).HasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (!new SheetNameValidator().isValid(data, label))\r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
- };\r
- return modifier;\r
- }\r
-\r
- @Override\r
- public boolean handleDoubleClick() {\r
- \r
- try {\r
- \r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
-\r
- Variable variable = graph.adapt(data, Variable.class);\r
- final Resource model = Variables.getModel(graph, variable);\r
- final RVI rvi = variable.getRVI(graph);\r
-\r
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
- \r
- private static final String EDITOR_ID = "org.simantics.spreadsheet.ui.editor2";\r
- \r
- @Override\r
- public void run() {\r
- try {\r
- System.out.println("Activating sheet: model=" + model + " rvi=" + rvi);\r
- WorkbenchUtils.openEditor(EDITOR_ID, new ResourceEditorInput2(EDITOR_ID, data, model, rvi));\r
- } catch (PartInitException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
- }\r
- });\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- \r
- return true;\r
- }\r
-\r
-\r
-}\r
+package org.simantics.sysdyn.ui.browser.nodes;
+
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.RVI;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.ui.utils.SheetNameValidator;
+import org.simantics.ui.workbench.ResourceEditorInput2;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+public class SheetNode extends AbstractNode<Resource> implements IModifiableNode, IDoubleClickableNode {
+
+ public SheetNode(Resource data) {
+ super(data);
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+
+ Session session = Simantics.getSession();
+ LabelModifier modifier = new LabelModifier(session, data, session.getService(Layer0.class).HasName) {
+ @Override
+ public String isValid(String label) {
+ if (!new SheetNameValidator().isValid(data, label))
+ return "Not valid";
+ else
+ return null;
+ }
+ };
+ return modifier;
+ }
+
+ @Override
+ public boolean handleDoubleClick() {
+
+ try {
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+
+ Variable variable = graph.adapt(data, Variable.class);
+ final Resource model = Variables.getModel(graph, variable);
+ final RVI rvi = variable.getRVI(graph);
+
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+
+ private static final String EDITOR_ID = "org.simantics.spreadsheet.ui.editor2";
+
+ @Override
+ public void run() {
+ try {
+ System.out.println("Activating sheet: model=" + model + " rvi=" + rvi);
+ WorkbenchUtils.openEditor(EDITOR_ID, new ResourceEditorInput2(EDITOR_ID, data, model, rvi));
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+ }
+ });
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return true;
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import java.io.File;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.handlers.ToggleResultActivation;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class SimulationResultNode<T> extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {\r
-\r
- public SimulationResultNode(Resource resource) {\r
- super(resource);\r
- }\r
- \r
- \r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
- @Override\r
- public String isValid(String label) {\r
- if (label.isEmpty())\r
- return "Empty label not allowed";\r
- return null;\r
- }\r
- };\r
- return modifier;\r
- }\r
-\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- unlinkResult(graph, data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- }\r
- \r
- }\r
- \r
- \r
- public static void unlinkResult(WriteGraph graph, Resource result) throws DatabaseException {\r
- deleteResultFiles(graph, result);\r
- RemoverUtil.remove(graph, result);\r
- }\r
- \r
- public static void deleteResultFiles(WriteGraph graph, Resource result) throws DatabaseException {\r
- String path;\r
- path = graph.getPossibleRelatedValue(result, SysdynResource.getInstance(graph).Result_resultFile);\r
- if(path != null) {\r
- File file = new File(path);\r
- file.delete();\r
- File parent = file.getParentFile();\r
- if(parent.listFiles() != null && parent.listFiles().length == 0)\r
- parent.delete();\r
- }\r
- }\r
-\r
-\r
- @Override\r
- public boolean handleDoubleClick() {\r
- Resource[] resources = {data};\r
- ToggleResultActivation.toggleActivation(resources);\r
- return true;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.browser.nodes;
+
+import java.io.File;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.handlers.ToggleResultActivation;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class SimulationResultNode<T> extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {
+
+ public SimulationResultNode(Resource resource) {
+ super(resource);
+ }
+
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), data) {
+ @Override
+ public String isValid(String label) {
+ if (label.isEmpty())
+ return "Empty label not allowed";
+ return null;
+ }
+ };
+ return modifier;
+ }
+
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ unlinkResult(graph, data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
+
+ public static void unlinkResult(WriteGraph graph, Resource result) throws DatabaseException {
+ deleteResultFiles(graph, result);
+ RemoverUtil.remove(graph, result);
+ }
+
+ public static void deleteResultFiles(WriteGraph graph, Resource result) throws DatabaseException {
+ String path;
+ path = graph.getPossibleRelatedValue(result, SysdynResource.getInstance(graph).Result_resultFile);
+ if(path != null) {
+ File file = new File(path);
+ file.delete();
+ File parent = file.getParentFile();
+ if(parent.listFiles() != null && parent.listFiles().length == 0)
+ parent.delete();
+ }
+ }
+
+
+ @Override
+ public boolean handleDoubleClick() {
+ Resource[] resources = {data};
+ ToggleResultActivation.toggleActivation(resources);
+ return true;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IDoubleClickableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.handlers.ToggleResultSetActivation;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class SimulationResultSetNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {\r
-\r
- public SimulationResultSetNode(Resource resource) {\r
- super(resource);\r
- }\r
- \r
- \r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data) {\r
- @Override\r
- public String isValid(String label) {\r
- if (label.isEmpty())\r
- return "Empty label not allowed";\r
- return null;\r
- }\r
- };\r
- return modifier;\r
- }\r
-\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- unlinkResultSet(graph, data);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- }\r
- \r
- }\r
- \r
- \r
- public static void unlinkResultSet(WriteGraph graph, Resource resultSet) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for (Resource result : graph.syncRequest(new ObjectsWithType(resultSet, sr.Experiment_result, sr.Result))) {\r
- SimulationResultNode.unlinkResult(graph, result);\r
- }\r
- RemoverUtil.remove(graph, resultSet);\r
- }\r
-\r
- @Override\r
- public boolean handleDoubleClick() {\r
- Resource[] resources = {data};\r
- ToggleResultSetActivation.toggleActivation(resources);\r
- return true;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IDoubleClickableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.handlers.ToggleResultSetActivation;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class SimulationResultSetNode extends AbstractNode<Resource> implements IDoubleClickableNode, IDeletableNode, IModifiableNode {
+
+ public SimulationResultSetNode(Resource resource) {
+ super(resource);
+ }
+
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), data) {
+ @Override
+ public String isValid(String label) {
+ if (label.isEmpty())
+ return "Empty label not allowed";
+ return null;
+ }
+ };
+ return modifier;
+ }
+
+
+ @Override
+ public void delete() throws DeleteException {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ unlinkResultSet(graph, data);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+
+
+ public static void unlinkResultSet(WriteGraph graph, Resource resultSet) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for (Resource result : graph.syncRequest(new ObjectsWithType(resultSet, sr.Experiment_result, sr.Result))) {
+ SimulationResultNode.unlinkResult(graph, result);
+ }
+ RemoverUtil.remove(graph, resultSet);
+ }
+
+ @Override
+ public boolean handleDoubleClick() {
+ Resource[] resources = {data};
+ ToggleResultSetActivation.toggleActivation(resources);
+ return true;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser.nodes;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class VariableNode<T> extends AbstractNode<Resource> implements IModifiableNode {\r
-\r
- Variable variable;\r
-\r
- public VariableNode(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- public VariableNode(Variable variable, Resource represents) {\r
- super(represents);\r
- this.variable = variable;\r
- }\r
-\r
- public Variable getVariable() {\r
- return variable;\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- try {\r
- final Session session = SimanticsUI.getSession();\r
- Resource hasName = Layer0.getInstance(session).HasName;\r
- LabelModifier modifier = new LabelModifier(session, data, hasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (!new VariableNameValidator().isValid(data, label))\r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
- \r
- @Override\r
- public void modify(final String label) {\r
- try {\r
- session.syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph)\r
- throws DatabaseException {\r
-\r
- String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);\r
- if(!originalName.equals(label)) {\r
- Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);\r
- new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);\r
- graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- super.modify(label);\r
- }\r
- };\r
- return modifier;\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return null;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.browser.nodes;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;
+
+public class VariableNode<T> extends AbstractNode<Resource> implements IModifiableNode {
+
+ Variable variable;
+
+ public VariableNode(Resource resource) {
+ super(resource);
+ }
+
+ public VariableNode(Variable variable, Resource represents) {
+ super(represents);
+ this.variable = variable;
+ }
+
+ public Variable getVariable() {
+ return variable;
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ try {
+ final Session session = Simantics.getSession();
+ Resource hasName = Layer0.getInstance(session).HasName;
+ LabelModifier modifier = new LabelModifier(session, data, hasName) {
+ @Override
+ public String isValid(String label) {
+ if (!new VariableNameValidator().isValid(data, label))
+ return "Not valid";
+ else
+ return null;
+ }
+
+ @Override
+ public void modify(final String label) {
+ try {
+ session.syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph)
+ throws DatabaseException {
+
+ String originalName = graph.getRelatedValue(data, Layer0.getInstance(graph).HasName);
+ if(!originalName.equals(label)) {
+ Resource configuration = graph.getPossibleObject(data, Layer0.getInstance(graph).PartOf);
+ new VariableNameValidator().renameInAllEquations(graph, configuration, originalName, label);
+ graph.claimLiteral(data, Layer0.getInstance(graph).HasName, label);
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ super.modify(label);
+ }
+ };
+ return modifier;
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.editor;\r
-\r
-import org.eclipse.ui.PartInitException;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.ResourceArray;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.modeling.ComponentUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.modeling.ui.Activator;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.structural2.StructuralVariables;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.workbench.ResourceEditorInput2;\r
-import org.simantics.ui.workbench.editor.AbstractResourceEditorAdapter;\r
-import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
-\r
-public class OpenDiagramFromConfigurationAdapter extends AbstractResourceEditorAdapter {\r
-\r
- private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";\r
-\r
- public OpenDiagramFromConfigurationAdapter() {\r
- super("Diagram Editor", Activator.COMPOSITE_ICON);\r
- }\r
-\r
- protected String getEditorId() {\r
- return EDITOR_ID;\r
- }\r
-\r
- @Override\r
- public boolean canHandle(ReadGraph g, Resource r) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- if(g.isInheritedFrom(r, sr.ModuleSymbol)) {\r
- ModelingResources mr = ModelingResources.getInstance(g);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
- Resource componentType = g.getSingleObject(r, mr.SymbolToComponentType);\r
- r = g.getSingleObject(componentType, sr2.IsDefinedBy);\r
- }\r
- Layer0X L0X = Layer0X.getInstance(g);\r
- Resource represents = g.getPossibleObject(r, L0X.Represents);\r
- if(represents != null){\r
- if(g.isInstanceOf(represents, sr.Configuration)) {\r
- r = represents;\r
- }\r
- }\r
- return ComponentUtils.compositeHasDiagram(g, r) /*|| ComponentUtils.componentHasDiagram(g, r)*/;\r
- }\r
-\r
- @Override\r
- public void openEditor(final Resource r) throws Exception {\r
-\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph g) throws DatabaseException {\r
- Resource cr = r;\r
- Layer0X L0X = Layer0X.getInstance(g);\r
- if(g.isInheritedFrom(r, SysdynResource.getInstance(g).ModuleSymbol)) {\r
- ModelingResources mr = ModelingResources.getInstance(g);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
- Resource componentType = g.getSingleObject(r, mr.SymbolToComponentType);\r
- Resource configuration = g.getSingleObject(componentType, sr2.IsDefinedBy);\r
- cr = configuration;\r
- } else { \r
- Resource represents = g.getPossibleObject(r, L0X.Represents);\r
- if(represents != null && g.isInstanceOf(represents, SysdynResource.getInstance(g).Configuration)){\r
- cr = represents;\r
- } else {\r
- cr = r;\r
- }\r
- }\r
-\r
- \r
- final Resource diagram = ComponentUtils.getPossibleCompositeDiagram(g, cr);\r
- if(diagram == null) return;\r
- final ResourceArray compositePath = StructuralVariables.getCompositeArray(g, cr);\r
- final ResourceArray variablePath = compositePath.removeFromBeginning(1);\r
-\r
- final Resource model = StructuralVariables.getModel(g, compositePath.head());\r
- if(model == null) return;\r
-\r
- \r
- \r
- final String rvi = StructuralVariables.getRVI(g, variablePath);\r
- if(rvi == null) return;\r
-\r
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
- @Override\r
- public void run() {\r
- try {\r
- String editorId = getEditorId();\r
-// System.out.println("Activating diagram: model=" + modelURI + " rvi='" + rvi + "'");\r
- WorkbenchUtils.openEditor(editorId, new ResourceEditorInput2(editorId, diagram, model, rvi));\r
- } catch (PartInitException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
-\r
- }\r
-\r
- });\r
-\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.editor;
+
+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.ResourceArray;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.modeling.ComponentUtils;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.modeling.ui.Activator;
+import org.simantics.operation.Layer0X;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.structural2.StructuralVariables;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.ui.workbench.ResourceEditorInput2;
+import org.simantics.ui.workbench.editor.AbstractResourceEditorAdapter;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+public class OpenDiagramFromConfigurationAdapter extends AbstractResourceEditorAdapter {
+
+ private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";
+
+ public OpenDiagramFromConfigurationAdapter() {
+ super("Diagram Editor", Activator.COMPOSITE_ICON);
+ }
+
+ protected static String getEditorId() {
+ return EDITOR_ID;
+ }
+
+ @Override
+ public boolean canHandle(ReadGraph g, Resource r) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ if(g.isInheritedFrom(r, sr.ModuleSymbol)) {
+ ModelingResources mr = ModelingResources.getInstance(g);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(g);
+ Resource componentType = g.getSingleObject(r, mr.SymbolToComponentType);
+ r = g.getSingleObject(componentType, sr2.IsDefinedBy);
+ }
+ Layer0X L0X = Layer0X.getInstance(g);
+ Resource represents = g.getPossibleObject(r, L0X.Represents);
+ if(represents != null){
+ if(g.isInstanceOf(represents, sr.Configuration)) {
+ r = represents;
+ }
+ }
+ return ComponentUtils.compositeHasDiagram(g, r) /*|| ComponentUtils.componentHasDiagram(g, r)*/;
+ }
+
+ @Override
+ public void openEditor(final Resource r) throws Exception {
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph g) throws DatabaseException {
+ openEditorHandler(g, r);
+ }
+ });
+ }
+
+ public static void openEditorHandler(ReadGraph g, final Resource r) throws DatabaseException {
+ Resource cr = r;
+ Layer0X L0X = Layer0X.getInstance(g);
+ if(g.isInheritedFrom(r, SysdynResource.getInstance(g).ModuleSymbol)) {
+ ModelingResources mr = ModelingResources.getInstance(g);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(g);
+ Resource componentType = g.getSingleObject(r, mr.SymbolToComponentType);
+ Resource configuration = g.getSingleObject(componentType, sr2.IsDefinedBy);
+ cr = configuration;
+ } else {
+ Resource represents = g.getPossibleObject(r, L0X.Represents);
+ if(represents != null && g.isInstanceOf(represents, SysdynResource.getInstance(g).Configuration)){
+ cr = represents;
+ } else {
+ cr = r;
+ }
+ }
+
+ final Resource diagram = ComponentUtils.getPossibleCompositeDiagram(g, cr);
+ if(diagram == null) return;
+ final ResourceArray compositePath = StructuralVariables.getCompositeArray(g, cr);
+ final ResourceArray variablePath = compositePath.removeFromBeginning(1);
+
+ final Resource model = StructuralVariables.getModel(g, compositePath.head());
+ if(model == null) return;
+
+ final String rvi = StructuralVariables.getRVI(g, variablePath);
+ if(rvi == null) return;
+
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ String editorId = getEditorId();
+ WorkbenchUtils.openEditor(editorId, new ResourceEditorInput2(editorId, diagram, model, rvi));
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+ }
+}
-package org.simantics.sysdyn.ui.editor;\r
-\r
-import org.eclipse.core.runtime.IAdaptable;\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.ui.IMemento;\r
-import org.eclipse.ui.IPersistableElement;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.RequestProcessor;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.common.ResourceArray;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.AdaptionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ResourceNotFoundException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.db.service.LifecycleSupport;\r
-import org.simantics.db.service.SerialisationSupport;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.icons.ImageDescriptorProvider;\r
-import org.simantics.ui.workbench.ResourceEditorInput2;\r
-import org.simantics.ui.workbench.ResourceEditorInputFactory2;\r
-import org.simantics.ui.workbench.TitleRequest;\r
-import org.simantics.ui.workbench.ToolTipRequest;\r
-import org.simantics.utils.ObjectUtils;\r
-import org.simantics.utils.datastructures.cache.ProvisionException;\r
-import org.simantics.utils.ui.ErrorLogger;\r
-import org.simantics.utils.ui.workbench.StringMemento;\r
-\r
-/**\r
- * TEMPORARY fix to support sysdyn\r
- * \r
- * @author tlteemu\r
- *\r
- */\r
-public class SysdynEditorInput extends ResourceEditorInput2 {\r
- \r
- private final static boolean DEBUG_UPDATE = false;\r
-\r
- private static final String NO_NAME = "(no name)";\r
-\r
- private final String editorID;\r
-\r
- private String randomAccessResourceId;\r
-\r
- private transient Resource resource;\r
-\r
- /**\r
- * Gotten from the editor that needs to initialize this input. Currently\r
- * needed for two things: {@link #exists()} and {@link #saveState(IMemento)}.\r
- */\r
- private transient Session session;\r
-\r
- private transient boolean exists;\r
-\r
- private transient String name;\r
-\r
- private transient String tooltip;\r
-\r
- private transient ImageDescriptor imageDesc;\r
-\r
- /** Persistent memento for external data */\r
- private final StringMemento persistentStore = new StringMemento();\r
-\r
- /**\r
- * @param editorID\r
- * @param r\r
- */\r
- public SysdynEditorInput(String editorID, Resource r, Resource model, String rvi) {\r
- super(editorID, r, model, rvi);\r
- if (editorID == null)\r
- throw new IllegalArgumentException("null editor id");\r
- if (r == null)\r
- throw new IllegalArgumentException("null resource");\r
-\r
- this.editorID = editorID;\r
- this.randomAccessResourceId = "";\r
- this.resource = r;\r
- this.rvi = rvi;\r
- this.session = SimanticsUI.getSession();\r
-\r
- ensureRandomAccessId();\r
- setNonExistant();\r
- }\r
-\r
- void ensureRandomAccessId() {\r
- if (resource == null)\r
- throw new IllegalStateException("resource is null, input is disposed");\r
- // Make sure that the resource has a random access id\r
- try {\r
- SerialisationSupport support = session.getService(SerialisationSupport.class);\r
- randomAccessResourceId = String.valueOf(support.getRandomAccessId(resource));\r
- } catch (DatabaseException e) {\r
- throw new RuntimeException(e);\r
- }\r
- }\r
-\r
- @Override\r
- public void init(IAdaptable adapter) throws DatabaseException {\r
- if (resource == null && randomAccessResourceId != null) {\r
- getSession().syncRequest(new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph g) throws DatabaseException {\r
- try {\r
- long id = Long.parseLong(randomAccessResourceId);\r
- resource = g.getService(SerialisationSupport.class).getResource(id);\r
- update(g);\r
- } catch (NumberFormatException e) {\r
- setNonExistant();\r
- } catch (DatabaseException e) {\r
- setNonExistant();\r
- }\r
- }\r
- });\r
- } else {\r
- if (resource != null) {\r
- updateCaches(getSession(), true);\r
- }\r
- }\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- //System.out.println("dispose resource editor input: " + name);\r
- // NOTE: this has to be done since Eclipse will cache these IEditorInput\r
- // instances within EditorHistoryItem's that are stored in an EditorHistory\r
- // instance. They are held by strong reference which means that the session\r
- // cannot be collected if it is not nulled here.\r
- session = null;\r
- resource = null;\r
- }\r
-\r
- /**\r
- * @return a graph instance if it exists and has not yet been disposed,\r
- * <code>null</code> otherwise\r
- */\r
- public Session getSession() {\r
- // TODO: also throw an exception if the session is disposed\r
- if (session == null)\r
- throw new IllegalStateException("session is disposed");\r
- return session;\r
- }\r
-\r
- @Override\r
- public boolean exists() {\r
- return exists;\r
- }\r
-\r
- @Override\r
- public boolean exists(ReadGraph graph) throws DatabaseException {\r
- try {\r
- assertExists(graph);\r
- return true;\r
- } catch (ResourceNotFoundException e) {\r
- } catch (Nonexistant e) {\r
- }\r
- return false;\r
- }\r
-\r
- @Override\r
- public Resource getResource() {\r
- return resource;\r
- }\r
-\r
- @Override\r
- @Deprecated\r
- public ResourceArray getResourceArray() {\r
- return new ResourceArray(resource);\r
- }\r
-\r
- @Override\r
- public String getRVI() {\r
- return rvi;\r
- }\r
-\r
- /* (non-Javadoc)\r
- * @see org.eclipse.ui.IEditorInput#getImageDescriptor()\r
- */\r
- @Override\r
- public ImageDescriptor getImageDescriptor() {\r
- return imageDesc;\r
- }\r
-\r
- /* (non-Javadoc)\r
- * @see org.eclipse.ui.IEditorInput#getName()\r
- */\r
- @Override\r
- public String getName() {\r
- return name;\r
- }\r
-\r
- /* (non-Javadoc)\r
- * @see org.eclipse.ui.IEditorInput#getToolTipText()\r
- */\r
- @Override\r
- public String getToolTipText() {\r
- return tooltip;\r
- }\r
-\r
- /* (non-Javadoc)\r
- * @see org.eclipse.ui.IEditorInput#getPersistable()\r
- */\r
- @Override\r
- public IPersistableElement getPersistable() {\r
- // Don't allow persistability when it's not possible.\r
- if (!isPersistable())\r
- return null;\r
- return this;\r
- }\r
-\r
- protected boolean isPersistable() {\r
- if (session == null)\r
- return false;\r
- LifecycleSupport lc = session.peekService(LifecycleSupport.class);\r
- if (lc == null)\r
- return false;\r
- if (lc.isClosed())\r
- return false;\r
- return true;\r
- }\r
-\r
- /* (non-Javadoc)\r
- * @see org.eclipse.ui.IPersistableElement#getFactoryId()\r
- */\r
- @Override\r
- public String getFactoryId() {\r
- return ResourceEditorInputFactory2.getFactoryId();\r
- }\r
-\r
- /**\r
- * Saves the state of the given resource editor input into the given memento.\r
- *\r
- * @param memento the storage area for element state\r
- * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)\r
- */\r
- @Override\r
- public void saveState(IMemento memento) {\r
-// List<String> ids = randomAccessResourceId;\r
- if (randomAccessResourceId == null) {\r
- // Must create a new random access ID.\r
- ensureRandomAccessId();\r
- }\r
- IMemento child = memento.createChild(ResourceEditorInputFactory2.TAG_RESOURCE_ID);\r
- child.putTextData(randomAccessResourceId);\r
- memento.putString(ResourceEditorInputFactory2.TAG_EDITOR_ID, editorID);\r
-// memento.putString(ResourceEditorInputFactory2.TAG_MODEL_URI, modelURI);\r
- memento.putString(ResourceEditorInputFactory2.TAG_MODEL_ID, modelId);\r
- memento.putString(ResourceEditorInputFactory2.TAG_RVI, rvi);\r
- memento.putString(ResourceEditorInputFactory2.TAG_EXTERNAL_MEMENTO_ID, persistentStore.toString());\r
- }\r
-\r
- /* (non-Javadoc)\r
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)\r
- */\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public Object getAdapter(Class adapter) {\r
- //System.out.println("[ResourceEditorInput] getAdapter: " + adapter.getName());\r
- return null;\r
- }\r
-\r
-\r
- @Override\r
- public int hashCode() {\r
- final int prime = 31;\r
- int result = 1;\r
- result = prime * result + editorID.hashCode();\r
- result = prime * result + ObjectUtils.hashCode(modelId);\r
- result = prime * result + ObjectUtils.hashCode(rvi);\r
- result = prime * result + ObjectUtils.hashCode(randomAccessResourceId);\r
- return result;\r
- }\r
-\r
- private void updateCaches(RequestProcessor processor, boolean sync) throws DatabaseException {\r
- ReadRequest req = new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph g) throws DatabaseException {\r
- update(g);\r
- }\r
- };\r
- if (sync) {\r
- processor.syncRequest(req);\r
- } else {\r
- processor.asyncRequest(req);\r
- }\r
- }\r
-\r
- static class Nonexistant extends DatabaseException {\r
- private static final long serialVersionUID = -7964385375237203651L;\r
-\r
- @Override\r
- public synchronized Throwable fillInStackTrace() {\r
- return this;\r
- }\r
- }\r
-\r
- /* (non-Javadoc)\r
- * @see org.simantics.ui.workbench.IResourceEditorInput#update(org.simantics.db.Graph)\r
- */\r
- @Override\r
- public void update(ReadGraph g) throws DatabaseException {\r
- Resource r = getResource();\r
- if (r == null)\r
- return;\r
-\r
- if (DEBUG_UPDATE)\r
- System.out.println("update(" + this + ")");\r
-\r
- try {\r
- assertExists(g);\r
-\r
- name = g.syncRequest(new TitleRequest(editorID, this));\r
- if (name == null)\r
- name = NO_NAME;\r
-\r
- tooltip = g.syncRequest(new ToolTipRequest(editorID, this));\r
- if (tooltip == null)\r
- tooltip = NO_NAME;\r
-\r
- try {\r
- ImageDescriptorProvider idp = g.adapt(r, ImageDescriptorProvider.class);\r
- imageDesc = idp.get();\r
- } catch (AdaptionException e) {\r
- imageDesc = ImageDescriptor.getMissingImageDescriptor();\r
- } catch (ProvisionException e) {\r
- imageDesc = ImageDescriptor.getMissingImageDescriptor();\r
- ErrorLogger.defaultLogError(e);\r
- }\r
-\r
- if (DEBUG_UPDATE)\r
- System.out.println("update(" + this + ") finished");\r
- } catch (DatabaseException e) {\r
- if (DEBUG_UPDATE)\r
- e.printStackTrace();\r
- setNonExistant();\r
- }\r
- }\r
-\r
- private void assertExists(ReadGraph g) throws DatabaseException {\r
- Resource r = getResource();\r
- if (r == null)\r
- throw new Nonexistant();\r
-\r
- // 1. Check resource existence\r
- boolean exists = g.hasStatement(r);\r
- if (!exists)\r
- throw new Nonexistant();\r
-\r
- // 2. Validate modelURI\r
- if (getModel(g) != null && g.getPossibleURI(getModel(g)) != null) {\r
- Layer0X L0X = Layer0X.getInstance(g);\r
- \r
- // 3. Validate RVI\r
- Resource model = getModel(g);\r
- Resource baseRealization = g.getPossibleObject(model, L0X.HasBaseRealization);\r
- Variable modelVariable = Variables.getVariable(g, g.getURI(baseRealization));\r
- modelVariable.browse(g, getRVI());\r
- }\r
-\r
- // Touch the diagram title calculation within this existence\r
- // checking request.\r
- g.syncRequest(new TitleRequest(editorID, this));\r
- }\r
-\r
- private void setNonExistant() {\r
- if (DEBUG_UPDATE)\r
- System.out.println("setNonExistant(" + this + " @ " + System.identityHashCode(this) + ")");\r
-\r
- exists = false;\r
- tooltip = name = NO_NAME;\r
- imageDesc = ImageDescriptor.getMissingImageDescriptor();\r
- }\r
-\r
- public IMemento getPersistentStore() {\r
- return persistentStore;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return getClass().getSimpleName() + " [name=" + getName() + ", resource=" + resource + "]";\r
- }\r
- \r
-\r
-\r
-}\r
+package org.simantics.sysdyn.ui.editor;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.IMemento;
+import org.eclipse.ui.IPersistableElement;
+import org.simantics.Simantics;
+import org.simantics.db.AsyncRequestProcessor;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.common.ResourceArray;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.exception.AdaptionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.ResourceNotFoundException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.service.LifecycleSupport;
+import org.simantics.db.service.SerialisationSupport;
+import org.simantics.operation.Layer0X;
+import org.simantics.ui.icons.ImageDescriptorProvider;
+import org.simantics.ui.workbench.ResourceEditorInput2;
+import org.simantics.ui.workbench.ResourceEditorInputFactory2;
+import org.simantics.ui.workbench.TitleRequest;
+import org.simantics.ui.workbench.ToolTipRequest;
+import org.simantics.utils.ObjectUtils;
+import org.simantics.utils.datastructures.cache.ProvisionException;
+import org.simantics.utils.ui.ErrorLogger;
+import org.simantics.utils.ui.workbench.StringMemento;
+
+/**
+ * TEMPORARY fix to support sysdyn
+ *
+ * @author tlteemu
+ *
+ */
+public class SysdynEditorInput extends ResourceEditorInput2 {
+
+ private final static boolean DEBUG_UPDATE = false;
+
+ private static final String NO_NAME = "(no name)";
+
+ private final String editorID;
+
+ private String randomAccessResourceId;
+
+ private transient Resource resource;
+
+ /**
+ * Gotten from the editor that needs to initialize this input. Currently
+ * needed for two things: {@link #exists()} and {@link #saveState(IMemento)}.
+ */
+ private transient Session session;
+
+ private transient boolean exists;
+
+ private transient String name;
+
+ private transient String tooltip;
+
+ private transient ImageDescriptor imageDesc;
+
+ /** Persistent memento for external data */
+ private final StringMemento persistentStore = new StringMemento();
+
+ /**
+ * @param editorID
+ * @param r
+ */
+ public SysdynEditorInput(String editorID, Resource r, Resource model, String rvi) {
+ super(editorID, r, model, rvi);
+ if (editorID == null)
+ throw new IllegalArgumentException("null editor id");
+ if (r == null)
+ throw new IllegalArgumentException("null resource");
+
+ this.editorID = editorID;
+ this.randomAccessResourceId = "";
+ this.resource = r;
+ this.rvi = rvi;
+ this.session = Simantics.getSession();
+
+ ensureRandomAccessId();
+ setNonExistant();
+ }
+
+ void ensureRandomAccessId() {
+ if (resource == null)
+ throw new IllegalStateException("resource is null, input is disposed");
+ // Make sure that the resource has a random access id
+ try {
+ SerialisationSupport support = session.getService(SerialisationSupport.class);
+ randomAccessResourceId = String.valueOf(support.getRandomAccessId(resource));
+ } catch (DatabaseException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void init(IAdaptable adapter) throws DatabaseException {
+ if (resource == null && randomAccessResourceId != null) {
+ getSession().syncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph g) throws DatabaseException {
+ try {
+ long id = Long.parseLong(randomAccessResourceId);
+ resource = g.getService(SerialisationSupport.class).getResource(id);
+ update(g);
+ } catch (NumberFormatException e) {
+ setNonExistant();
+ } catch (DatabaseException e) {
+ setNonExistant();
+ }
+ }
+ });
+ } else {
+ if (resource != null) {
+ updateCaches(getSession(), true);
+ }
+ }
+ }
+
+ @Override
+ public void dispose() {
+ //System.out.println("dispose resource editor input: " + name);
+ // NOTE: this has to be done since Eclipse will cache these IEditorInput
+ // instances within EditorHistoryItem's that are stored in an EditorHistory
+ // instance. They are held by strong reference which means that the session
+ // cannot be collected if it is not nulled here.
+ session = null;
+ resource = null;
+ }
+
+ /**
+ * @return a graph instance if it exists and has not yet been disposed,
+ * <code>null</code> otherwise
+ */
+ public Session getSession() {
+ // TODO: also throw an exception if the session is disposed
+ if (session == null)
+ throw new IllegalStateException("session is disposed");
+ return session;
+ }
+
+ @Override
+ public boolean exists() {
+ return exists;
+ }
+
+ @Override
+ public boolean exists(ReadGraph graph) throws DatabaseException {
+ try {
+ assertExists(graph);
+ return true;
+ } catch (ResourceNotFoundException e) {
+ } catch (Nonexistant e) {
+ }
+ return false;
+ }
+
+ @Override
+ public Resource getResource() {
+ return resource;
+ }
+
+ @Override
+ @Deprecated
+ public ResourceArray getResourceArray() {
+ return new ResourceArray(resource);
+ }
+
+ @Override
+ public String getRVI() {
+ return rvi;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IEditorInput#getImageDescriptor()
+ */
+ @Override
+ public ImageDescriptor getImageDescriptor() {
+ return imageDesc;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IEditorInput#getName()
+ */
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IEditorInput#getToolTipText()
+ */
+ @Override
+ public String getToolTipText() {
+ return tooltip;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IEditorInput#getPersistable()
+ */
+ @Override
+ public IPersistableElement getPersistable() {
+ // Don't allow persistability when it's not possible.
+ if (!isPersistable())
+ return null;
+ return this;
+ }
+
+ protected boolean isPersistable() {
+ if (session == null)
+ return false;
+ LifecycleSupport lc = session.peekService(LifecycleSupport.class);
+ if (lc == null)
+ return false;
+ if (lc.isClosed())
+ return false;
+ return true;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.ui.IPersistableElement#getFactoryId()
+ */
+ @Override
+ public String getFactoryId() {
+ return ResourceEditorInputFactory2.getFactoryId();
+ }
+
+ /**
+ * Saves the state of the given resource editor input into the given memento.
+ *
+ * @param memento the storage area for element state
+ * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)
+ */
+ @Override
+ public void saveState(IMemento memento) {
+// List<String> ids = randomAccessResourceId;
+ if (randomAccessResourceId == null) {
+ // Must create a new random access ID.
+ ensureRandomAccessId();
+ }
+ IMemento child = memento.createChild(ResourceEditorInputFactory2.TAG_RESOURCE_ID);
+ child.putTextData(randomAccessResourceId);
+ memento.putString(ResourceEditorInputFactory2.TAG_EDITOR_ID, editorID);
+// memento.putString(ResourceEditorInputFactory2.TAG_MODEL_URI, modelURI);
+ memento.putString(ResourceEditorInputFactory2.TAG_MODEL_ID, modelId);
+ memento.putString(ResourceEditorInputFactory2.TAG_RVI, rvi);
+ memento.putString(ResourceEditorInputFactory2.TAG_EXTERNAL_MEMENTO_ID, persistentStore.toString());
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
+ */
+ @Override
+ public <T> T getAdapter(Class<T> adapter) {
+ //System.out.println("[ResourceEditorInput] getAdapter: " + adapter.getName());
+ return null;
+ }
+
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + editorID.hashCode();
+ result = prime * result + ObjectUtils.hashCode(modelId);
+ result = prime * result + ObjectUtils.hashCode(rvi);
+ result = prime * result + ObjectUtils.hashCode(randomAccessResourceId);
+ return result;
+ }
+
+ private void updateCaches(AsyncRequestProcessor processor, boolean sync) throws DatabaseException {
+ ReadRequest req = new ReadRequest() {
+ @Override
+ public void run(ReadGraph g) throws DatabaseException {
+ update(g);
+ }
+ };
+ if (sync) {
+ processor.getSession().syncRequest(req);
+ } else {
+ processor.asyncRequest(req);
+ }
+ }
+
+ static class Nonexistant extends DatabaseException {
+ private static final long serialVersionUID = -7964385375237203651L;
+
+ @Override
+ public synchronized Throwable fillInStackTrace() {
+ return this;
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.simantics.ui.workbench.IResourceEditorInput#update(org.simantics.db.Graph)
+ */
+ @Override
+ public void update(ReadGraph g) throws DatabaseException {
+ Resource r = getResource();
+ if (r == null)
+ return;
+
+ if (DEBUG_UPDATE)
+ System.out.println("update(" + this + ")");
+
+ try {
+ assertExists(g);
+
+ name = g.syncRequest(new TitleRequest(editorID, this));
+ if (name == null)
+ name = NO_NAME;
+
+ tooltip = g.syncRequest(new ToolTipRequest(editorID, this));
+ if (tooltip == null)
+ tooltip = NO_NAME;
+
+ try {
+ ImageDescriptorProvider idp = g.adapt(r, ImageDescriptorProvider.class);
+ imageDesc = idp.get();
+ } catch (AdaptionException e) {
+ imageDesc = ImageDescriptor.getMissingImageDescriptor();
+ } catch (ProvisionException e) {
+ imageDesc = ImageDescriptor.getMissingImageDescriptor();
+ ErrorLogger.defaultLogError(e);
+ }
+
+ if (DEBUG_UPDATE)
+ System.out.println("update(" + this + ") finished");
+ } catch (DatabaseException e) {
+ if (DEBUG_UPDATE)
+ e.printStackTrace();
+ setNonExistant();
+ }
+ }
+
+ private void assertExists(ReadGraph g) throws DatabaseException {
+ Resource r = getResource();
+ if (r == null)
+ throw new Nonexistant();
+
+ // 1. Check resource existence
+ boolean exists = g.hasStatement(r);
+ if (!exists)
+ throw new Nonexistant();
+
+ // 2. Validate modelURI
+ if (getModel(g) != null && g.getPossibleURI(getModel(g)) != null) {
+ Layer0X L0X = Layer0X.getInstance(g);
+
+ // 3. Validate RVI
+ Resource model = getModel(g);
+ Resource baseRealization = g.getPossibleObject(model, L0X.HasBaseRealization);
+ Variable modelVariable = Variables.getVariable(g, g.getURI(baseRealization));
+ modelVariable.browse(g, getRVI());
+ }
+
+ // Touch the diagram title calculation within this existence
+ // checking request.
+ g.syncRequest(new TitleRequest(editorID, this));
+ }
+
+ private void setNonExistant() {
+ if (DEBUG_UPDATE)
+ System.out.println("setNonExistant(" + this + " @ " + System.identityHashCode(this) + ")");
+
+ exists = false;
+ tooltip = name = NO_NAME;
+ imageDesc = ImageDescriptor.getMissingImageDescriptor();
+ }
+
+ public IMemento getPersistentStore() {
+ return persistentStore;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + " [name=" + getName() + ", resource=" + resource + "]";
+ }
+
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.editor.participant;\r
-\r
-import java.awt.geom.AffineTransform;\r
-import java.awt.geom.Point2D;\r
-import java.util.Set;\r
-import java.util.function.Consumer;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.Queries;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;\r
-import org.simantics.diagram.elements.TextNode;\r
-import org.simantics.diagram.query.DiagramRequests;\r
-import org.simantics.g2d.canvas.Hints;\r
-import org.simantics.g2d.canvas.SGDesignation;\r
-import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;\r
-import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;\r
-import org.simantics.g2d.diagram.DiagramHints;\r
-import org.simantics.g2d.diagram.DiagramMutator;\r
-import org.simantics.g2d.diagram.DiagramUtils;\r
-import org.simantics.g2d.diagram.IDiagram;\r
-import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;\r
-import org.simantics.g2d.diagram.participant.ElementPainter;\r
-import org.simantics.g2d.diagram.participant.Selection;\r
-import org.simantics.g2d.element.ElementClass;\r
-import org.simantics.g2d.element.ElementUtils;\r
-import org.simantics.g2d.element.IElement;\r
-import org.simantics.g2d.participant.MouseUtil;\r
-import org.simantics.g2d.participant.MouseUtil.MouseInfo;\r
-import org.simantics.scenegraph.g2d.G2DParentNode;\r
-import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;\r
-import org.simantics.scenegraph.g2d.events.KeyEvent;\r
-import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;\r
-import org.simantics.scenegraph.g2d.events.KeyEvent.KeyReleasedEvent;\r
-import org.simantics.scenegraph.g2d.events.MouseEvent;\r
-import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;\r
-import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.elements.AuxiliaryFactory;\r
-import org.simantics.sysdyn.ui.elements.CloudFactory;\r
-import org.simantics.sysdyn.ui.elements.InputFactory;\r
-import org.simantics.sysdyn.ui.elements.LoopFactory;\r
-import org.simantics.sysdyn.ui.elements.ShadowFactory;\r
-import org.simantics.sysdyn.ui.elements.StockFactory;\r
-import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
-import org.simantics.sysdyn.ui.elements.ValveFactory;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class CreateVariablesShortcutParticipant extends AbstractDiagramParticipant {\r
-\r
- private GraphToDiagramSynchronizer synchronizer;\r
-\r
- private VariableInformation variableInformation;\r
-\r
- @Dependency\r
- MouseUtil mouseUtil;\r
-\r
- @Dependency\r
- Selection selection;\r
-\r
- @Dependency\r
- ElementPainter diagramPainter;\r
-\r
- ShapeNode node;\r
- G2DParentNode parent;\r
-\r
- private boolean createVar;\r
- private IDiagram createVarDiagram;\r
-\r
- @SGInit(designation = SGDesignation.CANVAS)\r
- public void init(G2DParentNode parent) {\r
- this.parent = parent;\r
- }\r
-\r
- public void removeSG() {\r
- node.remove();\r
- node = null;\r
- setDirty();\r
- }\r
-\r
- void updateSG() {\r
-\r
- if (node == null) {\r
- node = variableInformation.node;\r
- }\r
-\r
- MouseInfo mi = mouseUtil.getMouseInfo(0);\r
- if (mi == null)\r
- return;\r
-\r
- Point2D newPos = mi.canvasPosition;\r
- double x = newPos.getX();\r
- double y = newPos.getY();\r
-\r
- AffineTransform origAt = node.getTransform();\r
- double oldX = origAt.getTranslateX();\r
- double oldY = origAt.getTranslateY();\r
- AffineTransform move = new AffineTransform();\r
- move.setToTranslation(x - oldX, y - oldY);\r
- AffineTransform at2 = new AffineTransform(origAt);\r
- at2.preConcatenate(move);\r
- node.setTransform(at2);\r
- setDirty();\r
- }\r
-\r
- public CreateVariablesShortcutParticipant(GraphToDiagramSynchronizer synchronizer) {\r
- this.synchronizer = synchronizer;\r
- }\r
-\r
- @EventHandler(priority = -10)\r
- public boolean handleKeyboardEvent(KeyEvent ke) {\r
- \r
- // ignore this event if we are not in the unmodified pointer tool mode\r
- if (!Hints.POINTERTOOL.equals(getHint(Hints.KEY_TOOL)) || getHint(SysdynElementHints.SYSDYN_KEY_TOOL) != null) {\r
- return false;\r
- }\r
-\r
- KeyPressedEvent kpe;\r
- if (ke instanceof KeyPressedEvent) {\r
- \r
- kpe = (KeyPressedEvent) ke;\r
- \r
- if (!kpe.isShiftDown() || isEditing()) \r
- return false;\r
- \r
- if (kpe.keyCode == java.awt.event.KeyEvent.VK_A) {\r
- variableInformation = new VariableInformation(\r
- java.awt.event.KeyEvent.VK_A,\r
- SysdynResource.URIs.AuxiliarySymbol,\r
- (ShapeNode)AuxiliaryFactory.AUX_STATIC_IMAGE.init(parent)\r
- );\r
- } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_S) {\r
- variableInformation = new VariableInformation(\r
- java.awt.event.KeyEvent.VK_S,\r
- SysdynResource.URIs.StockSymbol,\r
- (ShapeNode)StockFactory.STOCK_IMAGE.init(parent)\r
- );\r
- } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_C) {\r
- variableInformation = new VariableInformation(\r
- java.awt.event.KeyEvent.VK_C,\r
- SysdynResource.URIs.CloudSymbol,\r
- (ShapeNode)CloudFactory.CLOUD_IMAGE.init(parent)\r
- );\r
- } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_V) {\r
- variableInformation = new VariableInformation(\r
- java.awt.event.KeyEvent.VK_V,\r
- SysdynResource.URIs.ValveSymbol,\r
- (ShapeNode)ValveFactory.VALVE_STATIC_IMAGE.init(parent)\r
- );\r
- } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_I) {\r
- variableInformation = new VariableInformation(\r
- java.awt.event.KeyEvent.VK_I,\r
- SysdynResource.URIs.InputSymbol,\r
- (ShapeNode)InputFactory.INPUT_IMAGE.init(parent)\r
- );\r
- } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_G) {\r
- variableInformation = new VariableInformation(\r
- java.awt.event.KeyEvent.VK_G,\r
- SysdynResource.URIs.ShadowSymbol,\r
- (ShapeNode)ShadowFactory.GHOST_IMAGE.init(parent)\r
- );\r
- } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_L) {\r
- variableInformation = new VariableInformation(\r
- java.awt.event.KeyEvent.VK_L,\r
- SysdynResource.URIs.LoopSymbol,\r
- (ShapeNode)LoopFactory.LOOP_STATIC_IMAGE.init(parent)\r
- );\r
- }\r
-\r
- if (variableInformation != null) {\r
- updateSG();\r
- return true;\r
- }\r
- }\r
-\r
- KeyReleasedEvent kre;\r
- if (ke instanceof KeyReleasedEvent) {\r
- kre = (KeyReleasedEvent) ke;\r
- \r
- if (variableInformation != null\r
- && (kre.keyCode == variableInformation.shortcutKey || kre.keyCode == java.awt.event.KeyEvent.VK_SHIFT)) {\r
- if (node != null) {\r
- // If there is a variable to be created, do it when a key is released.\r
- if (createVar) {\r
- createVar = false;\r
- createVariableOnDiagram(createVarDiagram);\r
- }\r
- variableInformation = null;\r
- removeSG();\r
- return true;\r
- }\r
- }\r
- }\r
-\r
- return false;\r
-\r
- }\r
-\r
- @EventHandler(priority = -10)\r
- public boolean handleMouse(MouseMovedEvent e) {\r
-\r
- if (variableInformation != null ) {\r
- updateSG();\r
- } else {\r
- if (node != null) {\r
- removeSG();\r
- }\r
- }\r
- return false;\r
- }\r
-\r
-\r
- @EventHandler(priority = 100)\r
- public boolean handleMouseEvent(MouseEvent me) {\r
-\r
-\r
- MouseEvent.MouseClickEvent mce;\r
- if (me instanceof MouseEvent.MouseClickEvent) {\r
- mce = (MouseEvent.MouseClickEvent) me;\r
- } else {\r
- return false;\r
- }\r
- \r
- // only create a variable if we are in the unmodified pointer tool mode\r
- if (!Hints.POINTERTOOL.equals(getHint(Hints.KEY_TOOL)) || getHint(SysdynElementHints.SYSDYN_KEY_TOOL) != null) {\r
- return false;\r
- }\r
-\r
- if (!\r
- (\r
- mce.button == MouseEvent.LEFT_BUTTON && \r
- variableInformation != null && \r
- mce.stateMask == MouseEvent.SHIFT_MASK\r
- )) \r
- {\r
- return false;\r
- }\r
- \r
- final IDiagram d = getHint(DiagramHints.KEY_DIAGRAM);\r
- if (d == null)\r
- return false;\r
- \r
- // Need to create a new variable, save the diagram to do this later.\r
- createVar = true;\r
- createVarDiagram = d;\r
-\r
- return true;\r
- }\r
-\r
-\r
- private void createVariableOnDiagram(IDiagram d) {\r
- DiagramUtils.mutateDiagram(d, new Consumer<DiagramMutator>() {\r
- @Override\r
- public void accept(DiagramMutator m) {\r
-\r
- Resource r;\r
- try {\r
- r = SimanticsUI\r
- .getSession()\r
- .syncRequest(\r
- Queries\r
- .resource(variableInformation.symbolURI));\r
- ElementClass ec = SimanticsUI.getSession().syncRequest(\r
- DiagramRequests.getElementClass(r, diagram));\r
-\r
- IElement element = m.newElement(ec);\r
-\r
- // MouseUtil mutil = new MouseUtil();\r
- MouseInfo minfo = mouseUtil.getMouseInfo(0);\r
-\r
- //at least when using breakpoints this is possible\r
- if(minfo == null) \r
- return;\r
-\r
- Point2D p = minfo.canvasPosition;\r
- //FIXME - Arto element doesn't know its size at first. Hopefully temp fix.\r
- p.setLocation(p.getX()-5.46, p.getY()+1);\r
-\r
- ElementUtils.setPos(element, p);\r
-\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- }\r
-\r
- }\r
- });\r
-\r
- synchronizer.getCanvasContext().getContentContext().setDirty();\r
-\r
- }\r
-\r
- private class VariableInformation {\r
- public String symbolURI;\r
- public ShapeNode node;\r
- public int shortcutKey;\r
-\r
- public VariableInformation(int shortcutKey, String symbolURI, ShapeNode node) {\r
- this.symbolURI = symbolURI;\r
- this.node = node;\r
- this.shortcutKey = shortcutKey;\r
- }\r
- }\r
- \r
- private boolean isEditing() {\r
- int selectionId = 0;\r
- Set<IElement> ss = selection.getSelection(selectionId);\r
- if (ss.isEmpty()) {\r
- return false;\r
- }\r
- for (IElement e : ss) {\r
- for(Object o : e.getHints().values()) {\r
- if (o instanceof TextNode) {\r
- TextNode tn = (TextNode) o;\r
- if(tn.isEditMode())\r
- return true;\r
- }\r
- }\r
- }\r
- return false;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.editor.participant;
+
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
+import java.util.Set;
+import java.util.function.Consumer;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.Queries;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;
+import org.simantics.diagram.elements.TextNode;
+import org.simantics.diagram.query.DiagramRequests;
+import org.simantics.g2d.canvas.Hints;
+import org.simantics.g2d.canvas.SGDesignation;
+import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
+import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
+import org.simantics.g2d.diagram.DiagramHints;
+import org.simantics.g2d.diagram.DiagramMutator;
+import org.simantics.g2d.diagram.DiagramUtils;
+import org.simantics.g2d.diagram.IDiagram;
+import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
+import org.simantics.g2d.diagram.participant.ElementPainter;
+import org.simantics.g2d.diagram.participant.Selection;
+import org.simantics.g2d.element.ElementClass;
+import org.simantics.g2d.element.ElementUtils;
+import org.simantics.g2d.element.IElement;
+import org.simantics.g2d.participant.MouseUtil;
+import org.simantics.g2d.participant.MouseUtil.MouseInfo;
+import org.simantics.scenegraph.g2d.G2DParentNode;
+import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
+import org.simantics.scenegraph.g2d.events.KeyEvent;
+import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
+import org.simantics.scenegraph.g2d.events.KeyEvent.KeyReleasedEvent;
+import org.simantics.scenegraph.g2d.events.MouseEvent;
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.elements.AuxiliaryFactory;
+import org.simantics.sysdyn.ui.elements.CloudFactory;
+import org.simantics.sysdyn.ui.elements.InputFactory;
+import org.simantics.sysdyn.ui.elements.LoopFactory;
+import org.simantics.sysdyn.ui.elements.ShadowFactory;
+import org.simantics.sysdyn.ui.elements.StockFactory;
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;
+import org.simantics.sysdyn.ui.elements.ValveFactory;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class CreateVariablesShortcutParticipant extends AbstractDiagramParticipant {
+
+ private GraphToDiagramSynchronizer synchronizer;
+
+ private VariableInformation variableInformation;
+
+ @Dependency
+ MouseUtil mouseUtil;
+
+ @Dependency
+ Selection selection;
+
+ @Dependency
+ ElementPainter diagramPainter;
+
+ ShapeNode node;
+ G2DParentNode parent;
+
+ private boolean createVar;
+ private IDiagram createVarDiagram;
+
+ @SGInit(designation = SGDesignation.CANVAS)
+ public void init(G2DParentNode parent) {
+ this.parent = parent;
+ }
+
+ public void removeSG() {
+ node.remove();
+ node = null;
+ setDirty();
+ }
+
+ void updateSG() {
+
+ if (node == null) {
+ node = variableInformation.node;
+ }
+
+ MouseInfo mi = mouseUtil.getMouseInfo(0);
+ if (mi == null)
+ return;
+
+ Point2D newPos = mi.canvasPosition;
+ double x = newPos.getX();
+ double y = newPos.getY();
+
+ AffineTransform origAt = node.getTransform();
+ double oldX = origAt.getTranslateX();
+ double oldY = origAt.getTranslateY();
+ AffineTransform move = new AffineTransform();
+ move.setToTranslation(x - oldX, y - oldY);
+ AffineTransform at2 = new AffineTransform(origAt);
+ at2.preConcatenate(move);
+ node.setTransform(at2);
+ setDirty();
+ }
+
+ public CreateVariablesShortcutParticipant(GraphToDiagramSynchronizer synchronizer) {
+ this.synchronizer = synchronizer;
+ }
+
+ @EventHandler(priority = -10)
+ public boolean handleKeyboardEvent(KeyEvent ke) {
+
+ // ignore this event if we are not in the unmodified pointer tool mode
+ if (!Hints.POINTERTOOL.equals(getHint(Hints.KEY_TOOL)) || getHint(SysdynElementHints.SYSDYN_KEY_TOOL) != null) {
+ return false;
+ }
+
+ KeyPressedEvent kpe;
+ if (ke instanceof KeyPressedEvent) {
+
+ kpe = (KeyPressedEvent) ke;
+
+ if (!kpe.isShiftDown() || isEditing())
+ return false;
+
+ if (kpe.keyCode == java.awt.event.KeyEvent.VK_A) {
+ variableInformation = new VariableInformation(
+ java.awt.event.KeyEvent.VK_A,
+ SysdynResource.URIs.AuxiliarySymbol,
+ (ShapeNode)AuxiliaryFactory.AUX_STATIC_IMAGE.init(parent)
+ );
+ } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_S) {
+ variableInformation = new VariableInformation(
+ java.awt.event.KeyEvent.VK_S,
+ SysdynResource.URIs.StockSymbol,
+ (ShapeNode)StockFactory.STOCK_IMAGE.init(parent)
+ );
+ } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_C) {
+ variableInformation = new VariableInformation(
+ java.awt.event.KeyEvent.VK_C,
+ SysdynResource.URIs.CloudSymbol,
+ (ShapeNode)CloudFactory.CLOUD_IMAGE.init(parent)
+ );
+ } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_V) {
+ variableInformation = new VariableInformation(
+ java.awt.event.KeyEvent.VK_V,
+ SysdynResource.URIs.ValveSymbol,
+ (ShapeNode)ValveFactory.VALVE_STATIC_IMAGE.init(parent)
+ );
+ } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_I) {
+ variableInformation = new VariableInformation(
+ java.awt.event.KeyEvent.VK_I,
+ SysdynResource.URIs.InputSymbol,
+ (ShapeNode)InputFactory.INPUT_IMAGE.init(parent)
+ );
+ } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_G) {
+ variableInformation = new VariableInformation(
+ java.awt.event.KeyEvent.VK_G,
+ SysdynResource.URIs.ShadowSymbol,
+ (ShapeNode)ShadowFactory.GHOST_IMAGE.init(parent)
+ );
+ } else if (kpe.keyCode == java.awt.event.KeyEvent.VK_L) {
+ variableInformation = new VariableInformation(
+ java.awt.event.KeyEvent.VK_L,
+ SysdynResource.URIs.LoopSymbol,
+ (ShapeNode)LoopFactory.LOOP_STATIC_IMAGE.init(parent)
+ );
+ }
+
+ if (variableInformation != null) {
+ updateSG();
+ return true;
+ }
+ }
+
+ KeyReleasedEvent kre;
+ if (ke instanceof KeyReleasedEvent) {
+ kre = (KeyReleasedEvent) ke;
+
+ if (variableInformation != null
+ && (kre.keyCode == variableInformation.shortcutKey || kre.keyCode == java.awt.event.KeyEvent.VK_SHIFT)) {
+ if (node != null) {
+ // If there is a variable to be created, do it when a key is released.
+ if (createVar) {
+ createVar = false;
+ createVariableOnDiagram(createVarDiagram);
+ }
+ variableInformation = null;
+ removeSG();
+ return true;
+ }
+ }
+ }
+
+ return false;
+
+ }
+
+ @EventHandler(priority = -10)
+ public boolean handleMouse(MouseMovedEvent e) {
+
+ if (variableInformation != null ) {
+ updateSG();
+ } else {
+ if (node != null) {
+ removeSG();
+ }
+ }
+ return false;
+ }
+
+
+ @EventHandler(priority = 100)
+ public boolean handleMouseEvent(MouseEvent me) {
+
+
+ MouseEvent.MouseClickEvent mce;
+ if (me instanceof MouseEvent.MouseClickEvent) {
+ mce = (MouseEvent.MouseClickEvent) me;
+ } else {
+ return false;
+ }
+
+ // only create a variable if we are in the unmodified pointer tool mode
+ if (!Hints.POINTERTOOL.equals(getHint(Hints.KEY_TOOL)) || getHint(SysdynElementHints.SYSDYN_KEY_TOOL) != null) {
+ return false;
+ }
+
+ if (!
+ (
+ mce.button == MouseEvent.LEFT_BUTTON &&
+ variableInformation != null &&
+ mce.stateMask == MouseEvent.SHIFT_MASK
+ ))
+ {
+ return false;
+ }
+
+ final IDiagram d = getHint(DiagramHints.KEY_DIAGRAM);
+ if (d == null)
+ return false;
+
+ // Need to create a new variable, save the diagram to do this later.
+ createVar = true;
+ createVarDiagram = d;
+
+ return true;
+ }
+
+
+ private void createVariableOnDiagram(IDiagram d) {
+ DiagramUtils.mutateDiagram(d, new Consumer<DiagramMutator>() {
+ @Override
+ public void accept(DiagramMutator m) {
+
+ Resource r;
+ try {
+ r = Simantics
+ .getSession()
+ .syncRequest(
+ Queries
+ .resource(variableInformation.symbolURI));
+ ElementClass ec = Simantics.getSession().syncRequest(
+ DiagramRequests.getElementClass(r, diagram));
+
+ IElement element = m.newElement(ec);
+
+ // MouseUtil mutil = new MouseUtil();
+ MouseInfo minfo = mouseUtil.getMouseInfo(0);
+
+ //at least when using breakpoints this is possible
+ if(minfo == null)
+ return;
+
+ Point2D p = minfo.canvasPosition;
+ //FIXME - Arto element doesn't know its size at first. Hopefully temp fix.
+ p.setLocation(p.getX()-5.46, p.getY()+1);
+
+ ElementUtils.setPos(element, p);
+
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+
+ }
+ });
+
+ synchronizer.getCanvasContext().getContentContext().setDirty();
+
+ }
+
+ private class VariableInformation {
+ public String symbolURI;
+ public ShapeNode node;
+ public int shortcutKey;
+
+ public VariableInformation(int shortcutKey, String symbolURI, ShapeNode node) {
+ this.symbolURI = symbolURI;
+ this.node = node;
+ this.shortcutKey = shortcutKey;
+ }
+ }
+
+ private boolean isEditing() {
+ int selectionId = 0;
+ Set<IElement> ss = selection.getSelection(selectionId);
+ if (ss.isEmpty()) {
+ return false;
+ }
+ for (IElement e : ss) {
+ for(Object o : e.getHints().values()) {
+ if (o instanceof TextNode) {
+ TextNode tn = (TextNode) o;
+ if(tn.isEditMode())
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.editor.participant;\r
-\r
-import java.util.Collection;\r
-\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.VirtualGraph;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.diagram.ui.DiagramModelHints;\r
-import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;\r
-import org.simantics.g2d.canvas.impl.HintReflection.HintListener;\r
-import org.simantics.g2d.diagram.DiagramHints;\r
-import org.simantics.g2d.diagram.IDiagram;\r
-import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;\r
-import org.simantics.g2d.diagram.participant.Selection;\r
-import org.simantics.g2d.element.ElementHints;\r
-import org.simantics.g2d.element.IElement;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
-import org.simantics.utils.datastructures.hints.IHintObservable;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-\r
-public class SelectionUpdaterParticipant extends AbstractDiagramParticipant {\r
-\r
- @Dependency Selection selection;\r
-\r
- @HintListener(Class = Selection.class, Field = "SELECTION0")\r
- public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
- IDiagram diagram = sender.getHint(DiagramHints.KEY_DIAGRAM);\r
- Collection<IElement> elements = AdaptionUtils.adaptToCollection(newValue, IElement.class);\r
- if(diagram != null) {\r
- Session session = SimanticsUI.getSession();\r
- session.asyncRequest(new ModifyDiagramSelection(session.getService(VirtualGraph.class), diagram, elements));\r
- }\r
- }\r
- \r
- @HintListener(Class = Selection.class, Field = "SELECTION0")\r
- public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
- IDiagram diagram = sender.getHint(DiagramHints.KEY_DIAGRAM);\r
- if(diagram != null) {\r
- Session session = SimanticsUI.getSession();\r
- session.asyncRequest(new ModifyDiagramSelection(session.getService(VirtualGraph.class), diagram, null));\r
- }\r
- }\r
- \r
- \r
- private class ModifyDiagramSelection extends WriteRequest {\r
- IDiagram diagram;\r
- Collection<IElement> elements;\r
- \r
- public ModifyDiagramSelection(VirtualGraph provider, IDiagram diagram, Collection<IElement> elements) {\r
- super(provider);\r
- this.elements = elements;\r
- this.diagram = diagram;\r
- }\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Resource diagramRuntime = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RUNTIME_RESOURCE);\r
- \r
- if(diagramRuntime == null) {\r
- return;\r
- }\r
- \r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- DiagramResource DR = DiagramResource.getInstance(graph);\r
-\r
- graph.deny(diagramRuntime, SR.ConfigurationDiagram_selection);\r
-\r
- if(elements != null) {\r
- for(IElement e : elements) {\r
- Resource object = e.getHint(ElementHints.KEY_OBJECT);\r
- if(object != null && graph.isInstanceOf(object, DR.Element)) {\r
- graph.claim(diagramRuntime, SR.ConfigurationDiagram_selection, object);\r
- }\r
- }\r
- }\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.editor.participant;
+
+import java.util.Collection;
+
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.VirtualGraph;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.diagram.stubs.DiagramResource;
+import org.simantics.diagram.ui.DiagramModelHints;
+import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
+import org.simantics.g2d.canvas.impl.HintReflection.HintListener;
+import org.simantics.g2d.diagram.DiagramHints;
+import org.simantics.g2d.diagram.IDiagram;
+import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
+import org.simantics.g2d.diagram.participant.Selection;
+import org.simantics.g2d.element.ElementHints;
+import org.simantics.g2d.element.IElement;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.datastructures.hints.IHintContext.Key;
+import org.simantics.utils.datastructures.hints.IHintObservable;
+import org.simantics.utils.ui.AdaptionUtils;
+
+
+public class SelectionUpdaterParticipant extends AbstractDiagramParticipant {
+
+ @Dependency Selection selection;
+
+ @HintListener(Class = Selection.class, Field = "SELECTION0")
+ public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
+ IDiagram diagram = sender.getHint(DiagramHints.KEY_DIAGRAM);
+ Collection<IElement> elements = AdaptionUtils.adaptToCollection(newValue, IElement.class);
+ if(diagram != null) {
+ Session session = Simantics.getSession();
+ session.asyncRequest(new ModifyDiagramSelection(session.getService(VirtualGraph.class), diagram, elements));
+ }
+ }
+
+ @HintListener(Class = Selection.class, Field = "SELECTION0")
+ public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {
+ IDiagram diagram = sender.getHint(DiagramHints.KEY_DIAGRAM);
+ if(diagram != null) {
+ Session session = Simantics.getSession();
+ session.asyncRequest(new ModifyDiagramSelection(session.getService(VirtualGraph.class), diagram, null));
+ }
+ }
+
+
+ private class ModifyDiagramSelection extends WriteRequest {
+ IDiagram diagram;
+ Collection<IElement> elements;
+
+ public ModifyDiagramSelection(VirtualGraph provider, IDiagram diagram, Collection<IElement> elements) {
+ super(provider);
+ this.elements = elements;
+ this.diagram = diagram;
+ }
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Resource diagramRuntime = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RUNTIME_RESOURCE);
+
+ if(diagramRuntime == null) {
+ return;
+ }
+
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ DiagramResource DR = DiagramResource.getInstance(graph);
+
+ graph.deny(diagramRuntime, SR.ConfigurationDiagram_selection);
+
+ if(elements != null) {
+ for(IElement e : elements) {
+ Resource object = e.getHint(ElementHints.KEY_OBJECT);
+ if(object != null && graph.isInstanceOf(object, DR.Element)) {
+ graph.claim(diagramRuntime, SR.ConfigurationDiagram_selection, object);
+ }
+ }
+ }
+ }
+ }
+}
-package org.simantics.sysdyn.ui.editor.participant;\r
-\r
-import java.awt.BasicStroke;\r
-import java.awt.Color;\r
-import java.awt.geom.AffineTransform;\r
-import java.awt.geom.Path2D;\r
-import java.awt.geom.Point2D;\r
-import java.awt.geom.Rectangle2D;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.Deque;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.diagram.participant.ConnectTool2;\r
-import org.simantics.diagram.participant.ConnectionBuilder;\r
-import org.simantics.diagram.participant.ControlPoint;\r
-import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;\r
-import org.simantics.g2d.connection.IConnectionAdvisor;\r
-import org.simantics.g2d.diagram.DiagramHints;\r
-import org.simantics.g2d.diagram.handler.Topology.Terminal;\r
-import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;\r
-import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;\r
-import org.simantics.g2d.element.ElementClass;\r
-import org.simantics.g2d.element.ElementClasses;\r
-import org.simantics.g2d.element.ElementUtils;\r
-import org.simantics.g2d.element.IElement;\r
-import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;\r
-import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
-import org.simantics.g2d.element.impl.Element;\r
-import org.simantics.g2d.elementclass.BranchPointClass;\r
-import org.simantics.g2d.elementclass.FlagClass;\r
-import org.simantics.g2d.routing.Constants;\r
-import org.simantics.g2d.routing.IConnection;\r
-import org.simantics.g2d.routing.IRouter2;\r
-import org.simantics.g2d.routing.TrivialRouter2;\r
-import org.simantics.scenegraph.g2d.G2DParentNode;\r
-import org.simantics.scenegraph.g2d.events.MouseEvent;\r
-import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonEvent;\r
-import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;\r
-import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;\r
-import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
-import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;\r
-import org.simantics.structural2.modelingRules.ConnectionJudgement;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.editor.routing.FlowRouter;\r
-import org.simantics.sysdyn.ui.elements.CloudFactory;\r
-import org.simantics.sysdyn.ui.elements.SysdynElementHints;\r
-import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;\r
-import org.simantics.sysdyn.ui.elements.connections.ConnectionClasses;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-import org.simantics.utils.ui.ErrorLogger;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-public class SysdynConnectTool extends ConnectTool2 {\r
-\r
- public SysdynConnectTool(TerminalInfo startTerminal, int mouseId,\r
- Point2D startCanvasPos) {\r
- super(startTerminal, mouseId, startCanvasPos);\r
- }\r
-\r
- @Override\r
- @SGInit\r
- public void initSG(G2DParentNode parent) {\r
- ghostNode = parent.addNode(G2DParentNode.class);\r
- ghostNode.setZIndex(PAINT_PRIORITY);\r
-\r
- ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);\r
- pathNode.setColor(Color.BLACK);\r
- pathNode.setStroke(new BasicStroke(1f));\r
- pathNode.setScaleStroke(true);\r
- pathNode.setZIndex(0);\r
-\r
- G2DParentNode points = ghostNode.getOrCreateNode("points", G2DParentNode.class);\r
- points.setZIndex(1);\r
-\r
- updateSG();\r
- }\r
-\r
- @Override\r
- protected TerminalInfo createFlag(EdgeEnd connectionEnd) {\r
- ElementClass flagClass = elementClassProvider.get(ElementClasses.FLAG);\r
- IElement e = Element.spawnNew(flagClass);\r
-\r
- e.setHint(FlagClass.KEY_FLAG_TYPE, endToFlagType(connectionEnd));\r
- e.setHint(FlagClass.KEY_FLAG_MODE, FlagClass.Mode.Internal);\r
-\r
- TerminalInfo ti = new TerminalInfo();\r
- ti.e = e;\r
-\r
- // start: this part changed to support overlapping terminals\r
- ArrayList<Terminal> terminals = new ArrayList<Terminal>();\r
- ElementUtils.getTerminals(e, terminals, false);\r
- ti.t = terminals.get(0);\r
- // end\r
-\r
- ti.posElem = TerminalUtil.getTerminalPosOnElement(e, ti.t);\r
- ti.posDia = TerminalUtil.getTerminalPosOnDiagram(e, ti.t);\r
-\r
- return ti;\r
- }\r
-\r
- static class Segment {\r
- public final ControlPoint begin;\r
- public final ControlPoint end;\r
- public Path2D path;\r
-\r
- public Segment(ControlPoint begin, ControlPoint end) {\r
- this.begin = begin;\r
- this.end = end;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return "Segment[begin=" + begin + ", end=" + end + ", path=" + path + "]";\r
- }\r
- }\r
-\r
- private List<Segment> toSegments(Deque<ControlPoint> points) {\r
- if (points.isEmpty())\r
- return Collections.emptyList();\r
-\r
- List<Segment> segments = new ArrayList<Segment>();\r
-\r
- Iterator<ControlPoint> it = points.iterator();\r
- ControlPoint prev = it.next();\r
- while (it.hasNext()) {\r
- ControlPoint next = it.next();\r
- segments.add(new Segment(prev, next));\r
- prev = next;\r
- }\r
-\r
- return segments;\r
- }\r
-\r
- public interface SysdynConnection extends IConnection { }\r
-\r
- @Override\r
- protected void updateSG() {\r
- if (controlPoints.isEmpty())\r
- return;\r
-\r
- // Route connection segments separately\r
- IRouter2 router = ElementUtils.getHintOrDefault(diagram, DiagramHints.ROUTE_ALGORITHM, TrivialRouter2.INSTANCE);\r
- final List<Segment> segments = toSegments(controlPoints);\r
- //System.out.println("controlpoints: " + controlPoints);\r
- //System.out.println("segments: " + segments);\r
- router.route(new SysdynConnection() {\r
- @Override\r
- public Collection<? extends Object> getSegments() {\r
- return segments;\r
- }\r
-\r
- @Override\r
- public Connector getBegin(Object seg) {\r
- return getConnector(((Segment) seg).begin);\r
- }\r
-\r
- @Override\r
- public Connector getEnd(Object seg) {\r
- return getConnector(((Segment) seg).end);\r
- }\r
-\r
- private Connector getConnector(ControlPoint cp) {\r
- Connector c = new Connector();\r
- c.x = cp.getPosition().getX();\r
- c.y = cp.getPosition().getY();\r
-\r
- c.allowedDirections = Constants.EAST_FLAG | Constants.WEST_FLAG\r
- | Constants.NORTH_FLAG | Constants.SOUTH_FLAG;\r
-\r
- TerminalInfo ti = cp.getAttachedTerminal();\r
- if (ti != null && (ti != startFlag && ti != endFlag)) {\r
- if(ti.e.getElementClass().containsClass(ValveSceneGraph.class)) {\r
- Rectangle2D bounds = ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D();\r
- c.parentObstacle = new Rectangle2D.Double(\r
- bounds.getCenterX() - FlowRouter.OFFSET,\r
- bounds.getCenterY() - FlowRouter.OFFSET, \r
- FlowRouter.OFFSET * 2,\r
- FlowRouter.OFFSET * 2);\r
- } else {\r
- c.parentObstacle = ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D();\r
- }\r
- } else if (ti != null && ti == startFlag) {\r
- c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),\r
- ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D());\r
- } else if (ti != null && isEndingInFlag()) {\r
- c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),\r
- CloudFactory.CLOUD_IMAGE.getBounds());\r
- } else {\r
- c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),\r
- BranchPointClass.DEFAULT_IMAGE2.getBounds());\r
- }\r
-\r
- return c;\r
- }\r
-\r
- @Override\r
- public void setPath(Object seg, Path2D path) {\r
- ((Segment) seg).path = (Path2D) path.clone();\r
- }\r
- });\r
-\r
- // Combine the routed paths\r
- Path2D path = new Path2D.Double();\r
- for (Segment seg : segments) {\r
- //System.out.println("SEG: " + seg);\r
- if (seg.path != null)\r
- path.append(seg.path.getPathIterator(null), true);\r
- }\r
-\r
- // Create scene graph to visualize the connection.\r
- ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);\r
- pathNode.setShape(path);\r
-\r
- /*\r
- * Removed Points\r
- */\r
-\r
- setDirty();\r
- }\r
-\r
- @Override\r
- protected Object canConnect(final IConnectionAdvisor advisor, final IElement endElement, final Terminal endTerminal) {\r
- final IElement se = startTerminal != null ? startTerminal.e : startFlag.e;\r
- final Terminal st = startTerminal != null ? startTerminal.t : null;\r
-\r
- if(se.equals(endElement)) return null;\r
- if(Boolean.FALSE.equals(diagram.getHint(DiagramHints.KEY_USE_CONNECTION_FLAGS)) && endElement == null) {\r
- return null;\r
- }\r
-\r
- if(endElement == null && endTerminal == null)\r
- return advisor.canBeConnected(null, se, st, endElement, endTerminal);\r
-\r
- try {\r
- return SimanticsUI.getSession().syncRequest(new Read<Object>() {\r
-\r
- @Override\r
- public Object perform(ReadGraph g) throws DatabaseException {\r
-\r
- // Checking if connection type can be connected to the intended endElement\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- StaticObjectAdapter soa = endElement.getElementClass().getSingleItem(StaticObjectAdapter.class);\r
- Resource end = soa.adapt(Resource.class);\r
- ElementClass dependency = elementClassProvider.get(ConnectionClasses.DEPENDENCY);\r
- ElementClass flow = elementClassProvider.get(ConnectionClasses.FLOW);\r
- ElementClass currentConnection = elementClassProvider.get(ElementClasses.CONNECTION);\r
- if(currentConnection.equals(dependency)) {\r
- if(end.equals(sr.CloudSymbol)) return null;\r
- soa = se.getElementClass().getSingleItem(StaticObjectAdapter.class);\r
- Resource start = soa.adapt(Resource.class);\r
- if(g.isInheritedFrom(start, sr.ModuleSymbol) && !end.equals(sr.InputSymbol)) return null;\r
- if(end.equals(sr.ShadowSymbol)) return null;\r
- } else if (currentConnection.equals(flow)) {\r
- if(!(end.equals(sr.StockSymbol) || end.equals(sr.ValveSymbol) || end.equals(sr.CloudSymbol))) return null;\r
- } else {\r
- return null;\r
- }\r
-\r
-\r
- if (advisor == null)\r
- return Boolean.TRUE; \r
- return advisor.canBeConnected(g, se, st, endElement, endTerminal);\r
- }\r
-\r
- });\r
- } catch(DatabaseException e) {\r
- e.printStackTrace();\r
- return null;\r
- }\r
-\r
- }\r
-\r
- @Override\r
- protected boolean processMouseMove(MouseMovedEvent me) {\r
- mouseHasMoved = true;\r
-\r
- Point2D mouseControlPos = me.controlPosition;\r
- Point2D mouseCanvasPos = util.controlToCanvas(mouseControlPos, new Point2D.Double());\r
-\r
- ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);\r
- if (snapAdvisor != null)\r
- snapAdvisor.snap(mouseCanvasPos);\r
-\r
- // Record last snapped canvas position of mouse.\r
- this.lastMouseCanvasPos.setLocation(mouseCanvasPos);\r
-\r
- if (isEndingInFlag()) {\r
- endFlagNode.setTransform(AffineTransform.getTranslateInstance(mouseCanvasPos.getX(), mouseCanvasPos.getY()));\r
- }\r
-\r
- List<TerminalInfo> tiList = ((SysdynPointerInteractor)pi).pickTerminals(me.controlPosition);\r
- TerminalInfo ti = null;\r
-\r
- IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);\r
- for(TerminalInfo info : tiList) {\r
- if(advisor == null || info.e == null || info.t == null)\r
- continue;\r
- Object canConnect = canConnect(advisor, info.e, info.t);\r
- if (canConnect != null) {\r
- ti = info;\r
- break;\r
- }\r
- }\r
-\r
- if (ti != null && !isStartTerminal(ti.e, ti.t)) {\r
- Pair<ConnectionJudgement, TerminalInfo> canConnect = canConnect(ti.e, ti.t);\r
- if (canConnect != null) {\r
- connectionJudgment = canConnect.first;\r
-\r
- if (!isEndingInFlag() || !TerminalUtil.isSameTerminal(ti, endTerminal)) {\r
- controlPoints.getLast()\r
- .setPosition(ti.posDia)\r
- .setAttachedToTerminal(ti);\r
-\r
- endTerminal = ti;\r
- }\r
-\r
- // Make sure that we are ending with a flag if ALT is pressed\r
- // and no end terminal is defined. If we are in flow creation\r
- // mode, we want to show the terminal cloud (or flag) even when\r
- // alt is not pressed.\r
- if (inFlowMode() && flowInProgress() && !startTerminals.isEmpty())\r
- endWithoutTerminal(lastMouseCanvasPos, true);\r
- else\r
- endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));\r
- updateSG();\r
- return false;\r
- }\r
- }\r
-\r
- connectionJudgment = null;\r
- if (isEndTerminalDefined()) {\r
- // CASE: Mouse was previously on top of a valid terminal to end\r
- // the connection. Now the mouse has been moved where there is\r
- // no longer a terminal to connect to.\r
- //\r
- // => Disconnect the last edge segment from the previous\r
- // terminal, mark endElement/endTerminal non-existent\r
- // and connect the disconnected edge to a new branch point.\r
-\r
- controlPoints.getLast()\r
- .setPosition(mouseCanvasPos)\r
- .setDirection(calculateCurrentBranchPointDirection())\r
- .setAttachedToTerminal(null);\r
-\r
- endTerminal = null;\r
- } else {\r
- // CASE: Mouse was not previously on top of a valid ending\r
- // element terminal.\r
- //\r
- // => Move and re-orient last branch point.\r
-\r
- controlPoints.getLast()\r
- .setPosition(mouseCanvasPos)\r
- .setDirection(calculateCurrentBranchPointDirection());\r
- }\r
-\r
- // Make sure that we are ending with a flag if ALT is pressed and no end\r
- // terminal is defined. If we are in flow creation mode, we want to show \r
- // the terminal cloud (or flag) even when alt is not pressed.\r
- if (inFlowMode() && flowInProgress() && !startTerminals.isEmpty())\r
- endWithoutTerminal(lastMouseCanvasPos, true);\r
- else\r
- endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));\r
- updateSG();\r
- return false;\r
- }\r
-\r
- @Override\r
- protected boolean processMouseButtonPress(MouseButtonPressedEvent e) {\r
- MouseButtonEvent me = e;\r
-\r
- // Do nothing before the mouse has moved at least a little.\r
- // This prevents the user from ending the connection right where\r
- // it started.\r
- if (!mouseHasMoved)\r
- return true;\r
-\r
- if (me.button == MouseEvent.LEFT_BUTTON || \r
- (me.button == MouseEvent.RIGHT_BUTTON && flowInProgress() && !inFlowMode())) {\r
- Point2D mouseControlPos = me.controlPosition;\r
- Point2D mouseCanvasPos = util.getInverseTransform().transform(mouseControlPos, new Point2D.Double());\r
-\r
- ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);\r
- if (snapAdvisor != null)\r
- snapAdvisor.snap(mouseCanvasPos);\r
-\r
- // Clicked on an allowed end terminal. End connection & end mode.\r
- if (isEndTerminalDefined()) {\r
- createConnection();\r
- remove();\r
- return true;\r
- } else {\r
- // Finish connection in thin air only if the\r
- // connection was started from a valid terminal.\r
- \r
- // If we are in flow creation mode, we want to be able to\r
- // create the terminal cloud (or flag) without having to \r
- // press alt.\r
- \r
- if (!startTerminals.isEmpty() && ((me.stateMask & MouseEvent.ALT_MASK) != 0 || \r
- (inFlowMode() && flowInProgress()))) {\r
- Pair<ConnectionJudgement, TerminalInfo> pair = canConnect(null, null);\r
- if (pair != null) {\r
- connectionJudgment = (ConnectionJudgement) pair.first;\r
- selectedStartTerminal = pair.second;\r
- createConnection();\r
- setDirty();\r
- remove();\r
- } else {\r
- // Inform the user why connection couldn't be created.\r
- ErrorLogger.defaultLogWarning("Can't resolve connection type for new connection.", null);\r
- }\r
- return true;\r
- } else if (routePointsAllowed()\r
- && (me.stateMask & (MouseEvent.ALT_MASK | MouseEvent.SHIFT_MASK | MouseEvent.CTRL_MASK)) == 0) {\r
- // Add new connection control point.\r
- controlPoints.add(newControlPointWithCalculatedDirection(mouseCanvasPos));\r
- resetForcedBranchPointDirection();\r
- updateSG();\r
- }\r
- }\r
- }\r
-\r
- return true;\r
- }\r
- \r
- private boolean inFlowMode() {\r
- return SysdynElementHints.FLOW_TOOL.equals(getHint(SysdynElementHints.SYSDYN_KEY_TOOL));\r
- }\r
- \r
- private boolean flowInProgress() {\r
- return elementClassProvider.get(ElementClasses.CONNECTION).equals(elementClassProvider.get(ConnectionClasses.FLOW));\r
- }\r
-\r
- @Override\r
- protected void createConnection() {\r
-\r
- if(this.connectionJudgment == null) return;\r
-\r
- final ConnectionJudgement judgment = this.connectionJudgment;\r
- // ConnectionBuilder changed to SysdynconnectionBuilder to support overlapping terminals and valve creation\r
- final ConnectionBuilder builder = new SysdynConnectionBuilder(this.diagram);\r
- final Deque<ControlPoint> controlPoints = this.controlPoints;\r
- final TerminalInfo startTerminal = this.startTerminal;\r
- final TerminalInfo endTerminal = this.endTerminal;\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- builder.create(graph, judgment, controlPoints, startTerminal, endTerminal);\r
- }\r
- }, e -> {\r
- if (e != null)\r
- ExceptionUtils.logAndShowError(e);\r
- });\r
- }\r
-}\r
+package org.simantics.sysdyn.ui.editor.participant;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Path2D;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.Iterator;
+import java.util.List;
+
+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.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.diagram.participant.ConnectTool2;
+import org.simantics.diagram.participant.ConnectionBuilder;
+import org.simantics.diagram.participant.ControlPoint;
+import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
+import org.simantics.g2d.connection.IConnectionAdvisor;
+import org.simantics.g2d.diagram.DiagramHints;
+import org.simantics.g2d.diagram.handler.Topology.Terminal;
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;
+import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;
+import org.simantics.g2d.element.ElementClass;
+import org.simantics.g2d.element.ElementClasses;
+import org.simantics.g2d.element.ElementUtils;
+import org.simantics.g2d.element.IElement;
+import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
+import org.simantics.g2d.element.impl.Element;
+import org.simantics.g2d.elementclass.BranchPointClass;
+import org.simantics.g2d.elementclass.FlagClass;
+import org.simantics.g2d.routing.Constants;
+import org.simantics.g2d.routing.IConnection;
+import org.simantics.g2d.routing.IRouter2;
+import org.simantics.g2d.routing.TrivialRouter2;
+import org.simantics.scenegraph.g2d.G2DParentNode;
+import org.simantics.scenegraph.g2d.events.MouseEvent;
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonEvent;
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;
+import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;
+import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
+import org.simantics.structural2.modelingRules.ConnectionJudgement;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.editor.routing.FlowRouter;
+import org.simantics.sysdyn.ui.elements.CloudFactory;
+import org.simantics.sysdyn.ui.elements.SysdynElementHints;
+import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;
+import org.simantics.sysdyn.ui.elements.connections.ConnectionClasses;
+import org.simantics.utils.datastructures.Pair;
+import org.simantics.utils.ui.ErrorLogger;
+import org.simantics.utils.ui.ExceptionUtils;
+
+public class SysdynConnectTool extends ConnectTool2 {
+
+ public SysdynConnectTool(TerminalInfo startTerminal, int mouseId,
+ Point2D startCanvasPos) {
+ super(startTerminal, mouseId, startCanvasPos);
+ }
+
+ @Override
+ @SGInit
+ public void initSG(G2DParentNode parent) {
+ ghostNode = parent.addNode(G2DParentNode.class);
+ ghostNode.setZIndex(PAINT_PRIORITY);
+
+ ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);
+ pathNode.setColor(Color.BLACK);
+ pathNode.setStroke(new BasicStroke(1f));
+ pathNode.setScaleStroke(true);
+ pathNode.setZIndex(0);
+
+ G2DParentNode points = ghostNode.getOrCreateNode("points", G2DParentNode.class);
+ points.setZIndex(1);
+
+ updateSG();
+ }
+
+ @Override
+ protected TerminalInfo createFlag(EdgeEnd connectionEnd) {
+ ElementClass flagClass = elementClassProvider.get(ElementClasses.FLAG);
+ IElement e = Element.spawnNew(flagClass);
+
+ e.setHint(FlagClass.KEY_FLAG_TYPE, endToFlagType(connectionEnd));
+ e.setHint(FlagClass.KEY_FLAG_MODE, FlagClass.Mode.Internal);
+
+ TerminalInfo ti = new TerminalInfo();
+ ti.e = e;
+
+ // start: this part changed to support overlapping terminals
+ ArrayList<Terminal> terminals = new ArrayList<Terminal>();
+ ElementUtils.getTerminals(e, terminals, false);
+ ti.t = terminals.get(0);
+ // end
+
+ ti.posElem = TerminalUtil.getTerminalPosOnElement(e, ti.t);
+ ti.posDia = TerminalUtil.getTerminalPosOnDiagram(e, ti.t);
+
+ return ti;
+ }
+
+ static class Segment {
+ public final ControlPoint begin;
+ public final ControlPoint end;
+ public Path2D path;
+
+ public Segment(ControlPoint begin, ControlPoint end) {
+ this.begin = begin;
+ this.end = end;
+ }
+
+ @Override
+ public String toString() {
+ return "Segment[begin=" + begin + ", end=" + end + ", path=" + path + "]";
+ }
+ }
+
+ private List<Segment> toSegments(Deque<ControlPoint> points) {
+ if (points.isEmpty())
+ return Collections.emptyList();
+
+ List<Segment> segments = new ArrayList<Segment>();
+
+ Iterator<ControlPoint> it = points.iterator();
+ ControlPoint prev = it.next();
+ while (it.hasNext()) {
+ ControlPoint next = it.next();
+ segments.add(new Segment(prev, next));
+ prev = next;
+ }
+
+ return segments;
+ }
+
+ public interface SysdynConnection extends IConnection { }
+
+ @Override
+ protected void updateSG() {
+ if (controlPoints.isEmpty())
+ return;
+
+ // Route connection segments separately
+ IRouter2 router = ElementUtils.getHintOrDefault(diagram, DiagramHints.ROUTE_ALGORITHM, TrivialRouter2.INSTANCE);
+ final List<Segment> segments = toSegments(controlPoints);
+ //System.out.println("controlpoints: " + controlPoints);
+ //System.out.println("segments: " + segments);
+ router.route(new SysdynConnection() {
+ @Override
+ public Collection<? extends Object> getSegments() {
+ return segments;
+ }
+
+ @Override
+ public Connector getBegin(Object seg) {
+ return getConnector(((Segment) seg).begin);
+ }
+
+ @Override
+ public Connector getEnd(Object seg) {
+ return getConnector(((Segment) seg).end);
+ }
+
+ private Connector getConnector(ControlPoint cp) {
+ Connector c = new Connector();
+ c.x = cp.getPosition().getX();
+ c.y = cp.getPosition().getY();
+
+ c.allowedDirections = Constants.EAST_FLAG | Constants.WEST_FLAG
+ | Constants.NORTH_FLAG | Constants.SOUTH_FLAG;
+
+ TerminalInfo ti = cp.getAttachedTerminal();
+ if (ti != null && (ti != startFlag && ti != endFlag)) {
+ if(ti.e.getElementClass().containsClass(ValveSceneGraph.class)) {
+ Rectangle2D bounds = ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D();
+ c.parentObstacle = new Rectangle2D.Double(
+ bounds.getCenterX() - FlowRouter.OFFSET,
+ bounds.getCenterY() - FlowRouter.OFFSET,
+ FlowRouter.OFFSET * 2,
+ FlowRouter.OFFSET * 2);
+ } else {
+ c.parentObstacle = ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D();
+ }
+ } else if (ti != null && ti == startFlag) {
+ c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),
+ ElementUtils.getElementBoundsOnDiagram(ti.e).getBounds2D());
+ } else if (ti != null && isEndingInFlag()) {
+ c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),
+ CloudFactory.CLOUD_IMAGE.getBounds());
+ } else {
+ c.parentObstacle = org.simantics.scenegraph.utils.GeometryUtils.transformRectangle(AffineTransform.getTranslateInstance(c.x, c.y),
+ BranchPointClass.DEFAULT_IMAGE2.getBounds());
+ }
+
+ return c;
+ }
+
+ @Override
+ public void setPath(Object seg, Path2D path) {
+ ((Segment) seg).path = (Path2D) path.clone();
+ }
+ });
+
+ // Combine the routed paths
+ Path2D path = new Path2D.Double();
+ for (Segment seg : segments) {
+ //System.out.println("SEG: " + seg);
+ if (seg.path != null)
+ path.append(seg.path.getPathIterator(null), true);
+ }
+
+ // Create scene graph to visualize the connection.
+ ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);
+ pathNode.setShape(path);
+
+ /*
+ * Removed Points
+ */
+
+ setDirty();
+ }
+
+ @Override
+ protected Object canConnect(final IConnectionAdvisor advisor, final IElement endElement, final Terminal endTerminal) {
+ final IElement se = startTerminal != null ? startTerminal.e : startFlag.e;
+ final Terminal st = startTerminal != null ? startTerminal.t : null;
+
+ if(se.equals(endElement)) return null;
+ if(Boolean.FALSE.equals(diagram.getHint(DiagramHints.KEY_USE_CONNECTION_FLAGS)) && endElement == null) {
+ return null;
+ }
+
+ if(endElement == null && endTerminal == null)
+ return advisor.canBeConnected(null, se, st, endElement, endTerminal);
+
+ try {
+ return Simantics.getSession().syncRequest(new Read<Object>() {
+
+ @Override
+ public Object perform(ReadGraph g) throws DatabaseException {
+
+ // Checking if connection type can be connected to the intended endElement
+ SysdynResource sr = SysdynResource.getInstance(g);
+ StaticObjectAdapter soa = endElement.getElementClass().getSingleItem(StaticObjectAdapter.class);
+ Resource end = soa.adapt(Resource.class);
+ ElementClass dependency = elementClassProvider.get(ConnectionClasses.DEPENDENCY);
+ ElementClass flow = elementClassProvider.get(ConnectionClasses.FLOW);
+ ElementClass currentConnection = elementClassProvider.get(ElementClasses.CONNECTION);
+ if(currentConnection.equals(dependency)) {
+ if(end.equals(sr.CloudSymbol)) return null;
+ soa = se.getElementClass().getSingleItem(StaticObjectAdapter.class);
+ Resource start = soa.adapt(Resource.class);
+ if(g.isInheritedFrom(start, sr.ModuleSymbol) && !end.equals(sr.InputSymbol)) return null;
+ if(end.equals(sr.ShadowSymbol)) return null;
+ } else if (currentConnection.equals(flow)) {
+ if(!(end.equals(sr.StockSymbol) || end.equals(sr.ValveSymbol) || end.equals(sr.CloudSymbol))) return null;
+ } else {
+ return null;
+ }
+
+
+ if (advisor == null)
+ return Boolean.TRUE;
+ return advisor.canBeConnected(g, se, st, endElement, endTerminal);
+ }
+
+ });
+ } catch(DatabaseException e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ }
+
+ @Override
+ protected boolean processMouseMove(MouseMovedEvent me) {
+ mouseHasMoved = true;
+
+ Point2D mouseControlPos = me.controlPosition;
+ Point2D mouseCanvasPos = util.controlToCanvas(mouseControlPos, new Point2D.Double());
+
+ ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
+ if (snapAdvisor != null)
+ snapAdvisor.snap(mouseCanvasPos);
+
+ // Record last snapped canvas position of mouse.
+ this.lastMouseCanvasPos.setLocation(mouseCanvasPos);
+
+ if (isEndingInFlag()) {
+ endFlagNode.setTransform(AffineTransform.getTranslateInstance(mouseCanvasPos.getX(), mouseCanvasPos.getY()));
+ }
+
+ List<TerminalInfo> tiList = ((SysdynPointerInteractor)pi).pickTerminals(me.controlPosition);
+ TerminalInfo ti = null;
+
+ IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);
+ for(TerminalInfo info : tiList) {
+ if(advisor == null || info.e == null || info.t == null)
+ continue;
+ Object canConnect = canConnect(advisor, info.e, info.t);
+ if (canConnect != null) {
+ ti = info;
+ break;
+ }
+ }
+
+ if (ti != null && !isStartTerminal(ti.e, ti.t)) {
+ Pair<ConnectionJudgement, TerminalInfo> canConnect = canConnect(ti.e, ti.t);
+ if (canConnect != null) {
+ connectionJudgment = canConnect.first;
+
+ if (!isEndingInFlag() || !TerminalUtil.isSameTerminal(ti, endTerminal)) {
+ controlPoints.getLast()
+ .setPosition(ti.posDia)
+ .setAttachedToTerminal(ti);
+
+ endTerminal = ti;
+ }
+
+ // Make sure that we are ending with a flag if ALT is pressed
+ // and no end terminal is defined. If we are in flow creation
+ // mode, we want to show the terminal cloud (or flag) even when
+ // alt is not pressed.
+ if (inFlowMode() && flowInProgress() && !startTerminals.isEmpty())
+ endWithoutTerminal(lastMouseCanvasPos, true);
+ else
+ endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));
+ updateSG();
+ return false;
+ }
+ }
+
+ connectionJudgment = null;
+ if (isEndTerminalDefined()) {
+ // CASE: Mouse was previously on top of a valid terminal to end
+ // the connection. Now the mouse has been moved where there is
+ // no longer a terminal to connect to.
+ //
+ // => Disconnect the last edge segment from the previous
+ // terminal, mark endElement/endTerminal non-existent
+ // and connect the disconnected edge to a new branch point.
+
+ controlPoints.getLast()
+ .setPosition(mouseCanvasPos)
+ .setDirection(calculateCurrentBranchPointDirection())
+ .setAttachedToTerminal(null);
+
+ endTerminal = null;
+ } else {
+ // CASE: Mouse was not previously on top of a valid ending
+ // element terminal.
+ //
+ // => Move and re-orient last branch point.
+
+ controlPoints.getLast()
+ .setPosition(mouseCanvasPos)
+ .setDirection(calculateCurrentBranchPointDirection());
+ }
+
+ // Make sure that we are ending with a flag if ALT is pressed and no end
+ // terminal is defined. If we are in flow creation mode, we want to show
+ // the terminal cloud (or flag) even when alt is not pressed.
+ if (inFlowMode() && flowInProgress() && !startTerminals.isEmpty())
+ endWithoutTerminal(lastMouseCanvasPos, true);
+ else
+ endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));
+ updateSG();
+ return false;
+ }
+
+ @Override
+ protected boolean processMouseButtonPress(MouseButtonPressedEvent e) {
+ MouseButtonEvent me = e;
+
+ // Do nothing before the mouse has moved at least a little.
+ // This prevents the user from ending the connection right where
+ // it started.
+ if (!mouseHasMoved)
+ return true;
+
+ if (me.button == MouseEvent.LEFT_BUTTON ||
+ (me.button == MouseEvent.RIGHT_BUTTON && flowInProgress() && !inFlowMode())) {
+ Point2D mouseControlPos = me.controlPosition;
+ Point2D mouseCanvasPos = util.getInverseTransform().transform(mouseControlPos, new Point2D.Double());
+
+ ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
+ if (snapAdvisor != null)
+ snapAdvisor.snap(mouseCanvasPos);
+
+ // Clicked on an allowed end terminal. End connection & end mode.
+ if (isEndTerminalDefined()) {
+ createConnection();
+ remove();
+ return true;
+ } else {
+ // Finish connection in thin air only if the
+ // connection was started from a valid terminal.
+
+ // If we are in flow creation mode, we want to be able to
+ // create the terminal cloud (or flag) without having to
+ // press alt.
+
+ if (!startTerminals.isEmpty() && ((me.stateMask & MouseEvent.ALT_MASK) != 0 ||
+ (inFlowMode() && flowInProgress()))) {
+ Pair<ConnectionJudgement, TerminalInfo> pair = canConnect(null, null);
+ if (pair != null) {
+ connectionJudgment = (ConnectionJudgement) pair.first;
+ selectedStartTerminal = pair.second;
+ createConnection();
+ setDirty();
+ remove();
+ } else {
+ // Inform the user why connection couldn't be created.
+ ErrorLogger.defaultLogWarning("Can't resolve connection type for new connection.", null);
+ }
+ return true;
+ } else if (routePointsAllowed()
+ && (me.stateMask & (MouseEvent.ALT_MASK | MouseEvent.SHIFT_MASK | MouseEvent.CTRL_MASK)) == 0) {
+ // Add new connection control point.
+ controlPoints.add(newControlPointWithCalculatedDirection(mouseCanvasPos));
+ resetForcedBranchPointDirection();
+ updateSG();
+ }
+ }
+ }
+
+ return true;
+ }
+
+ private boolean inFlowMode() {
+ return SysdynElementHints.FLOW_TOOL.equals(getHint(SysdynElementHints.SYSDYN_KEY_TOOL));
+ }
+
+ private boolean flowInProgress() {
+ return elementClassProvider.get(ElementClasses.CONNECTION).equals(elementClassProvider.get(ConnectionClasses.FLOW));
+ }
+
+ @Override
+ protected void createConnection() {
+
+ if(this.connectionJudgment == null) return;
+
+ final ConnectionJudgement judgment = this.connectionJudgment;
+ // ConnectionBuilder changed to SysdynconnectionBuilder to support overlapping terminals and valve creation
+ final ConnectionBuilder builder = new SysdynConnectionBuilder(this.diagram);
+ final Deque<ControlPoint> controlPoints = this.controlPoints;
+ final TerminalInfo startTerminal = this.startTerminal;
+ final TerminalInfo endTerminal = this.endTerminal;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ builder.create(graph, judgment, controlPoints, startTerminal, endTerminal);
+ }
+ }, e -> {
+ if (e != null)
+ ExceptionUtils.logAndShowError(e);
+ });
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.elements;\r
-\r
-import java.awt.BasicStroke;\r
-import java.awt.Color;\r
-import java.awt.Paint;\r
-import java.awt.Shape;\r
-import java.awt.geom.AffineTransform;\r
-import java.awt.geom.Arc2D;\r
-import java.awt.geom.Path2D;\r
-import java.awt.geom.Point2D;\r
-import java.awt.geom.RectangularShape;\r
-import java.util.Collection;\r
-import java.util.function.Consumer;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.elements.ITextListener;\r
-import org.simantics.diagram.elements.TextNode;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.g2d.canvas.ICanvasContext;\r
-import org.simantics.g2d.diagram.DiagramUtils;\r
-import org.simantics.g2d.diagram.IDiagram;\r
-import org.simantics.g2d.element.ElementClass;\r
-import org.simantics.g2d.element.ElementHints;\r
-import org.simantics.g2d.element.ElementUtils;\r
-import org.simantics.g2d.element.IElement;\r
-import org.simantics.g2d.element.SceneGraphNodeKey;\r
-import org.simantics.g2d.element.handler.HandleMouseEvent;\r
-import org.simantics.g2d.element.handler.impl.BoundsOutline;\r
-import org.simantics.g2d.element.handler.impl.DefaultTransform;\r
-import org.simantics.g2d.element.handler.impl.HoverImpl;\r
-import org.simantics.g2d.element.handler.impl.ObjectTerminal;\r
-import org.simantics.g2d.element.handler.impl.OutlinePick;\r
-import org.simantics.g2d.element.handler.impl.SimpleElementLayers;\r
-import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
-import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;\r
-import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;\r
-import org.simantics.g2d.element.handler.impl.TextColorImpl;\r
-import org.simantics.g2d.element.handler.impl.TextFontImpl;\r
-import org.simantics.g2d.element.handler.impl.TextImpl;\r
-import org.simantics.g2d.elementclass.ImageClass.StaticImageElementHandler;\r
-import org.simantics.g2d.image.DefaultImages;\r
-import org.simantics.g2d.image.Image;\r
-import org.simantics.g2d.image.impl.ShapeImage;\r
-import org.simantics.g2d.svg.SVGImage;\r
-import org.simantics.g2d.utils.Alignment;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.scenegraph.g2d.G2DParentNode;\r
-import org.simantics.scenegraph.g2d.nodes.SVGNode;\r
-import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.properties.LoopTab;\r
-import org.simantics.sysdyn.utils.LoopUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
-import org.simantics.utils.datastructures.hints.IHintListener;\r
-import org.simantics.utils.datastructures.hints.IHintObservable;\r
-\r
-/**\r
- * Factory for loops.\r
- * \r
- * @author Tuomas Miettinen\r
- */\r
-public class LoopFactory extends SysdynElementFactory {\r
-\r
- public static final Image LOOP_STATIC_IMAGE = new ShapeImage(getLoopShape(), null, new BasicStroke(1), true);\r
- private static Image image = null;\r
-\r
- @Override\r
- public ElementClass create(ReadGraph graph, ICanvasContext canvas,\r
- IDiagram diagram, Resource elementType) throws DatabaseException {\r
-\r
- // Create the loop symbol svg image\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- String svgDoc = graph.getPossibleRelatedValue(elementType, g2d.HasSVGDocument);\r
- String id = "TextElement: " + NameUtils.getSafeName(graph, elementType);\r
- if (svgDoc != null)\r
- image = new SVGImage(id+".svg", svgDoc);\r
- else\r
- image = DefaultImages.ERROR_DECORATOR.get();\r
-\r
- return ElementClass.compile(\r
- SimpleElementLayers.INSTANCE,\r
- OutlinePick.INSTANCE,\r
- TextImpl.INSTANCE,\r
- TextColorImpl.BLACK,\r
- TextFontImpl.DEFAULT,\r
- DefaultTransform.INSTANCE,\r
- new StaticObjectAdapter(elementType),\r
- new StaticSymbolImpl(image),\r
- StaticSymbolImageInitializer.INSTANCE,\r
- LoopSceneGraph.INSTANCE,\r
- new LoopImageSceneGraph(image),\r
- HoverImpl.INSTANCE,\r
- BoundsOutline.INSTANCE,\r
- LoopClockwise.INSTANCE\r
- ).setId(LoopFactory.class.getSimpleName());\r
- }\r
-\r
- static Shape getLoopShape() {\r
- // Used in shortcut.\r
- double x0 = 5, y0 = 2;\r
- Path2D loop = new Path2D.Double();\r
- loop.moveTo(x0 + 1, y0 + 2);\r
- loop.lineTo(x0 + 0, y0 + 0);\r
- loop.lineTo(x0 -1, y0 + 2);\r
- loop.closePath();\r
-\r
- loop.append(new Arc2D.Double(x0 -10, y0 -3, 10, 10, 0, -270, Arc2D.OPEN), false);\r
- return loop;\r
- }\r
-\r
- @Override\r
- protected String getText(ReadGraph graph, Resource element) throws DatabaseException {\r
- // Get loop comment instead of loop name.\r
- SysdynResource sr = SysdynResource.getInstance(graph); \r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
- String text = null;\r
- if (component != null) {\r
- text = (String) graph.getPossibleRelatedValue(component, sr.Loop_Comment);\r
- }\r
- if (text == null)\r
- text = "";\r
- else if (LoopTab.AUTO.equals(text)) {\r
- switch (LoopUtils.getLoopType(graph, component)) {\r
- case BALANCING:\r
- text = "B";\r
- break;\r
- case REINFORCING:\r
- text = "R";\r
- break;\r
- default:\r
- text = "";\r
- }\r
- }\r
- return text;\r
- }\r
-\r
- @Override\r
- protected ElementClass compileElementClass(Resource elementType,\r
- Collection<ObjectTerminal> terminals) {\r
- return null;\r
- }\r
- \r
- @Override\r
- public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {\r
- super.load(graph, canvas, diagram, element, e);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Boolean clockwise = graph.getPossibleRelatedValue(element, sr.LoopSymbol_Clockwise, Bindings.BOOLEAN);\r
- if(clockwise == null) {\r
- clockwise = Boolean.TRUE;\r
- }\r
- SysdynElementUtils.setLoopClockwise(e, clockwise);\r
- }\r
- \r
- \r
-\r
- /**\r
- * Handling for the loop image on diagram.\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
- public static class LoopImageSceneGraph extends StaticImageElementHandler {\r
-\r
- private static final long serialVersionUID = -185893525553743589L;\r
- \r
- private IHintListener hoverHintListener;\r
- \r
- private static final Key NODE = new SceneGraphNodeKey(LoopNode.class, "LOOP_NODE");\r
-\r
- public LoopImageSceneGraph(Image i) {\r
- super(i);\r
- }\r
-\r
- @Override\r
- public void init(IElement e, G2DParentNode parent) {\r
- super.init(e, parent);\r
-\r
- // Create new hover shape node for the loop image\r
- final LoopNode node = ElementUtils.getOrCreateNode(e, parent, NODE, "loopHover", LoopNode.class);\r
- \r
- // Mirror the image if clockwise is selected.\r
- Boolean clockwise = e.getHint(SysdynElementHints.KEY_LOOP_CLOCKWISE);\r
- SVGNode image = e.getHint(getNodeKey());\r
- if (clockwise != null && clockwise) {\r
- Point2D imageParent = (Point2D) image.localToParent(new Point2D.Double(0.0,0.0)).clone();\r
- AffineTransform at = new AffineTransform(-1.0, 0.0, 0.0, 1.0, imageParent.getX()+12.34, imageParent.getY());\r
- image.setTransform(at);\r
- }\r
- \r
- // Set the shape of the shape node to match the shape of the image\r
- RectangularShape bounds = (RectangularShape)image.getBounds().clone();\r
- node.setShape(bounds);\r
- \r
- // Set the shape node transparent\r
- Paint paint = new Color(0,0,0,0);\r
- node.setColor(paint);\r
- \r
- // Handle hover\r
- Boolean hover = e.getHint(ElementHints.KEY_HOVER); \r
- node.setHover(hover != null ? hover : false);\r
- hoverHintListener = new IHintListener() {\r
-\r
- @Override\r
- public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
- }\r
-\r
- @Override\r
- public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
- IElement e = (IElement)sender;\r
- LoopNode shape = (LoopNode) e.getHint(NODE);\r
- if(shape == null) {\r
- return;\r
- }\r
- boolean hover = ElementUtils.isHovering(e);\r
- shape.setHover(hover);\r
- }\r
- };\r
- e.addHintListener(hoverHintListener);\r
- }\r
-\r
- @Override\r
- public void cleanup(IElement e) {\r
- super.cleanup(e);\r
- e.removeHintListener(hoverHintListener);\r
- }\r
- }\r
-\r
- /**\r
- * Handling for the text box of loop in diagram.\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
- public static class LoopSceneGraph extends SysdynTextElementNoBounds implements HandleMouseEvent {\r
-\r
- private static final long serialVersionUID = -5093461687773246286L;\r
-\r
- public static final LoopSceneGraph INSTANCE = new LoopSceneGraph();\r
- \r
- private static final Key NODE = new SceneGraphNodeKey(ShapeNode.class, "LOOP_COMMENT_NODE");\r
- \r
- public LoopSceneGraph() {\r
- super(0, 0, Alignment.CENTER, 0, 1, 1, true);\r
- }\r
- \r
- @Override\r
- public void init(IElement e, G2DParentNode parent) {\r
- super.init(e, parent);\r
- \r
- // Move the text box into (around) the middle of the loop image\r
- AffineTransform at = ElementUtils.getTransform(e);\r
- final LoopNode node = ElementUtils.getOrCreateNode(e, parent, NODE, "loopComment", LoopNode.class);\r
-\r
- // Unflip the text and image\r
- unflipText(e);\r
-\r
- if(at != null) {\r
- node.setTransform(at);\r
-\r
- TextNode name = (TextNode) e.getHint(SG_NODE);\r
- if(name != null) {\r
- AffineTransform at2 = (AffineTransform) at.clone();\r
- at2.translate(getXCoordShift(e), getYCoordShift(e));\r
-\r
- Alignment alignment = Alignment.CENTER;\r
-\r
- name.setTransform(at2);\r
- if(alignment != null) {\r
- name.setHorizontalAlignment((byte) alignment.ordinal());\r
- name.setVerticalAlignment((byte) alignment.ordinal());\r
- }\r
- }\r
- }\r
- }\r
-\r
- private static double getXCoordShift(IElement e) {\r
- //String location = e.getHint(SysdynElementHints.KEY_LOCATION);\r
- return 6.3;\r
- }\r
-\r
- private static double getYCoordShift(IElement e) {\r
- //String location = e.getHint(SysdynElementHints.KEY_LOCATION);\r
- return -0.3;\r
- }\r
-\r
- @Override\r
- protected <T extends SysdynTextNode> Consumer<T> getCallback(final IElement e, G2DParentNode parent, Class<T> nodeClass) {\r
- return new Consumer<T>() {\r
- @Override\r
- public void accept(T node) {\r
- node.setTextListener(new ITextListener() {\r
-\r
- Resource component;\r
-\r
- @Override\r
- public void textChanged() {\r
- }\r
-\r
- @Override\r
- public void textEditingStarted() {\r
- if(component != null) return;\r
-\r
- Object o = e.getHint(ElementHints.KEY_OBJECT);\r
- if(o != null && o instanceof Resource) {\r
- final Resource element = (Resource)o;\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- component = graph.getPossibleObject(element, ModelingResources.getInstance(graph).ElementToComponent);\r
- }\r
- });\r
- }\r
- }\r
-\r
- @Override\r
- public void textEditingCancelled() {\r
- TextNode node = (TextNode) e.getHint(SG_NODE);\r
- if (node != null) {\r
- endEdit(node);\r
- }\r
- }\r
-\r
- @Override\r
- public void textEditingEnded() {\r
- TextNode node = (TextNode) e.getHint(SG_NODE);\r
- if (node == null)\r
- return;\r
-\r
- // Write the changed comment of the loop\r
- final String text = node.getText();\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph)\r
- throws DatabaseException {\r
- if (component != null) {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- graph.deny(component, sr.Loop_Comment);\r
- graph.claimLiteral(component, sr.Loop_Comment, text);\r
- }\r
- }\r
-\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
-\r
- IDiagram diagram = ElementUtils.getDiagram(e);\r
- DiagramUtils.synchronizeHintsToBackend(diagram, e);\r
- endEdit(node);\r
- }\r
- });\r
- }\r
- };\r
- }\r
-\r
- }\r
-\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.elements;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Paint;
+import java.awt.Shape;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Arc2D;
+import java.awt.geom.Path2D;
+import java.awt.geom.Point2D;
+import java.awt.geom.RectangularShape;
+import java.util.Collection;
+import java.util.function.Consumer;
+
+import org.simantics.Simantics;
+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.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.diagram.elements.ITextListener;
+import org.simantics.diagram.elements.TextNode;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.g2d.canvas.ICanvasContext;
+import org.simantics.g2d.diagram.DiagramUtils;
+import org.simantics.g2d.diagram.IDiagram;
+import org.simantics.g2d.element.ElementClass;
+import org.simantics.g2d.element.ElementHints;
+import org.simantics.g2d.element.ElementUtils;
+import org.simantics.g2d.element.IElement;
+import org.simantics.g2d.element.SceneGraphNodeKey;
+import org.simantics.g2d.element.handler.HandleMouseEvent;
+import org.simantics.g2d.element.handler.impl.BoundsOutline;
+import org.simantics.g2d.element.handler.impl.DefaultTransform;
+import org.simantics.g2d.element.handler.impl.HoverImpl;
+import org.simantics.g2d.element.handler.impl.ObjectTerminal;
+import org.simantics.g2d.element.handler.impl.OutlinePick;
+import org.simantics.g2d.element.handler.impl.SimpleElementLayers;
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
+import org.simantics.g2d.element.handler.impl.StaticSymbolImageInitializer;
+import org.simantics.g2d.element.handler.impl.StaticSymbolImpl;
+import org.simantics.g2d.element.handler.impl.TextColorImpl;
+import org.simantics.g2d.element.handler.impl.TextFontImpl;
+import org.simantics.g2d.element.handler.impl.TextImpl;
+import org.simantics.g2d.elementclass.ImageClass.StaticImageElementHandler;
+import org.simantics.g2d.image.DefaultImages;
+import org.simantics.g2d.image.Image;
+import org.simantics.g2d.image.impl.ShapeImage;
+import org.simantics.g2d.svg.SVGImage;
+import org.simantics.g2d.utils.Alignment;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.scenegraph.g2d.G2DParentNode;
+import org.simantics.scenegraph.g2d.nodes.SVGNode;
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.properties.LoopTab;
+import org.simantics.sysdyn.utils.LoopUtils;
+import org.simantics.utils.datastructures.hints.IHintContext.Key;
+import org.simantics.utils.datastructures.hints.IHintListener;
+import org.simantics.utils.datastructures.hints.IHintObservable;
+
+/**
+ * Factory for loops.
+ *
+ * @author Tuomas Miettinen
+ */
+public class LoopFactory extends SysdynElementFactory {
+
+ public static final Image LOOP_STATIC_IMAGE = new ShapeImage(getLoopShape(), null, new BasicStroke(1), true);
+ private static Image image = null;
+
+ @Override
+ public ElementClass create(ReadGraph graph, ICanvasContext canvas,
+ IDiagram diagram, Resource elementType) throws DatabaseException {
+
+ // Create the loop symbol svg image
+ G2DResource g2d = G2DResource.getInstance(graph);
+ String svgDoc = graph.getPossibleRelatedValue(elementType, g2d.HasSVGDocument);
+ String id = "TextElement: " + NameUtils.getSafeName(graph, elementType);
+ if (svgDoc != null)
+ image = new SVGImage(id+".svg", svgDoc);
+ else
+ image = DefaultImages.ERROR_DECORATOR.get();
+
+ return ElementClass.compile(
+ SimpleElementLayers.INSTANCE,
+ OutlinePick.INSTANCE,
+ TextImpl.INSTANCE,
+ TextColorImpl.BLACK,
+ TextFontImpl.DEFAULT,
+ DefaultTransform.INSTANCE,
+ new StaticObjectAdapter(elementType),
+ new StaticSymbolImpl(image),
+ StaticSymbolImageInitializer.INSTANCE,
+ LoopSceneGraph.INSTANCE,
+ new LoopImageSceneGraph(image),
+ HoverImpl.INSTANCE,
+ BoundsOutline.INSTANCE,
+ LoopClockwise.INSTANCE
+ ).setId(LoopFactory.class.getSimpleName());
+ }
+
+ static Shape getLoopShape() {
+ // Used in shortcut.
+ double x0 = 5, y0 = 2;
+ Path2D loop = new Path2D.Double();
+ loop.moveTo(x0 + 1, y0 + 2);
+ loop.lineTo(x0 + 0, y0 + 0);
+ loop.lineTo(x0 -1, y0 + 2);
+ loop.closePath();
+
+ loop.append(new Arc2D.Double(x0 -10, y0 -3, 10, 10, 0, -270, Arc2D.OPEN), false);
+ return loop;
+ }
+
+ @Override
+ protected String getText(ReadGraph graph, Resource element) throws DatabaseException {
+ // Get loop comment instead of loop name.
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ Resource component = graph.getPossibleObject(element, mr.ElementToComponent);
+ String text = null;
+ if (component != null) {
+ text = (String) graph.getPossibleRelatedValue(component, sr.Loop_Comment);
+ }
+ if (text == null)
+ text = "";
+ else if (LoopTab.AUTO.equals(text)) {
+ switch (LoopUtils.getLoopType(graph, component)) {
+ case BALANCING:
+ text = "B";
+ break;
+ case REINFORCING:
+ text = "R";
+ break;
+ default:
+ text = "";
+ }
+ }
+ return text;
+ }
+
+ @Override
+ protected ElementClass compileElementClass(Resource elementType,
+ Collection<ObjectTerminal> terminals) {
+ return null;
+ }
+
+ @Override
+ public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource element, final IElement e) throws DatabaseException {
+ super.load(graph, canvas, diagram, element, e);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Boolean clockwise = graph.getPossibleRelatedValue(element, sr.LoopSymbol_Clockwise, Bindings.BOOLEAN);
+ if(clockwise == null) {
+ clockwise = Boolean.TRUE;
+ }
+ SysdynElementUtils.setLoopClockwise(e, clockwise);
+ }
+
+
+
+ /**
+ * Handling for the loop image on diagram.
+ * @author Tuomas Miettinen
+ *
+ */
+ public static class LoopImageSceneGraph extends StaticImageElementHandler {
+
+ private static final long serialVersionUID = -185893525553743589L;
+
+ private IHintListener hoverHintListener;
+
+ private static final Key NODE = new SceneGraphNodeKey(LoopNode.class, "LOOP_NODE");
+
+ public LoopImageSceneGraph(Image i) {
+ super(i);
+ }
+
+ @Override
+ public void init(IElement e, G2DParentNode parent) {
+ super.init(e, parent);
+
+ // Create new hover shape node for the loop image
+ final LoopNode node = ElementUtils.getOrCreateNode(e, parent, NODE, "loopHover", LoopNode.class);
+
+ // Mirror the image if clockwise is selected.
+ Boolean clockwise = e.getHint(SysdynElementHints.KEY_LOOP_CLOCKWISE);
+ SVGNode image = e.getHint(getNodeKey());
+ if (clockwise != null && clockwise) {
+ Point2D imageParent = (Point2D) image.localToParent(new Point2D.Double(0.0,0.0)).clone();
+ AffineTransform at = new AffineTransform(-1.0, 0.0, 0.0, 1.0, imageParent.getX()+12.34, imageParent.getY());
+ image.setTransform(at);
+ }
+
+ // Set the shape of the shape node to match the shape of the image
+ RectangularShape bounds = (RectangularShape)image.getBounds().clone();
+ node.setShape(bounds);
+
+ // Set the shape node transparent
+ Paint paint = new Color(0,0,0,0);
+ node.setColor(paint);
+
+ // Handle hover
+ Boolean hover = e.getHint(ElementHints.KEY_HOVER);
+ node.setHover(hover != null ? hover : false);
+ hoverHintListener = new IHintListener() {
+
+ @Override
+ public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {
+ }
+
+ @Override
+ public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
+ IElement e = (IElement)sender;
+ LoopNode shape = (LoopNode) e.getHint(NODE);
+ if(shape == null) {
+ return;
+ }
+ boolean hover = ElementUtils.isHovering(e);
+ shape.setHover(hover);
+ }
+ };
+ e.addHintListener(hoverHintListener);
+ }
+
+ @Override
+ public void cleanup(IElement e) {
+ super.cleanup(e);
+ e.removeHintListener(hoverHintListener);
+ }
+ }
+
+ /**
+ * Handling for the text box of loop in diagram.
+ * @author Tuomas Miettinen
+ *
+ */
+ public static class LoopSceneGraph extends SysdynTextElementNoBounds implements HandleMouseEvent {
+
+ private static final long serialVersionUID = -5093461687773246286L;
+
+ public static final LoopSceneGraph INSTANCE = new LoopSceneGraph();
+
+ private static final Key NODE = new SceneGraphNodeKey(ShapeNode.class, "LOOP_COMMENT_NODE");
+
+ public LoopSceneGraph() {
+ super(0, 0, Alignment.CENTER, 0, 1, 1, true);
+ }
+
+ @Override
+ public void init(IElement e, G2DParentNode parent) {
+ super.init(e, parent);
+
+ // Move the text box into (around) the middle of the loop image
+ AffineTransform at = ElementUtils.getTransform(e);
+ final LoopNode node = ElementUtils.getOrCreateNode(e, parent, NODE, "loopComment", LoopNode.class);
+
+ // Unflip the text and image
+ unflipText(e);
+
+ if(at != null) {
+ node.setTransform(at);
+
+ TextNode name = (TextNode) e.getHint(SG_NODE);
+ if(name != null) {
+ AffineTransform at2 = (AffineTransform) at.clone();
+ at2.translate(getXCoordShift(e), getYCoordShift(e));
+
+ Alignment alignment = Alignment.CENTER;
+
+ name.setTransform(at2);
+ if(alignment != null) {
+ name.setHorizontalAlignment((byte) alignment.ordinal());
+ name.setVerticalAlignment((byte) alignment.ordinal());
+ }
+ }
+ }
+ }
+
+ private static double getXCoordShift(IElement e) {
+ //String location = e.getHint(SysdynElementHints.KEY_LOCATION);
+ return 6.3;
+ }
+
+ private static double getYCoordShift(IElement e) {
+ //String location = e.getHint(SysdynElementHints.KEY_LOCATION);
+ return -0.3;
+ }
+
+ @Override
+ protected <T extends SysdynTextNode> Consumer<T> getCallback(final IElement e, G2DParentNode parent, Class<T> nodeClass) {
+ return new Consumer<T>() {
+ @Override
+ public void accept(T node) {
+ node.setTextListener(new ITextListener() {
+
+ Resource component;
+
+ @Override
+ public void textChanged() {
+ }
+
+ @Override
+ public void textEditingStarted() {
+ if(component != null) return;
+
+ Object o = e.getHint(ElementHints.KEY_OBJECT);
+ if(o != null && o instanceof Resource) {
+ final Resource element = (Resource)o;
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ component = graph.getPossibleObject(element, ModelingResources.getInstance(graph).ElementToComponent);
+ }
+ });
+ }
+ }
+
+ @Override
+ public void textEditingCancelled() {
+ TextNode node = (TextNode) e.getHint(SG_NODE);
+ if (node != null) {
+ endEdit(node);
+ }
+ }
+
+ @Override
+ public void textEditingEnded() {
+ TextNode node = (TextNode) e.getHint(SG_NODE);
+ if (node == null)
+ return;
+
+ // Write the changed comment of the loop
+ final String text = node.getText();
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph)
+ throws DatabaseException {
+ if (component != null) {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ graph.deny(component, sr.Loop_Comment);
+ graph.claimLiteral(component, sr.Loop_Comment, text);
+ }
+ }
+
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+
+ IDiagram diagram = ElementUtils.getDiagram(e);
+ DiagramUtils.synchronizeHintsToBackend(diagram, e);
+ endEdit(node);
+ }
+ });
+ }
+ };
+ }
+
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2014 Association for Decentralized Information Management\r
- * in Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.elements;\r
-\r
-import java.awt.Color;\r
-import java.awt.Graphics2D;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.diagram.elements.DiagramNodeUtil;\r
-import org.simantics.g2d.element.ElementHints;\r
-import org.simantics.g2d.element.IElement;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.scenegraph.INode;\r
-import org.simantics.scenegraph.ParentNode;\r
-import org.simantics.scenegraph.g2d.IG2DNode;\r
-import org.simantics.scenegraph.g2d.nodes.ConnectionNode;\r
-import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;\r
-import org.simantics.scenegraph.utils.NodeUtil;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Node for Sysdyn loop elements.\r
- * \r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class LoopNode extends HoverShapeNode {\r
-\r
- /**\r
- * Interface for nodes that can be part of loops\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
- public interface ILoopComponentNode {\r
- \r
- /**\r
- * Sets or resets the loop selected status\r
- * @param loop The loop which has been selected\r
- * @param selected true iff the loop is selected\r
- */\r
- public void setLoopSelected(LoopNode loop, boolean selected);\r
- \r
- }\r
- \r
- public static Color HIGHLIGHT_COLOR = Color.decode("#ff5fbf");\r
- \r
- private boolean selected = false;\r
- \r
- private static final long serialVersionUID = 6173159124691715569L;\r
- \r
- @Override\r
- public void render(Graphics2D g2d) {\r
- super.render(g2d);\r
- \r
- // If the loop is selected, highlight also the elements that belong to the loop.\r
- boolean selected = NodeUtil.isSelected(this, 1);\r
- // Do nothing if the selection is and was off.\r
- if (selected || this.selected != selected) {\r
- this.selected = selected; \r
- // Tell all items belonging to the loop that the loop is selected.\r
- setLoopItemsSelected();\r
- }\r
- }\r
- \r
- private void setLoopItemsSelected() {\r
- // Get all variables and dependencies in the loop.\r
- List<Resource> loopItems = getAllLoopItems();\r
- \r
- // Get the diagram where this loop is.\r
- RTreeNode diagramNode = (RTreeNode)NodeUtil.getPossibleNearestParentOfType(this, RTreeNode.class);\r
- if (diagramNode == null)\r
- return;\r
- \r
- // Go through all elements on the diagram where this loop is.\r
- Collection<IG2DNode> children = diagramNode.getNodes();\r
- Iterator<IG2DNode> it = children.iterator();\r
- while (it.hasNext()) {\r
- IG2DNode n = it.next();\r
- \r
- // Get the respective node \r
- INode child = getNodeOfPossibleLoopComponentNode(n);\r
- if (child instanceof ILoopComponentNode) {\r
- ILoopComponentNode ln = (ILoopComponentNode)child;\r
- // Get the respective element \r
- IElement e = DiagramNodeUtil.getElement((IG2DNode)child.getParent());\r
- // Get the respective resource \r
- Resource r = e.getHint(ElementHints.KEY_OBJECT);\r
- // If the node belongs to the loop, tell it that whether the loop is selected or not.\r
- ln.setLoopSelected(this, NodeUtil.isSelected(this, 1) && loopItems.contains(r));\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Get the ILoopComponentNode under the variable, dependency, or flow. \r
- * @param n node under which the ILoopComponentNode is sought\r
- * @return ILoopComponentNode or null, if there is not any.\r
- */\r
- private static INode getNodeOfPossibleLoopComponentNode(IG2DNode n) {\r
- // Get all nodeIds of n's children.\r
- Collection<String> nodeIds = ((ParentNode<?>)n).getNodeIds();\r
-\r
- // Flows and SysdynTextNodes\r
- for (String id : nodeIds) {\r
- if ("text".equals(id)\r
- || id.startsWith("flow_")) \r
- return ((ParentNode<?>)n).getNode(id);\r
- }\r
-\r
- // Dependencies\r
- if (n instanceof ConnectionNode) {\r
- // See the if a child of n has a DependencyNode as a child.\r
- Iterator<IG2DNode> it = ((ConnectionNode) n).getNodes().iterator();\r
- while (it.hasNext()) {\r
- n = it.next();\r
- if (n instanceof ParentNode<?>) {\r
- nodeIds = ((ParentNode<?>)n).getNodeIds();\r
- for (String id : nodeIds) {\r
- if (id.startsWith("edge_"))\r
- return ((ParentNode<?>)n).getNode(id);\r
- }\r
- }\r
- }\r
- }\r
- \r
- return null; // n was no variable, dependency, or flow\r
-\r
- }\r
-\r
- /**\r
- * Get all variables and dependencies in the loop.\r
- * @return A list where the items are, in unspecified order.\r
- */\r
- private List<Resource> getAllLoopItems() {\r
- IElement loopElement = DiagramNodeUtil.getElement(this);\r
- final Resource loopSymbolResource = loopElement.getHint(ElementHints.KEY_OBJECT);\r
- List<Resource> loopItems = Collections.emptyList();\r
- \r
- try {\r
- loopItems = SimanticsUI.getSession().syncRequest(new Read<List<Resource>>(){\r
-\r
- @Override\r
- public List<Resource> perform(ReadGraph graph) throws DatabaseException {\r
- ModelingResources mod = ModelingResources.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource loopComponentResource = graph.getPossibleObject(loopSymbolResource, mod.ElementToComponent);\r
- if (loopComponentResource == null)\r
- return Collections.emptyList();\r
- \r
- Resource loopResource = graph.getPossibleObject(loopComponentResource, sr.Loop_Items);\r
- if (loopResource == null)\r
- return Collections.emptyList();\r
- \r
- List<Resource> loopItems = ListUtils.toPossibleList(graph, loopResource);\r
- if (loopItems == null)\r
- return Collections.emptyList();\r
- \r
- ArrayList<Resource> dependencyItems = new ArrayList<Resource>();\r
- \r
- // Add dependencies and flows.\r
- for (int i = 0; i < loopItems.size(); ++i) {\r
- boolean skipBackwardFlows = false;\r
- \r
- // Go through forward dependencies and flows\r
- Collection<Resource> forwardDependencies = graph.getObjects(loopItems.get(i), sr.Variable_isTailOf);\r
- \r
- // And also through the forward dependencies of possible shadows.\r
- Collection<Resource> shadows = graph.getObjects(loopItems.get(i), sr.Shadow_original_Inverse);\r
- for (Resource shadow : shadows)\r
- forwardDependencies.addAll(graph.getObjects(shadow, sr.Variable_isTailOf));\r
- \r
- for (Resource dependency : forwardDependencies) {\r
- Resource dependingVariable = graph.getSingleObject(dependency, sr.Variable_HasHead);\r
- if (dependingVariable.equals(loopItems.get((i + 1) % loopItems.size()))) {\r
- if (graph.isInstanceOf(dependency, sr.Flow)\r
- && graph.isInstanceOf(loopItems.get(i), sr.Stock)) {\r
- // Flows from stocks don't count. \r
- continue;\r
- }\r
- skipBackwardFlows = true;\r
- dependencyItems.add(graph.getSingleObject(dependency, mod.ConnectionToDiagramConnection));\r
- break;\r
- }\r
- }\r
- \r
- if (skipBackwardFlows)\r
- continue;\r
- \r
- // Backward flows from stocks.\r
- Collection<Resource> backwardFlows = graph.getObjects(loopItems.get(i), sr.Variable_isHeadOf);\r
- for (Resource flow : backwardFlows) {\r
- if (graph.isInstanceOf(flow, sr.Flow)) {\r
- Resource dependingVariable = graph.getSingleObject(flow, sr.Variable_HasTail);\r
- if (dependingVariable.equals(loopItems.get((i + 1) % loopItems.size()))\r
- && graph.isInstanceOf(dependingVariable, sr.Stock)) {\r
- dependencyItems.add(graph.getSingleObject(flow, mod.ConnectionToDiagramConnection));\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- \r
- // Convert variables from component to element.\r
- for (int i = 0; i < loopItems.size(); ++i) {\r
- loopItems.set(i, graph.getPossibleObject(loopItems.get(i), mod.ComponentToElement));\r
- }\r
- // Merge the two lists.\r
- loopItems.addAll(dependencyItems);\r
- \r
- return loopItems;\r
- }\r
- \r
- });\r
- } catch (DatabaseException e1) {\r
- // TODO Auto-generated catch block\r
- e1.printStackTrace();\r
- }\r
- \r
- return loopItems;\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2014 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.sysdyn.ui.elements;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.diagram.elements.DiagramNodeUtil;
+import org.simantics.g2d.element.ElementHints;
+import org.simantics.g2d.element.IElement;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.scenegraph.INode;
+import org.simantics.scenegraph.ParentNode;
+import org.simantics.scenegraph.g2d.IG2DNode;
+import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
+import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
+import org.simantics.scenegraph.utils.NodeUtil;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Node for Sysdyn loop elements.
+ *
+ * @author Tuomas Miettinen
+ *
+ */
+public class LoopNode extends HoverShapeNode {
+
+ /**
+ * Interface for nodes that can be part of loops
+ * @author Tuomas Miettinen
+ *
+ */
+ public interface ILoopComponentNode {
+
+ /**
+ * Sets or resets the loop selected status
+ * @param loop The loop which has been selected
+ * @param selected true iff the loop is selected
+ */
+ public void setLoopSelected(LoopNode loop, boolean selected);
+
+ }
+
+ public static Color HIGHLIGHT_COLOR = Color.decode("#ff5fbf");
+
+ private boolean selected = false;
+
+ private static final long serialVersionUID = 6173159124691715569L;
+
+ @Override
+ public void render(Graphics2D g2d) {
+ super.render(g2d);
+
+ // If the loop is selected, highlight also the elements that belong to the loop.
+ boolean selected = NodeUtil.isSelected(this, 1);
+ // Do nothing if the selection is and was off.
+ if (selected || this.selected != selected) {
+ this.selected = selected;
+ // Tell all items belonging to the loop that the loop is selected.
+ setLoopItemsSelected();
+ }
+ }
+
+ private void setLoopItemsSelected() {
+ // Get all variables and dependencies in the loop.
+ List<Resource> loopItems = getAllLoopItems();
+
+ // Get the diagram where this loop is.
+ RTreeNode diagramNode = (RTreeNode)NodeUtil.getPossibleNearestParentOfType(this, RTreeNode.class);
+ if (diagramNode == null)
+ return;
+
+ // Go through all elements on the diagram where this loop is.
+ Collection<IG2DNode> children = diagramNode.getNodes();
+ Iterator<IG2DNode> it = children.iterator();
+ while (it.hasNext()) {
+ IG2DNode n = it.next();
+
+ // Get the respective node
+ INode child = getNodeOfPossibleLoopComponentNode(n);
+ if (child instanceof ILoopComponentNode) {
+ ILoopComponentNode ln = (ILoopComponentNode)child;
+ // Get the respective element
+ IElement e = DiagramNodeUtil.getElement((IG2DNode)child.getParent());
+ // Get the respective resource
+ Resource r = e.getHint(ElementHints.KEY_OBJECT);
+ // If the node belongs to the loop, tell it that whether the loop is selected or not.
+ ln.setLoopSelected(this, NodeUtil.isSelected(this, 1) && loopItems.contains(r));
+ }
+ }
+ }
+
+ /**
+ * Get the ILoopComponentNode under the variable, dependency, or flow.
+ * @param n node under which the ILoopComponentNode is sought
+ * @return ILoopComponentNode or null, if there is not any.
+ */
+ private static INode getNodeOfPossibleLoopComponentNode(IG2DNode n) {
+ // Get all nodeIds of n's children.
+ Collection<String> nodeIds = ((ParentNode<?>)n).getNodeIds();
+
+ // Flows and SysdynTextNodes
+ for (String id : nodeIds) {
+ if ("text".equals(id)
+ || id.startsWith("flow_"))
+ return ((ParentNode<?>)n).getNode(id);
+ }
+
+ // Dependencies
+ if (n instanceof ConnectionNode) {
+ // See the if a child of n has a DependencyNode as a child.
+ Iterator<IG2DNode> it = ((ConnectionNode) n).getNodes().iterator();
+ while (it.hasNext()) {
+ n = it.next();
+ if (n instanceof ParentNode<?>) {
+ nodeIds = ((ParentNode<?>)n).getNodeIds();
+ for (String id : nodeIds) {
+ if (id.startsWith("edge_"))
+ return ((ParentNode<?>)n).getNode(id);
+ }
+ }
+ }
+ }
+
+ return null; // n was no variable, dependency, or flow
+
+ }
+
+ /**
+ * Get all variables and dependencies in the loop.
+ * @return A list where the items are, in unspecified order.
+ */
+ private List<Resource> getAllLoopItems() {
+ IElement loopElement = DiagramNodeUtil.getElement(this);
+ final Resource loopSymbolResource = loopElement.getHint(ElementHints.KEY_OBJECT);
+ List<Resource> loopItems = Collections.emptyList();
+
+ try {
+ loopItems = Simantics.getSession().syncRequest(new Read<List<Resource>>(){
+
+ @Override
+ public List<Resource> perform(ReadGraph graph) throws DatabaseException {
+ ModelingResources mod = ModelingResources.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource loopComponentResource = graph.getPossibleObject(loopSymbolResource, mod.ElementToComponent);
+ if (loopComponentResource == null)
+ return Collections.emptyList();
+
+ Resource loopResource = graph.getPossibleObject(loopComponentResource, sr.Loop_Items);
+ if (loopResource == null)
+ return Collections.emptyList();
+
+ List<Resource> loopItems = ListUtils.toPossibleList(graph, loopResource);
+ if (loopItems == null)
+ return Collections.emptyList();
+
+ ArrayList<Resource> dependencyItems = new ArrayList<Resource>();
+
+ // Add dependencies and flows.
+ for (int i = 0; i < loopItems.size(); ++i) {
+ boolean skipBackwardFlows = false;
+
+ // Go through forward dependencies and flows
+ Collection<Resource> forwardDependencies = graph.getObjects(loopItems.get(i), sr.Variable_isTailOf);
+
+ // And also through the forward dependencies of possible shadows.
+ Collection<Resource> shadows = graph.getObjects(loopItems.get(i), sr.Shadow_original_Inverse);
+ for (Resource shadow : shadows)
+ forwardDependencies.addAll(graph.getObjects(shadow, sr.Variable_isTailOf));
+
+ for (Resource dependency : forwardDependencies) {
+ Resource dependingVariable = graph.getSingleObject(dependency, sr.Variable_HasHead);
+ if (dependingVariable.equals(loopItems.get((i + 1) % loopItems.size()))) {
+ if (graph.isInstanceOf(dependency, sr.Flow)
+ && graph.isInstanceOf(loopItems.get(i), sr.Stock)) {
+ // Flows from stocks don't count.
+ continue;
+ }
+ skipBackwardFlows = true;
+ dependencyItems.add(graph.getSingleObject(dependency, mod.ConnectionToDiagramConnection));
+ break;
+ }
+ }
+
+ if (skipBackwardFlows)
+ continue;
+
+ // Backward flows from stocks.
+ Collection<Resource> backwardFlows = graph.getObjects(loopItems.get(i), sr.Variable_isHeadOf);
+ for (Resource flow : backwardFlows) {
+ if (graph.isInstanceOf(flow, sr.Flow)) {
+ Resource dependingVariable = graph.getSingleObject(flow, sr.Variable_HasTail);
+ if (dependingVariable.equals(loopItems.get((i + 1) % loopItems.size()))
+ && graph.isInstanceOf(dependingVariable, sr.Stock)) {
+ dependencyItems.add(graph.getSingleObject(flow, mod.ConnectionToDiagramConnection));
+ break;
+ }
+ }
+ }
+ }
+
+ // Convert variables from component to element.
+ for (int i = 0; i < loopItems.size(); ++i) {
+ loopItems.set(i, graph.getPossibleObject(loopItems.get(i), mod.ComponentToElement));
+ }
+ // Merge the two lists.
+ loopItems.addAll(dependencyItems);
+
+ return loopItems;
+ }
+
+ });
+ } catch (DatabaseException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+
+ return loopItems;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.elements;\r
-\r
-import java.util.HashMap;\r
-\r
-import org.eclipse.jface.viewers.LabelProvider;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;\r
-import org.simantics.db.Resource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ShadowVariableReferenceDialogRunnable implements Runnable {\r
-\r
- private Resource shadow;\r
- private HashMap<String, Resource> possibleReferences;\r
- \r
- public ShadowVariableReferenceDialogRunnable(Resource shadow, HashMap<String, Resource> possibleReferences) {\r
- this.shadow = shadow;\r
- this.possibleReferences = possibleReferences;\r
- }\r
- \r
- @Override\r
- public void run() {\r
- Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
- \r
- ElementListSelectionDialog dialog = \r
- new ElementListSelectionDialog(shell, new LabelProvider());\r
- dialog.setElements(possibleReferences.keySet().toArray(new String[possibleReferences.keySet().size()]));\r
- dialog.setTitle("Select referred variable");\r
- dialog.setMultipleSelection(false);\r
- \r
- dialog.open();\r
- \r
- Object[] result = dialog.getResult(); \r
- \r
- Resource resource = null;\r
- if(result != null && result.length == 1)\r
- resource = possibleReferences.get(result[0]);\r
- \r
- SimanticsUI.getSession().asyncRequest(new ShadowVariableReferenceRequest(shadow, resource));\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.elements;
+
+import java.util.HashMap;
+
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.dialogs.ElementListSelectionDialog;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+
+public class ShadowVariableReferenceDialogRunnable implements Runnable {
+
+ private Resource shadow;
+ private HashMap<String, Resource> possibleReferences;
+
+ public ShadowVariableReferenceDialogRunnable(Resource shadow, HashMap<String, Resource> possibleReferences) {
+ this.shadow = shadow;
+ this.possibleReferences = possibleReferences;
+ }
+
+ @Override
+ public void run() {
+ Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
+
+ ElementListSelectionDialog dialog =
+ new ElementListSelectionDialog(shell, new LabelProvider());
+ dialog.setElements(possibleReferences.keySet().toArray(new String[possibleReferences.keySet().size()]));
+ dialog.setTitle("Select referred variable");
+ dialog.setMultipleSelection(false);
+
+ dialog.open();
+
+ Object[] result = dialog.getResult();
+
+ Resource resource = null;
+ if(result != null && result.length == 1)
+ resource = possibleReferences.get(result[0]);
+
+ Simantics.getSession().asyncRequest(new ShadowVariableReferenceRequest(shadow, resource));
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT - initial API and implementation\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.elements;\r
-\r
-import java.awt.Color;\r
-import java.awt.geom.AffineTransform;\r
-import java.util.function.Consumer;\r
-\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.ui.IWorkbenchPage;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.elements.DiagramNodeUtil;\r
-import org.simantics.diagram.elements.ITextListener;\r
-import org.simantics.diagram.elements.TextElementNoBounds;\r
-import org.simantics.diagram.elements.TextNode;\r
-import org.simantics.diagram.participant.SGFocusParticipant;\r
-import org.simantics.g2d.canvas.ICanvasContext;\r
-import org.simantics.g2d.chassis.SWTChassis;\r
-import org.simantics.g2d.diagram.DiagramUtils;\r
-import org.simantics.g2d.diagram.IDiagram;\r
-import org.simantics.g2d.element.ElementHints;\r
-import org.simantics.g2d.element.ElementUtils;\r
-import org.simantics.g2d.element.IElement;\r
-import org.simantics.g2d.utils.Alignment;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
-import org.simantics.modeling.ui.diagramEditor.DiagramViewer;\r
-import org.simantics.scenegraph.g2d.G2DParentNode;\r
-import org.simantics.scenegraph.g2d.events.MouseEvent;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
-import org.simantics.sysdyn.ui.utils.VariableNameValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
-import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
-\r
-/**\r
- * TextElement for variables in Siamntics System Dynamics\r
- * \r
- * The main differences for the basic TextElementNoBounds are:\r
- * 1. Text is never mirrored\r
- * 2. Edit mode is activated when the variable is created\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class SysdynTextElementNoBounds extends TextElementNoBounds {\r
-\r
- private static final long serialVersionUID = -148784588840819612L;\r
- \r
- public static final Key ELEMENT_INITIALIZED = new KeyOf(Boolean.class, "SYSDYN_TEXT_ELEMENT_INITIALIZED");\r
-\r
- // Constructors \r
- public SysdynTextElementNoBounds() {\r
- super(0, 0, Alignment.LEADING, 0);\r
- }\r
-\r
- public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment) {\r
- super(originX, originY, horizontalAlignment, 0);\r
- }\r
-\r
- public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment, double borderWidth) {\r
- super(originX, originY, horizontalAlignment, borderWidth);\r
- }\r
-\r
- public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment, double borderWidth, double paddingX, double paddingY, boolean editable) {\r
- super(originX, originY, horizontalAlignment, borderWidth, paddingX, paddingY, editable);\r
- }\r
-\r
- // End constructors\r
-\r
- protected <T extends SysdynTextNode> Consumer<T> getCallback(final IElement e, G2DParentNode parent, Class<T> nodeClass) {\r
- return new Consumer<T>() {\r
- @Override\r
- public void accept(T node) {\r
- node.setTextListener(new ITextListener() {\r
-\r
- String textBeforeEdit;\r
- Resource component;\r
-\r
- @Override\r
- public void textChanged() {\r
- TextNode node = (TextNode) e.getHint(SG_NODE);\r
- if(!new VariableNameValidator().isValid(component, node.getText(), false)) {\r
- node.setColor(Color.RED);\r
- } else {\r
- node.setColor(ElementUtils.getTextColor(e, Color.BLACK));\r
- }\r
-\r
-\r
- }\r
-\r
- @Override\r
- public void textEditingStarted() {\r
- TextNode node = (TextNode) e.getHint(SG_NODE);\r
- if (node == null)\r
- return;\r
- textBeforeEdit = node.getText();\r
-\r
- if(component != null) return;\r
- \r
- Object o = e.getHint(ElementHints.KEY_OBJECT);\r
- if(o != null && o instanceof Resource) {\r
- final Resource element = (Resource)o;\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- component = graph.getPossibleObject(element, ModelingResources.getInstance(graph).ElementToComponent);\r
- }\r
- });\r
- }\r
- }\r
-\r
- @Override\r
- public void textEditingCancelled() {\r
- TextNode node = (TextNode) e.getHint(SG_NODE);\r
- if (node != null) {\r
- if(new VariableNameValidator().isValid(component, node.getText(), false))\r
- node.setColor(ElementUtils.getTextColor(e, Color.BLACK));\r
- endEdit(node);\r
- }\r
- }\r
-\r
- @Override\r
- public void textEditingEnded() {\r
- TextNode node = (TextNode) e.getHint(SG_NODE);\r
- if (node == null)\r
- return;\r
- String text = node.getText();\r
- if(!new VariableNameValidator().isValid(component, text, false)) {\r
- text = textBeforeEdit;\r
- node.setEditMode(false);\r
- node.setText(text);\r
- if(new VariableNameValidator().isValid(component, text, false))\r
- node.setColor(ElementUtils.getTextColor(e, Color.BLACK));\r
- } else {\r
- Object o = e.getHint(ElementHints.KEY_OBJECT);\r
- final String textAfterEdit = text;\r
- if(o != null && o instanceof Resource) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Resource configuration = graph.getPossibleObject(component, Layer0.getInstance(graph).PartOf);\r
- new VariableNameValidator().renameInAllEquations(graph, configuration, textBeforeEdit, textAfterEdit);\r
- }\r
- });\r
- }\r
- }\r
- ElementUtils.setText(e, text);\r
- IDiagram diagram = ElementUtils.getDiagram(e);\r
- DiagramUtils.synchronizeHintsToBackend(diagram, e);\r
- endEdit(node);\r
- }\r
- });\r
- }\r
- };\r
- }\r
- \r
- /**\r
- * Reverts any rotations that are assigned to the text element\r
- * @param e\r
- */\r
- public static void unflipText(IElement e) {\r
- Object o = e.getHint(SG_NODE);\r
- if (o instanceof TextNode) {\r
- TextNode text = (TextNode)o;\r
- AffineTransform at = new AffineTransform(text.getTransform());\r
- double x = at.getTranslateX();\r
- double y = at.getTranslateY();\r
- at.setToRotation(0);\r
- at.setToTranslation(x, y);\r
- at.setTransform(at);\r
- }\r
- }\r
- \r
- /**\r
- * Activates edit mode for a newly created variable. \r
- * \r
- * Sets focus for diagram if the variable was created by dragging from model browser.\r
- * \r
- * @param e\r
- */\r
- protected void activateEdit(final IElement e) {\r
- final SysdynTextNode node = e.getHint(SG_NODE);\r
- if(node == null)\r
- return;\r
- \r
- final ICanvasContext ctx = DiagramNodeUtil.getCanvasContext(node);\r
- // FIXME: needed only because eventdelegator registrations are done before adding node to scene graph.\r
- if (ctx == null)\r
- return;\r
- if (!node.isEditMode()) {\r
- \r
- // Get the active editor\r
- IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();\r
- final DiagramEditor editor = (DiagramEditor)page.getActiveEditor();\r
- final ICanvasContext editorCtx = (ICanvasContext) editor.getViewer().getAdapter(ICanvasContext.class);\r
-\r
- editor.getViewer().getComposite().getDisplay().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- Control c = editor.getViewer().getComposite().getDisplay().getFocusControl();\r
- if (c == null || "BasicSymbols".equals(c.getParent().getToolTipText())) {\r
- // If the variable has been drag and dropped, set focus to diagram and then activate edit.\r
- \r
- editorCtx.add(new SGFocusParticipant((SWTChassis)editor.getViewer().getComposite(), DiagramViewer.DIAGRAMMING_CONTEXT) {\r
- \r
- @Override\r
- public void focusGained(java.awt.event.FocusEvent event) {\r
- \r
- // When focus has been gained, acticate edit and destroy the listener.\r
- editor.getViewer().getComposite().getDisplay().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- if (Boolean.TRUE.equals(node.setEditMode(true))) {\r
- node.activateEdit(0, e, ctx, true);\r
- node.repaint();\r
- }\r
- }\r
- });\r
- ctx.remove(this);\r
- }\r
- \r
- @Override\r
- public void focusLost(java.awt.event.FocusEvent e) {\r
- }\r
- });\r
- \r
- editor.setFocus();\r
- } else {\r
- // If the variable has been created with shortcut key, just activate the edit.\r
- if (Boolean.TRUE.equals(node.setEditMode(true))) {\r
- node.activateEdit(0, e, ctx, true);\r
- node.repaint();\r
- }\r
- }\r
- }\r
- }); \r
- }\r
- }\r
- \r
- @Override\r
- protected TextNode getOrCreateTextNode(IElement e, G2DParentNode parent) {\r
- return ElementUtils.getOrCreateNode(e, parent, SG_NODE, "text", SysdynTextNode.class, getCallback(e, parent, SysdynTextNode.class));\r
- }\r
- \r
- @Override\r
- public void init(final IElement e, G2DParentNode parent) {\r
- super.init(e, parent);\r
-\r
- \r
- // Add handling for activating text edit for new variables\r
- // Store initialization status to hints to prevent unnecessary graph queries\r
- Boolean isInitialized = e.getHint(ELEMENT_INITIALIZED); \r
- Object o = e.getHint(ElementHints.KEY_OBJECT);\r
- if (o instanceof Resource && !Boolean.TRUE.equals(isInitialized)) {\r
- final Resource element = (Resource)o;\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- ModelingResources MR = ModelingResources.getInstance(graph);\r
- Resource component = graph.getPossibleObject(element, MR.ElementToComponent);\r
- if (component == null)\r
- return;\r
- \r
- // See if the resource of the element has just been created. \r
- Resource r = graph.getPossibleObject(component, SR.IndependentVariable_isUninitialized);\r
- if (r == null){\r
- return;\r
- }\r
- \r
- // If the resource is just been created, activate editing its name.\r
- if (!graph.isInstanceOf(r, SR.Loop)) {\r
- activateEdit(e);\r
- }\r
- graph.deny(component, SR.IndependentVariable_isUninitialized, r);\r
- }\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- e.setHint(ELEMENT_INITIALIZED, Boolean.TRUE);\r
- }\r
- \r
- unflipText(e);\r
- }\r
- \r
- @Override\r
- public boolean handleMouseEvent(IElement e, final ICanvasContext ctx, MouseEvent me) {\r
- //if (!(me instanceof MouseEnterEvent) && !(me instanceof MouseMovedEvent) && !(me instanceof MouseExitEvent))\r
- //System.out.println(me instanceof MouseDragBegin ? "drag begin" : "no drag begin");\r
- //SysdynWorkbenchUtils.setHoveringHint(ctx, me, SysdynTextElementNoBounds.this);\r
- return super.handleMouseEvent(e, ctx, me);\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 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 - initial API and implementation
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.elements;
+
+import java.awt.Color;
+import java.awt.geom.AffineTransform;
+import java.util.function.Consumer;
+
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.IWorkbenchPage;
+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.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.diagram.elements.DiagramNodeUtil;
+import org.simantics.diagram.elements.ITextListener;
+import org.simantics.diagram.elements.TextElementNoBounds;
+import org.simantics.diagram.elements.TextNode;
+import org.simantics.diagram.participant.SGFocusParticipant;
+import org.simantics.g2d.canvas.ICanvasContext;
+import org.simantics.g2d.chassis.SWTChassis;
+import org.simantics.g2d.diagram.DiagramUtils;
+import org.simantics.g2d.diagram.IDiagram;
+import org.simantics.g2d.element.ElementHints;
+import org.simantics.g2d.element.ElementUtils;
+import org.simantics.g2d.element.IElement;
+import org.simantics.g2d.utils.Alignment;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;
+import org.simantics.modeling.ui.diagramEditor.DiagramViewer;
+import org.simantics.scenegraph.g2d.G2DParentNode;
+import org.simantics.scenegraph.g2d.events.MouseEvent;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;
+import org.simantics.sysdyn.ui.utils.VariableNameValidator;
+import org.simantics.utils.datastructures.hints.IHintContext.Key;
+import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
+
+/**
+ * TextElement for variables in Siamntics System Dynamics
+ *
+ * The main differences for the basic TextElementNoBounds are:
+ * 1. Text is never mirrored
+ * 2. Edit mode is activated when the variable is created
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class SysdynTextElementNoBounds extends TextElementNoBounds {
+
+ private static final long serialVersionUID = -148784588840819612L;
+
+ public static final Key ELEMENT_INITIALIZED = new KeyOf(Boolean.class, "SYSDYN_TEXT_ELEMENT_INITIALIZED");
+
+ // Constructors
+ public SysdynTextElementNoBounds() {
+ super(0, 0, Alignment.LEADING, 0);
+ }
+
+ public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment) {
+ super(originX, originY, horizontalAlignment, 0);
+ }
+
+ public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment, double borderWidth) {
+ super(originX, originY, horizontalAlignment, borderWidth);
+ }
+
+ public SysdynTextElementNoBounds(double originX, double originY, Alignment horizontalAlignment, double borderWidth, double paddingX, double paddingY, boolean editable) {
+ super(originX, originY, horizontalAlignment, borderWidth, paddingX, paddingY, editable);
+ }
+
+ // End constructors
+
+ protected <T extends SysdynTextNode> Consumer<T> getCallback(final IElement e, G2DParentNode parent, Class<T> nodeClass) {
+ return new Consumer<T>() {
+ @Override
+ public void accept(T node) {
+ node.setTextListener(new ITextListener() {
+
+ String textBeforeEdit;
+ Resource component;
+
+ @Override
+ public void textChanged() {
+ TextNode node = (TextNode) e.getHint(SG_NODE);
+ if(!new VariableNameValidator().isValid(component, node.getText(), false)) {
+ node.setColor(Color.RED);
+ } else {
+ node.setColor(ElementUtils.getTextColor(e, Color.BLACK));
+ }
+
+
+ }
+
+ @Override
+ public void textEditingStarted() {
+ TextNode node = (TextNode) e.getHint(SG_NODE);
+ if (node == null)
+ return;
+ textBeforeEdit = node.getText();
+
+ if(component != null) return;
+
+ Object o = e.getHint(ElementHints.KEY_OBJECT);
+ if(o != null && o instanceof Resource) {
+ final Resource element = (Resource)o;
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ component = graph.getPossibleObject(element, ModelingResources.getInstance(graph).ElementToComponent);
+ }
+ });
+ }
+ }
+
+ @Override
+ public void textEditingCancelled() {
+ TextNode node = (TextNode) e.getHint(SG_NODE);
+ if (node != null) {
+ if(new VariableNameValidator().isValid(component, node.getText(), false))
+ node.setColor(ElementUtils.getTextColor(e, Color.BLACK));
+ endEdit(node);
+ }
+ }
+
+ @Override
+ public void textEditingEnded() {
+ TextNode node = (TextNode) e.getHint(SG_NODE);
+ if (node == null)
+ return;
+ String text = node.getText();
+ if(!new VariableNameValidator().isValid(component, text, false)) {
+ text = textBeforeEdit;
+ node.setEditMode(false);
+ node.setText(text);
+ if(new VariableNameValidator().isValid(component, text, false))
+ node.setColor(ElementUtils.getTextColor(e, Color.BLACK));
+ } else {
+ Object o = e.getHint(ElementHints.KEY_OBJECT);
+ final String textAfterEdit = text;
+ if(o != null && o instanceof Resource) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Resource configuration = graph.getPossibleObject(component, Layer0.getInstance(graph).PartOf);
+ new VariableNameValidator().renameInAllEquations(graph, configuration, textBeforeEdit, textAfterEdit);
+ }
+ });
+ }
+ }
+ ElementUtils.setText(e, text);
+ IDiagram diagram = ElementUtils.getDiagram(e);
+ DiagramUtils.synchronizeHintsToBackend(diagram, e);
+ endEdit(node);
+ }
+ });
+ }
+ };
+ }
+
+ /**
+ * Reverts any rotations that are assigned to the text element
+ * @param e
+ */
+ public static void unflipText(IElement e) {
+ Object o = e.getHint(SG_NODE);
+ if (o instanceof TextNode) {
+ TextNode text = (TextNode)o;
+ AffineTransform at = new AffineTransform(text.getTransform());
+ double x = at.getTranslateX();
+ double y = at.getTranslateY();
+ at.setToRotation(0);
+ at.setToTranslation(x, y);
+ at.setTransform(at);
+ }
+ }
+
+ /**
+ * Activates edit mode for a newly created variable.
+ *
+ * Sets focus for diagram if the variable was created by dragging from model browser.
+ *
+ * @param e
+ */
+ protected void activateEdit(final IElement e) {
+ final SysdynTextNode node = e.getHint(SG_NODE);
+ if(node == null)
+ return;
+
+ final ICanvasContext ctx = DiagramNodeUtil.getCanvasContext(node);
+ // FIXME: needed only because eventdelegator registrations are done before adding node to scene graph.
+ if (ctx == null)
+ return;
+ if (!node.isEditMode()) {
+
+ // Get the active editor
+ IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();
+ final DiagramEditor editor = (DiagramEditor)page.getActiveEditor();
+ final ICanvasContext editorCtx = (ICanvasContext) editor.getViewer().getAdapter(ICanvasContext.class);
+
+ editor.getViewer().getComposite().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ Control c = editor.getViewer().getComposite().getDisplay().getFocusControl();
+ if (c == null || "BasicSymbols".equals(c.getParent().getToolTipText())) {
+ // If the variable has been drag and dropped, set focus to diagram and then activate edit.
+
+ editorCtx.add(new SGFocusParticipant((SWTChassis)editor.getViewer().getComposite(), DiagramViewer.DIAGRAMMING_CONTEXT) {
+
+ @Override
+ public void focusGained(java.awt.event.FocusEvent event) {
+
+ // When focus has been gained, acticate edit and destroy the listener.
+ editor.getViewer().getComposite().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if (Boolean.TRUE.equals(node.setEditMode(true))) {
+ node.activateEdit(0, e, ctx, true);
+ node.repaint();
+ }
+ }
+ });
+ ctx.remove(this);
+ }
+
+ @Override
+ public void focusLost(java.awt.event.FocusEvent e) {
+ }
+ });
+
+ editor.setFocus();
+ } else {
+ // If the variable has been created with shortcut key, just activate the edit.
+ if (Boolean.TRUE.equals(node.setEditMode(true))) {
+ node.activateEdit(0, e, ctx, true);
+ node.repaint();
+ }
+ }
+ }
+ });
+ }
+ }
+
+ @Override
+ protected TextNode getOrCreateTextNode(IElement e, G2DParentNode parent) {
+ return ElementUtils.getOrCreateNode(e, parent, SG_NODE, "text", SysdynTextNode.class, getCallback(e, parent, SysdynTextNode.class));
+ }
+
+ @Override
+ public void init(final IElement e, G2DParentNode parent) {
+ super.init(e, parent);
+
+
+ // Add handling for activating text edit for new variables
+ // Store initialization status to hints to prevent unnecessary graph queries
+ Boolean isInitialized = e.getHint(ELEMENT_INITIALIZED);
+ Object o = e.getHint(ElementHints.KEY_OBJECT);
+ if (o instanceof Resource && !Boolean.TRUE.equals(isInitialized)) {
+ final Resource element = (Resource)o;
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ ModelingResources MR = ModelingResources.getInstance(graph);
+ Resource component = graph.getPossibleObject(element, MR.ElementToComponent);
+ if (component == null)
+ return;
+
+ // See if the resource of the element has just been created.
+ Resource r = graph.getPossibleObject(component, SR.IndependentVariable_isUninitialized);
+ if (r == null){
+ return;
+ }
+
+ // If the resource is just been created, activate editing its name.
+ if (!graph.isInstanceOf(r, SR.Loop)) {
+ activateEdit(e);
+ }
+ graph.deny(component, SR.IndependentVariable_isUninitialized, r);
+ }
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ e.setHint(ELEMENT_INITIALIZED, Boolean.TRUE);
+ }
+
+ unflipText(e);
+ }
+
+ @Override
+ public boolean handleMouseEvent(IElement e, final ICanvasContext ctx, MouseEvent me) {
+ //if (!(me instanceof MouseEnterEvent) && !(me instanceof MouseMovedEvent) && !(me instanceof MouseExitEvent))
+ //System.out.println(me instanceof MouseDragBegin ? "drag begin" : "no drag begin");
+ //SysdynWorkbenchUtils.setHoveringHint(ctx, me, SysdynTextElementNoBounds.this);
+ return super.handleMouseEvent(e, ctx, me);
+ }
+
+}
-package org.simantics.sysdyn.ui.elements.connections;\r
-\r
-import java.awt.Color;\r
-import java.awt.Graphics2D;\r
-import java.awt.Stroke;\r
-import java.awt.geom.Path2D;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.diagram.connection.rendering.BasicConnectionStyle;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.elements.LoopNode;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class FlowConnectionStyle extends BasicConnectionStyle {\r
-\r
- private static final long serialVersionUID = 2777194644079591357L;\r
-\r
- Color lineColor;\r
- Stroke lineStroke;\r
-\r
- private Resource resource;\r
-\r
- // Is the default color overridden by the loop color\r
- private boolean loopColorOverride = false;\r
- \r
- public static final float DEFAULT_LINE_WIDTH = 1.0f;\r
-\r
- public FlowConnectionStyle(Color lineColor, Stroke lineStroke, Resource resource) {\r
- super(lineColor, Color.BLACK, 0.5, lineStroke, lineStroke, 0.8);\r
- this.lineColor = lineColor;\r
- this.lineStroke = lineStroke;\r
- this.resource = resource;\r
- }\r
- \r
- @Override\r
- public void drawBranchPoint(Graphics2D g, double x, double y) {\r
- }\r
-\r
- @Override\r
- public void drawLine(Graphics2D g, double x1, double y1, double x2, double y2, boolean isTransient) {\r
- }\r
-\r
- @Override\r
- public void drawPath(Graphics2D g, Path2D path, boolean isTransient) {\r
- if (lineColor != null) // Highlight the flow if loop where the flow belongs to is selected.\r
- g.setColor(loopColorOverride ? LoopNode.HIGHLIGHT_COLOR : lineColor);\r
- if (lineStroke != null)\r
- g.setStroke(lineStroke);\r
-\r
- // Fetch the width of the flow\r
- Float width = DEFAULT_LINE_WIDTH;\r
- try {\r
- Float connectionWidth = SimanticsUI.getSession().syncRequest(new Read<Float>() {\r
-\r
- @Override\r
- public Float perform(ReadGraph graph)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if (resource == null)\r
- return null;\r
- return graph.getPossibleRelatedValue(resource, sr.FlowConnection_width, Bindings.FLOAT);\r
- }\r
- });\r
- if (connectionWidth != null)\r
- width = connectionWidth; \r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- Path2D p1 = Flows.createOffsetPath(path, width/2);\r
- Path2D p2 = Flows.createOffsetPath(path, -width/2);\r
- p1.append(p2, false);\r
- g.draw(p1);\r
- }\r
-\r
- @Override\r
- public void drawDegeneratedLine(Graphics2D g, double x, double y, boolean isHorizontal, boolean isTransient) {\r
- }\r
-\r
- @Override\r
- public double getDegeneratedLineLength() {\r
- return 0;\r
- }\r
-\r
- /**\r
- * Set if the flow color should be overwritten with loop color\r
- * @param loopColorOverride \r
- */\r
- public void setLoopColorOverride(boolean loopColorOverride) {\r
- this.loopColorOverride = loopColorOverride;\r
- }\r
- \r
-}\r
+package org.simantics.sysdyn.ui.elements.connections;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.Stroke;
+import java.awt.geom.Path2D;
+
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.diagram.connection.rendering.BasicConnectionStyle;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.elements.LoopNode;
+
+public class FlowConnectionStyle extends BasicConnectionStyle {
+
+ private static final long serialVersionUID = 2777194644079591357L;
+
+ Color lineColor;
+ Stroke lineStroke;
+
+ private Resource resource;
+
+ // Is the default color overridden by the loop color
+ private boolean loopColorOverride = false;
+
+ public static final float DEFAULT_LINE_WIDTH = 1.0f;
+
+ public FlowConnectionStyle(Color lineColor, Stroke lineStroke, Resource resource) {
+ super(lineColor, Color.BLACK, 0.5, lineStroke, lineStroke, 0.8);
+ this.lineColor = lineColor;
+ this.lineStroke = lineStroke;
+ this.resource = resource;
+ }
+
+ @Override
+ public void drawBranchPoint(Graphics2D g, double x, double y) {
+ }
+
+ @Override
+ public void drawLine(Graphics2D g, double x1, double y1, double x2, double y2, boolean isTransient) {
+ }
+
+ @Override
+ public void drawPath(Graphics2D g, Path2D path, boolean isTransient) {
+ if (lineColor != null) // Highlight the flow if loop where the flow belongs to is selected.
+ g.setColor(loopColorOverride ? LoopNode.HIGHLIGHT_COLOR : lineColor);
+ if (lineStroke != null)
+ g.setStroke(lineStroke);
+
+ // Fetch the width of the flow
+ Float width = DEFAULT_LINE_WIDTH;
+ try {
+ Float connectionWidth = Simantics.getSession().syncRequest(new Read<Float>() {
+
+ @Override
+ public Float perform(ReadGraph graph)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if (resource == null)
+ return null;
+ return graph.getPossibleRelatedValue(resource, sr.FlowConnection_width, Bindings.FLOAT);
+ }
+ });
+ if (connectionWidth != null)
+ width = connectionWidth;
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ Path2D p1 = Flows.createOffsetPath(path, width/2);
+ Path2D p2 = Flows.createOffsetPath(path, -width/2);
+ p1.append(p2, false);
+ g.draw(p1);
+ }
+
+ @Override
+ public void drawDegeneratedLine(Graphics2D g, double x, double y, boolean isHorizontal, boolean isTransient) {
+ }
+
+ @Override
+ public double getDegeneratedLineLength() {
+ return 0;
+ }
+
+ /**
+ * Set if the flow color should be overwritten with loop color
+ * @param loopColorOverride
+ */
+ public void setLoopColorOverride(boolean loopColorOverride) {
+ this.loopColorOverride = loopColorOverride;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.elements.connections;\r
-\r
-import java.awt.BasicStroke;\r
-import java.awt.Color;\r
-import java.awt.Shape;\r
-import java.awt.Stroke;\r
-import java.awt.geom.AffineTransform;\r
-import java.awt.geom.Rectangle2D;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.HashSet;\r
-import java.util.Map;\r
-import java.util.Set;\r
-import java.util.concurrent.ConcurrentSkipListMap;\r
-import java.util.concurrent.atomic.AtomicInteger;\r
-\r
-import org.eclipse.jface.resource.StringConverter;\r
-import org.eclipse.swt.graphics.RGB;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.AsyncReadGraph;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.Statement;\r
-import org.simantics.db.common.procedure.adapter.TransientCacheListener;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.AsyncProcedure;\r
-import org.simantics.db.procedure.SyncMultiProcedure;\r
-import org.simantics.diagram.G2DUtils;\r
-import org.simantics.diagram.adapter.SyncElementFactory;\r
-import org.simantics.diagram.connection.ConnectionVisuals;\r
-import org.simantics.diagram.connection.RouteGraph;\r
-import org.simantics.diagram.connection.RouteGraphConnectionClass;\r
-import org.simantics.diagram.connection.RouteLine;\r
-import org.simantics.diagram.connection.RouteNode;\r
-import org.simantics.diagram.connection.RouteTerminal;\r
-import org.simantics.diagram.connection.rendering.ConnectionStyle;\r
-import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;\r
-import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;\r
-import org.simantics.diagram.content.EdgeResource;\r
-import org.simantics.diagram.content.ResourceTerminal;\r
-import org.simantics.diagram.content.TerminalMap;\r
-import org.simantics.diagram.query.DiagramRequests;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
-import org.simantics.diagram.synchronization.graph.RouteGraphConnection;\r
-import org.simantics.diagram.ui.DiagramModelHints;\r
-import org.simantics.g2d.canvas.ICanvasContext;\r
-import org.simantics.g2d.connection.ConnectionEntity;\r
-import org.simantics.g2d.diagram.DiagramHints;\r
-import org.simantics.g2d.diagram.IDiagram;\r
-import org.simantics.g2d.diagram.handler.DataElementMap;\r
-import org.simantics.g2d.diagram.handler.Topology.Connection;\r
-import org.simantics.g2d.diagram.handler.Topology.Terminal;\r
-import org.simantics.g2d.element.ElementClass;\r
-import org.simantics.g2d.element.ElementHints;\r
-import org.simantics.g2d.element.ElementUtils;\r
-import org.simantics.g2d.element.IElement;\r
-import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;\r
-import org.simantics.g2d.element.handler.TerminalTopology;\r
-import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;\r
-import org.simantics.g2d.routing.algorithm2.Router4;\r
-import org.simantics.g2d.utils.TopologicalSelectionExpander;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.scenegraph.g2d.nodes.connection.IRouteGraphListener;\r
-import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphChangeEvent;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.structural2.modelingRules.CPTerminal;\r
-import org.simantics.structural2.modelingRules.IAttachmentRelationMap;\r
-import org.simantics.structural2.modelingRules.IModelingRules;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;\r
-import org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferences;\r
-import org.simantics.sysdyn.ui.preferences.SysdynDiagramPropertyExternalRead;\r
-import org.simantics.utils.datastructures.Pair;\r
-/**\r
- * An element class for Sysdyn Flow elements.\r
- * Copied from RouteGraphConnectionClassFactory and adapted to Flow needs\r
- * \r
- * @author Teemu Lempinen\r
- * \r
- */\r
-public class RouteFlowConnectionFactory extends SyncElementFactory {\r
-\r
- public static final ElementClass CLASS = RouteFlowEdgeClass.FLOW_CLASS;\r
-\r
- Layer0 L0;\r
- DiagramResource DIA;\r
- StructuralResource2 STR;\r
- ModelingResources MOD;\r
-\r
- public RouteFlowConnectionFactory(ReadGraph graph) {\r
- this.L0 = Layer0.getInstance(graph);\r
- this.DIA = DiagramResource.getInstance(graph);\r
- this.STR = StructuralResource2.getInstance(graph);\r
- this.MOD = ModelingResources.getInstance(graph);\r
- }\r
-\r
- @Override\r
- public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType, final AsyncProcedure<ElementClass> procedure) {\r
- procedure.execute(graph, CLASS.newClassWith(false, new StaticObjectAdapter(elementType)));\r
- }\r
-\r
- @Override\r
- protected Resource getElementClassBaseType(AsyncReadGraph graph) {\r
- return graph.getService(SysdynResource.class).FlowConnection;\r
- }\r
-\r
- @Override\r
- public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource connection,\r
- final IElement element) throws DatabaseException {\r
-\r
- // Do we need this?\r
- element.setHint(DiagramHints.ROUTE_ALGORITHM, new Router4(false));\r
- IModelingRules modelingRules = diagram.getHint(DiagramModelHints.KEY_MODELING_RULES);\r
-\r
- Color color = null;\r
- DiagramResource DR = DiagramResource.getInstance(graph);\r
- G2DResource G2D = G2DResource.getInstance(graph);\r
- if (graph.isInstanceOf(connection, DR.ColorProvider)) {\r
- Statement colorStatement = graph.getPossibleStatement(connection, G2D.HasColor);\r
- if(colorStatement != null && !colorStatement.isAsserted(connection)) {\r
- element.setHint(ElementHints.KEY_TEXT_COLOR, G2DUtils.getColor(graph, colorStatement.getObject()));\r
- } else {\r
- String colorString = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(connection, SysdynDiagramPreferences.getColorPreferenceName(graph, connection))));\r
- if(colorString != null) {\r
- RGB rgb = StringConverter.asRGB(colorString, null);\r
- if(rgb != null) {\r
- color = new Color(rgb.red, rgb.green, rgb.blue);\r
- element.setHint(ElementHints.KEY_TEXT_COLOR, color);\r
- }\r
- }\r
-\r
- }\r
- }\r
-\r
- RouteGraph rg = new RouteGraph();\r
-\r
- Set<Resource> nodes = new HashSet<Resource>();\r
- Set<EdgeResource> links = new HashSet<EdgeResource>();\r
- Map<Object, RouteNode> nodeByData = new HashMap<Object, RouteNode>();\r
-\r
- // Needed to support ConnectionEntity#getTerminalConnections\r
- Set<BackendConnection> backendonnections = new HashSet<BackendConnection>();\r
-\r
- // Load all route graph interior RouteNodes: route lines and points\r
- for (Resource interiorNode : graph.getObjects(connection, DIA.HasInteriorRouteNode)) {\r
- if (graph.isInstanceOf(interiorNode, DIA.RouteLine)) {\r
- Boolean isHorizontal = graph.getRelatedValue(interiorNode, DIA.IsHorizontal, Bindings.BOOLEAN);\r
- Double position = graph.getRelatedValue(interiorNode, DIA.HasPosition, Bindings.DOUBLE);\r
- RouteLine line = rg.addLine(isHorizontal, position);\r
- line.setData( RouteGraphConnection.serialize(graph, interiorNode) );\r
-\r
- nodes.add( interiorNode );\r
- nodeByData.put( interiorNode, line );\r
-\r
- for (Resource connectedTo : graph.getObjects(interiorNode, DIA.AreConnected)) {\r
- links.add( new EdgeResource(interiorNode, connectedTo) );\r
- }\r
- } else if (graph.isInstanceOf(interiorNode, DIA.RoutePoint)) {\r
- // Not supported yet. Ignore.\r
- }\r
- }\r
-\r
- Rectangle2D bounds = new Rectangle2D.Double();\r
-\r
- // Load all node terminal connections as RouteTerminals\r
- for (Statement toConnector : graph.getStatements(connection, DIA.HasConnector)) {\r
- Resource connector = toConnector.getObject();\r
- Resource attachmentRelation = toConnector.getPredicate();\r
-\r
- Statement terminalStm = findTerminalStatement(graph, STR, connection, connector);\r
- if (terminalStm == null)\r
- // Ignore broken connector: attached to the connection but not to any terminal.\r
- continue;\r
-\r
- Resource terminalElement = terminalStm.getObject();\r
- Resource terminalElementType = graph.getPossibleType(terminalElement, DIA.Element);\r
- if (terminalElementType == null)\r
- // Ignore non-element terminal elements\r
- continue;\r
-\r
- Resource connectionRelation = graph.getInverse(terminalStm.getPredicate());\r
-\r
- // Discover node and terminal this connector is connected to.\r
- TerminalMap terminals = graph.syncRequest(DiagramRequests.elementTypeTerminals(terminalElementType),\r
- TransientCacheListener.<TerminalMap> instance());\r
- Resource terminal = terminals.getTerminal(connectionRelation);\r
- if (terminal == null) {\r
- System.err.println(getClass().getSimpleName()\r
- + ": Could not find terminal for connection point "\r
- + NameUtils.getSafeName(graph, connectionRelation, true)\r
- + " in element "\r
- + NameUtils.getSafeName(graph, terminalElement, true)); \r
- continue;\r
- }\r
-\r
- double[] position = graph.getRelatedValue(connector, DIA.HasRelativeLocation, Bindings.DOUBLE_ARRAY);\r
- if (position.length != 2)\r
- position = new double[] { 0, 0 };\r
-\r
- //System.out.println("terminalStm: " + NameUtils.toString(graph, terminalStm));\r
- AffineTransform terminalElementTr = getWorldTransform(graph, terminalElement);\r
-\r
- double x = terminalElementTr.getTranslateX();\r
- double y = terminalElementTr.getTranslateY();\r
- double minx = x-1, miny = y-1, maxx = x+1, maxy = y+1;\r
- int direction = 0x0;\r
-\r
- // Use modelingRules to ascertain the proper attachmentRelation\r
- // for this terminal connection, if available.\r
- if (modelingRules != null) {\r
- // Get attachmentRelation from modelingRules if possible.\r
- IAttachmentRelationMap map = modelingRules.getAttachmentRelations(graph, connection);\r
- Resource att = map.get(graph, new CPTerminal(terminalElement, terminal));\r
- if (att != null) {\r
- //System.out.println("modeling rules attachment: " + NameUtils.getSafeLabel(graph, att));\r
- attachmentRelation = att;\r
- }\r
- }\r
- //System.out.println("attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));\r
-\r
- // Get element bounds to decide allowed terminal direction(s)\r
- IElement te = graph.syncRequest(DiagramRequests.getElement(canvas, diagram, terminalElement, null));\r
- \r
- // Fetch the flow width\r
- float lw = FlowConnectionStyle.DEFAULT_LINE_WIDTH;\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Float width = graph.getPossibleRelatedValue(connection, sr.FlowConnection_width, Bindings.FLOAT);\r
- if (width != null)\r
- lw = width;\r
- \r
- if(te.getElementClass().containsClass(ValveSceneGraph.class)) {\r
- // Valve behaves differently. The flow must start inside the valve bounds\r
- ValveSceneGraph vs = te.getElementClass().getSingleItem(ValveSceneGraph.class);\r
- Rectangle2D size = new Rectangle2D.Double();\r
- vs.getValveBounds(te, size);\r
- Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(size, terminalElementTr);\r
- size = (Rectangle2D) shp;\r
- bounds.setFrame(new Rectangle2D.Double(size.getCenterX() - (lw/2), size.getCenterY() - (lw/2), lw, lw));\r
- } else {\r
- // Basic bounds\r
- bounds = ElementUtils.getElementShape(te).getBounds2D();\r
- Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(bounds, terminalElementTr);\r
- bounds.setFrame(shp.getBounds2D());\r
- }\r
- \r
- x = bounds.getCenterX();\r
- y = bounds.getCenterY();\r
-\r
- // Expand bounds by 4mm to make the connections enter the terminals\r
- // at a straight angle and from a distance instead of coming in\r
- // "horizontally".\r
- //GeometryUtils.expandRectangle(bounds, 4);\r
-\r
- minx = bounds.getMinX();\r
- miny = bounds.getMinY();\r
- maxx = bounds.getMaxX();\r
- maxy = bounds.getMaxY();\r
-\r
- Integer allowedDirections = graph.getPossibleRelatedValue(terminal, DIA.Terminal_AllowedDirections, Bindings.INTEGER);\r
-\r
- // Valve behaves differently. Allowed directions depend on the orientation of the valve\r
- if(te.getElementClass().containsClass(ValveSceneGraph.class)) {\r
- if(graph.hasStatement(terminalElement, sr.ValveSymbol_orientation, sr.Vertical)) {\r
- allowedDirections = 10; // Directions up and down (1010)\r
- } else {\r
- allowedDirections = 5; // Directions left and right (0101)\r
- }\r
- }\r
- if (allowedDirections != null) {\r
- direction |= allowedDirections;\r
- } else {\r
- direction |= RouteGraphConnectionClass.shortestDirectionOutOfBounds(x, y, bounds);\r
- }\r
-\r
- backendonnections.add(\r
- new BackendConnection(\r
- toEdgeEnd(graph, attachmentRelation, EdgeEnd.Begin),\r
- terminalElement,\r
- terminal)\r
- );\r
-\r
- if (direction == 0)\r
- // Accept any horizontal/vertical direction if nothing is defined\r
- direction = 0xf;\r
-\r
- //System.out.println("load line style: " + NameUtils.getSafeLabel(graph, attachmentRelation));\r
- ILineEndStyle endStyle = loadLineEndStyle(graph, te, attachmentRelation, color, lw);\r
-\r
- RouteTerminal routeTerminal = rg.addBigTerminal(/*x, y,*/ minx, miny, maxx, maxy, /*direction,*/ endStyle);\r
- routeTerminal.setData( RouteGraphConnection.serialize(graph, connector) );\r
-\r
- nodes.add( connector );\r
- nodeByData.put( connector, routeTerminal );\r
-\r
- for (Resource connectedTo : graph.getObjects(connector, DIA.AreConnected)) {\r
- links.add( new EdgeResource(connectedTo, connector) );\r
- }\r
- }\r
-\r
- // Finish route graph loading by Linking route nodes together\r
- for (EdgeResource link : links) {\r
- RouteNode n1 = nodeByData.get(link.first());\r
- RouteNode n2 = nodeByData.get(link.second());\r
- if (n1 == null || n2 == null) {\r
- System.err.println("Stray connection link found: " + link.toString(graph));\r
- continue;\r
- }\r
- rg.link(n1, n2);\r
- }\r
-\r
- // Load connection line style\r
- ConnectionStyle style = readConnectionStyle(graph, modelingRules, connection, element);\r
- StyledRouteGraphRenderer renderer = new StyledRouteGraphRenderer(style);\r
-\r
- // Finish element load\r
- element.setHint(RouteGraphConnectionClass.KEY_ROUTEGRAPH, rg);\r
- element.setHint(RouteGraphConnectionClass.KEY_RENDERER, renderer);\r
- element.setHint(RouteGraphConnectionClass.KEY_PICK_TOLERANCE, 0.5);\r
-\r
- // Initialize ConnectionEntity in element\r
- // NOTE: MUST use the mapped element with class CE, not the connection (element) were loading into.\r
- // GDS will synchronize element into mappedElement in a controlled manner.\r
- element.setHint(ElementHints.KEY_CONNECTION_ENTITY, new CE(diagram, connection, element, backendonnections));\r
-\r
- // Setup graph writeback support for route graph modifications\r
- final Session session = graph.getSession();\r
- element.setHint(RouteGraphConnectionClass.KEY_RG_LISTENER, new IRouteGraphListener() {\r
- @Override\r
- public void routeGraphChanged(RouteGraphChangeEvent event) {\r
- scheduleSynchronize(session, connection, event);\r
- }\r
- });\r
- \r
- // A complicated-looking procedure for obtaining all HasProperties to properties map\r
- final AtomicInteger ready = new AtomicInteger(1);\r
- final ConcurrentSkipListMap<String, Pair<Resource, Object>> properties = new ConcurrentSkipListMap<String, Pair<Resource, Object>>();\r
- graph.forEachPredicate(connection, new SyncMultiProcedure<Resource>() {\r
-\r
- @Override\r
- public void exception(ReadGraph graph, Throwable throwable) {\r
- throwable.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(ReadGraph graph, final Resource property) {\r
-\r
- ready.incrementAndGet();\r
- Layer0 l0;\r
- try {\r
- l0 = Layer0.getInstance(graph.getSession());\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- return;\r
- }\r
-\r
- graph.forIsSubrelationOf(property, l0.HasProperty, new AsyncProcedure<Boolean>() {\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph, Throwable throwable) {\r
- throwable.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph, final Boolean isProperty) {\r
-\r
- if(isProperty) {\r
-\r
- graph.forPossibleRelatedValue(connection, property, new AsyncProcedure<Object>() {\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph, Throwable throwable) {\r
- throwable.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph, final Object value) {\r
-\r
- Layer0 l0;\r
- try {\r
- l0 = Layer0.getInstance(graph.getSession());\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- return;\r
- }\r
-\r
- graph.forPossibleRelatedValue(property, l0.HasName, Bindings.STRING, new AsyncProcedure<String>() {\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph, Throwable throwable) {\r
- throwable.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph, String name) {\r
-\r
- properties.put(name, Pair.make(property, value));\r
- if(ready.decrementAndGet() == 0) {\r
- element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Pair<Resource, Object>>(properties));\r
- }\r
-\r
- }\r
-\r
- });\r
-\r
- }\r
-\r
- });\r
-\r
-\r
- } else {\r
-\r
- if(ready.decrementAndGet() == 0) {\r
- element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Pair<Resource, Object>>(properties));\r
- }\r
-\r
- }\r
-\r
- }\r
-\r
- });\r
- }\r
-\r
- @Override\r
- public void finished(ReadGraph graph) {\r
-\r
- if(ready.decrementAndGet() == 0) {\r
- element.setHint(DiagramHints.PROPERTIES, new HashMap<String, Object>(properties));\r
- }\r
-\r
- }\r
-\r
- });\r
-\r
- }\r
-\r
- private EdgeEnd toEdgeEnd(ReadGraph graph, Resource attachmentRelation, EdgeEnd defaultValue)\r
- throws DatabaseException {\r
- if (graph.isSubrelationOf(attachmentRelation, DIA.IsTailConnectorOf))\r
- return EdgeEnd.Begin;\r
- if (graph.isSubrelationOf(attachmentRelation, DIA.IsHeadConnectorOf))\r
- return EdgeEnd.End;\r
- return defaultValue;\r
- }\r
-\r
- private ConnectionStyle readConnectionStyle(ReadGraph graph, IModelingRules modelingRules, Resource connection,\r
- IElement element) throws DatabaseException {\r
- Resource connectionType = null;\r
- if (modelingRules != null)\r
- connectionType = modelingRules.getConnectionType(graph, connection);\r
- if (connectionType == null)\r
- connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);\r
-\r
- ConnectionVisuals cv = null;\r
- if (connectionType != null)\r
- cv = graph.syncRequest(DiagramRequests.getConnectionVisuals(connectionType),\r
- TransientCacheListener.<ConnectionVisuals> instance());\r
-\r
-\r
- Color lineColor = element.getHint(ElementHints.KEY_TEXT_COLOR);\r
- if (lineColor == null)\r
- lineColor = (cv != null && cv.toColor() != null) ? cv.toColor() : Color.DARK_GRAY;\r
-\r
- Stroke lineStroke = cv != null ? cv.stroke : null;\r
- if (lineStroke == null)\r
- lineStroke = new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, null, 0);\r
-\r
- return new FlowConnectionStyle(\r
- lineColor,\r
- lineStroke,\r
- connection);\r
- }\r
-\r
- /**\r
- * @param graph\r
- * @param STR\r
- * @param connection\r
- * @param connector\r
- * @return connection relation statement from diagram connection connector\r
- * to a node\r
- * @throws DatabaseException\r
- */\r
- private static Statement findTerminalStatement(ReadGraph graph, StructuralResource2 STR, Resource connection,\r
- Resource connector) throws DatabaseException {\r
- for (Statement stm : graph.getStatements(connector, STR.Connects)) {\r
- if (connection.equals(stm.getObject()))\r
- continue;\r
- return stm;\r
- }\r
- return null;\r
- }\r
-\r
- public ILineEndStyle loadLineEndStyle(ReadGraph graph, IElement te, Resource attachmentRelation, Color color, float lineWidth)\r
- throws DatabaseException {\r
- ILineEndStyle style;\r
- // TODO: change bounds according to terminal type: Very small rectangle for Valves, Text box size for Stocks and Clouds\r
- if(te.getElementClass().containsClass(ValveSceneGraph.class)) {\r
- style = new FlowArrowLineStyle("none 0 0 0", color);\r
- } else {\r
- if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector)) {\r
- float arrowSize = lineWidth * 1.3f;\r
- style = new FlowArrowLineStyle("fill " + arrowSize + " " + arrowSize + " 0", color);\r
- } else {\r
- style = new FlowArrowLineStyle("none 0 0 0", color);\r
- }\r
- }\r
- return style;\r
- }\r
-\r
- /**\r
- * @param graph\r
- * @param element\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- private static AffineTransform getWorldTransform(ReadGraph graph, Resource element) throws DatabaseException {\r
- ModelingResources MOD = ModelingResources.getInstance(graph);\r
- AffineTransform result = DiagramGraphUtil.getAffineTransform(graph, element);\r
- while (true) {\r
- Resource parentComponent = graph.getPossibleObject(element, MOD.HasParentComponent);\r
- if (parentComponent == null)\r
- return result;\r
- element = graph.getPossibleObject(parentComponent, MOD.ComponentToElement);\r
- if (element == null)\r
- return result;\r
- AffineTransform tr = DiagramGraphUtil.getAffineTransform(graph, element);\r
- tr.setToTranslation(tr.getTranslateX(), tr.getTranslateY());\r
- result.preConcatenate(tr);\r
- }\r
- }\r
-\r
-\r
- protected void scheduleSynchronize(Session session, Resource connection, RouteGraphChangeEvent event) {\r
- session.asyncRequest(RouteGraphConnection.synchronizer(connection, event));\r
- }\r
-\r
- /**\r
- * Must have this in order for {@link TopologicalSelectionExpander} to work.\r
- * Otherwise this is pretty useless and should be deprecated altogether.\r
- * \r
- * @see ElementHints#KEY_CONNECTION_ENTITY\r
- */\r
- static class CE implements ConnectionEntity {\r
-\r
- \r
- private IDiagram diagram;\r
-\r
- private transient DataElementMap dataMap;\r
- \r
- /**\r
- * The connection instance resource in the graph backend.\r
- */\r
- final Resource connection;\r
-\r
- /**\r
- * The connection entity element which is a part of the diagram.\r
- */\r
- IElement connectionElement;\r
-\r
- /**\r
- * @see #getTerminalConnections(Collection)\r
- */\r
- final Set<BackendConnection> backendConnections;\r
-\r
- /**\r
- * Cache.\r
- */\r
- Set<Connection> terminalConnections;\r
-\r
- \r
- public CE(IDiagram diagram, Resource connection, IElement connectionElement, Set<BackendConnection> backendConnections) {\r
- if (connectionElement == null)\r
- throw new NullPointerException("null connection element");\r
- this.diagram = diagram;\r
- this.dataMap = diagram.getDiagramClass().getSingleItem(DataElementMap.class);\r
- this.connection = connection;\r
- this.connectionElement = connectionElement;\r
- this.backendConnections = backendConnections;\r
- IElement ce = getConnection0();\r
- if (ce != null)\r
- this.connectionElement = ce;\r
- }\r
-\r
- public IElement getConnection0() {\r
- IElement connectionElement = dataMap.getElement(diagram, connection);\r
- return connectionElement;\r
- }\r
-\r
- @Override\r
- public IElement getConnection() {\r
- IElement c = getConnection0();\r
- if (c == null)\r
- c = this.connectionElement;\r
- return c;\r
- }\r
-\r
- public Object getConnectionObject() {\r
- return connection;\r
- }\r
-\r
- public IElement getConnectionElement() {\r
- return connectionElement;\r
- }\r
-\r
- @Override\r
- public Collection<IElement> getBranchPoints(Collection<IElement> result) {\r
- return result != null ? result : Collections.<IElement> emptyList();\r
- }\r
-\r
- @Override\r
- public Collection<IElement> getSegments(Collection<IElement> result) {\r
- return result != null ? result : Collections.<IElement> emptyList();\r
- }\r
-\r
- @Override\r
- public Collection<Connection> getTerminalConnections(Collection<Connection> result) {\r
- if (terminalConnections == null)\r
- terminalConnections = calculateTerminalConnections();\r
- if (result == null)\r
- result = new ArrayList<Connection>(terminalConnections);\r
- else\r
- result.addAll(terminalConnections);\r
- return terminalConnections;\r
- }\r
-\r
- private Set<Connection> calculateTerminalConnections() {\r
- DataElementMap dem = diagram.getDiagramClass().getSingleItem(DataElementMap.class);\r
- Set<Connection> result = new HashSet<Connection>();\r
- ArrayList<Terminal> ts = new ArrayList<Terminal>();\r
- for (BackendConnection bc : backendConnections) {\r
- IElement e = dem.getElement(diagram, bc.node);\r
- if (e == null)\r
- continue;\r
- TerminalTopology tt = e.getElementClass().getSingleItem(TerminalTopology.class);\r
- tt.getTerminals(e, ts);\r
- for (Terminal t : ts) {\r
- if (t instanceof ResourceTerminal) {\r
- ResourceTerminal rt = (ResourceTerminal) t;\r
- if (bc.terminal.equals(rt.getResource())) {\r
- result.add(new Connection(connectionElement, bc.end, e, t));\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- return result;\r
- }\r
-\r
- @Override\r
- public void setListener(ConnectionListener listener) {\r
- throw new UnsupportedOperationException();\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return getClass().getSimpleName() + "[resource=" + connection + ", connectionElement=" + connectionElement\r
- + "]";\r
- }\r
-\r
- }\r
-\r
- public static class BackendConnection {\r
- public final Resource node;\r
- public final Resource terminal;\r
- public final EdgeEnd end;\r
- public BackendConnection(EdgeEnd end, Resource node, Resource terminal) {\r
- assert end != null;\r
- assert node != null;\r
- assert terminal != null;\r
- this.end = end;\r
- this.node = node;\r
- this.terminal = terminal;\r
- }\r
- @Override\r
- public boolean equals(Object obj) {\r
- if (this == obj)\r
- return true;\r
- if (!(obj instanceof Connection))\r
- return false;\r
- Connection other = (Connection) obj;\r
- return other.terminal == terminal\r
- && other.node == node\r
- && other.end == end;\r
- }\r
- @Override\r
- public int hashCode() {\r
- final int prime = 31;\r
- int result = 1;\r
- result = prime * result + end.hashCode();\r
- result = prime * result + ((node == null) ? 0 : node.hashCode());\r
- result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());\r
- return result;\r
- }\r
- @Override\r
- public String toString() {\r
- return "BackendConnection[node=" + node + ", terminal=" + terminal + ", end=" + end + "]";\r
- }\r
- }\r
-\r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.elements.connections;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Shape;
+import java.awt.Stroke;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.eclipse.jface.resource.StringConverter;
+import org.eclipse.swt.graphics.RGB;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.Statement;
+import org.simantics.db.common.procedure.adapter.TransientCacheListener;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.procedure.AsyncProcedure;
+import org.simantics.diagram.G2DUtils;
+import org.simantics.diagram.adapter.SyncElementFactory;
+import org.simantics.diagram.connection.ConnectionVisuals;
+import org.simantics.diagram.connection.RouteGraph;
+import org.simantics.diagram.connection.RouteGraphConnectionClass;
+import org.simantics.diagram.connection.RouteLine;
+import org.simantics.diagram.connection.RouteNode;
+import org.simantics.diagram.connection.RouteTerminal;
+import org.simantics.diagram.connection.rendering.ConnectionStyle;
+import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;
+import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
+import org.simantics.diagram.content.EdgeResource;
+import org.simantics.diagram.content.ResourceTerminal;
+import org.simantics.diagram.content.TerminalMap;
+import org.simantics.diagram.query.DiagramRequests;
+import org.simantics.diagram.stubs.DiagramResource;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
+import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
+import org.simantics.diagram.ui.DiagramModelHints;
+import org.simantics.g2d.canvas.ICanvasContext;
+import org.simantics.g2d.connection.ConnectionEntity;
+import org.simantics.g2d.diagram.DiagramHints;
+import org.simantics.g2d.diagram.IDiagram;
+import org.simantics.g2d.diagram.handler.DataElementMap;
+import org.simantics.g2d.diagram.handler.Topology.Connection;
+import org.simantics.g2d.diagram.handler.Topology.Terminal;
+import org.simantics.g2d.element.ElementClass;
+import org.simantics.g2d.element.ElementHints;
+import org.simantics.g2d.element.ElementUtils;
+import org.simantics.g2d.element.IElement;
+import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
+import org.simantics.g2d.element.handler.TerminalTopology;
+import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
+import org.simantics.g2d.routing.algorithm2.Router4;
+import org.simantics.g2d.utils.TopologicalSelectionExpander;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.scenegraph.g2d.nodes.connection.IRouteGraphListener;
+import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphChangeEvent;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.structural2.modelingRules.CPTerminal;
+import org.simantics.structural2.modelingRules.IAttachmentRelationMap;
+import org.simantics.structural2.modelingRules.IModelingRules;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPreferences;
+import org.simantics.sysdyn.ui.preferences.SysdynDiagramPropertyExternalRead;
+import org.simantics.utils.datastructures.Pair;
+/**
+ * An element class for Sysdyn Flow elements.
+ * Copied from RouteGraphConnectionClassFactory and adapted to Flow needs
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class RouteFlowConnectionFactory extends SyncElementFactory {
+
+ public static final ElementClass CLASS = RouteFlowEdgeClass.FLOW_CLASS;
+
+ Layer0 L0;
+ DiagramResource DIA;
+ StructuralResource2 STR;
+ ModelingResources MOD;
+
+ public RouteFlowConnectionFactory(ReadGraph graph) {
+ this.L0 = Layer0.getInstance(graph);
+ this.DIA = DiagramResource.getInstance(graph);
+ this.STR = StructuralResource2.getInstance(graph);
+ this.MOD = ModelingResources.getInstance(graph);
+ }
+
+ @Override
+ public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType, final AsyncProcedure<ElementClass> procedure) {
+ procedure.execute(graph, CLASS.newClassWith(false, new StaticObjectAdapter(elementType)));
+ }
+
+ @Override
+ protected Resource getElementClassBaseType(AsyncReadGraph graph) {
+ return graph.getService(SysdynResource.class).FlowConnection;
+ }
+
+ @Override
+ public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource connection,
+ final IElement element) throws DatabaseException {
+
+ // Do we need this?
+ element.setHint(DiagramHints.ROUTE_ALGORITHM, new Router4(false));
+ IModelingRules modelingRules = diagram.getHint(DiagramModelHints.KEY_MODELING_RULES);
+
+ Color color = null;
+ DiagramResource DR = DiagramResource.getInstance(graph);
+ G2DResource G2D = G2DResource.getInstance(graph);
+ if (graph.isInstanceOf(connection, DR.ColorProvider)) {
+ Statement colorStatement = graph.getPossibleStatement(connection, G2D.HasColor);
+ if(colorStatement != null && !colorStatement.isAsserted(connection)) {
+ element.setHint(ElementHints.KEY_TEXT_COLOR, G2DUtils.getColor(graph, colorStatement.getObject()));
+ } else {
+ String colorString = graph.syncRequest(new SysdynDiagramPropertyExternalRead(new Pair<Resource, String>(connection, SysdynDiagramPreferences.getColorPreferenceName(graph, connection))));
+ if(colorString != null) {
+ RGB rgb = StringConverter.asRGB(colorString, null);
+ if(rgb != null) {
+ color = new Color(rgb.red, rgb.green, rgb.blue);
+ element.setHint(ElementHints.KEY_TEXT_COLOR, color);
+ }
+ }
+
+ }
+ }
+
+ RouteGraph rg = new RouteGraph();
+
+ Set<Resource> nodes = new HashSet<Resource>();
+ Set<EdgeResource> links = new HashSet<EdgeResource>();
+ Map<Object, RouteNode> nodeByData = new HashMap<Object, RouteNode>();
+
+ // Needed to support ConnectionEntity#getTerminalConnections
+ Set<BackendConnection> backendonnections = new HashSet<BackendConnection>();
+
+ // Load all route graph interior RouteNodes: route lines and points
+ for (Resource interiorNode : graph.getObjects(connection, DIA.HasInteriorRouteNode)) {
+ if (graph.isInstanceOf(interiorNode, DIA.RouteLine)) {
+ Boolean isHorizontal = graph.getRelatedValue(interiorNode, DIA.IsHorizontal, Bindings.BOOLEAN);
+ Double position = graph.getRelatedValue(interiorNode, DIA.HasPosition, Bindings.DOUBLE);
+ RouteLine line = rg.addLine(isHorizontal, position);
+ line.setData( RouteGraphConnection.serialize(graph, interiorNode) );
+
+ nodes.add( interiorNode );
+ nodeByData.put( interiorNode, line );
+
+ for (Resource connectedTo : graph.getObjects(interiorNode, DIA.AreConnected)) {
+ links.add( new EdgeResource(interiorNode, connectedTo) );
+ }
+ } else if (graph.isInstanceOf(interiorNode, DIA.RoutePoint)) {
+ // Not supported yet. Ignore.
+ }
+ }
+
+ Rectangle2D bounds = new Rectangle2D.Double();
+
+ // Load all node terminal connections as RouteTerminals
+ for (Statement toConnector : graph.getStatements(connection, DIA.HasConnector)) {
+ Resource connector = toConnector.getObject();
+ Resource attachmentRelation = toConnector.getPredicate();
+
+ Statement terminalStm = findTerminalStatement(graph, STR, connection, connector);
+ if (terminalStm == null)
+ // Ignore broken connector: attached to the connection but not to any terminal.
+ continue;
+
+ Resource terminalElement = terminalStm.getObject();
+ Resource terminalElementType = graph.getPossibleType(terminalElement, DIA.Element);
+ if (terminalElementType == null)
+ // Ignore non-element terminal elements
+ continue;
+
+ Resource connectionRelation = graph.getInverse(terminalStm.getPredicate());
+
+ // Discover node and terminal this connector is connected to.
+ TerminalMap terminals = graph.syncRequest(DiagramRequests.elementTypeTerminals(terminalElementType),
+ TransientCacheListener.<TerminalMap> instance());
+ Resource terminal = terminals.getTerminal(connectionRelation);
+ if (terminal == null) {
+ System.err.println(getClass().getSimpleName()
+ + ": Could not find terminal for connection point "
+ + NameUtils.getSafeName(graph, connectionRelation, true)
+ + " in element "
+ + NameUtils.getSafeName(graph, terminalElement, true));
+ continue;
+ }
+
+ double[] position = graph.getRelatedValue(connector, DIA.HasRelativeLocation, Bindings.DOUBLE_ARRAY);
+ if (position.length != 2)
+ position = new double[] { 0, 0 };
+
+ //System.out.println("terminalStm: " + NameUtils.toString(graph, terminalStm));
+ AffineTransform terminalElementTr = getWorldTransform(graph, terminalElement);
+
+ double x = terminalElementTr.getTranslateX();
+ double y = terminalElementTr.getTranslateY();
+ double minx = x-1, miny = y-1, maxx = x+1, maxy = y+1;
+ int direction = 0x0;
+
+ // Use modelingRules to ascertain the proper attachmentRelation
+ // for this terminal connection, if available.
+ if (modelingRules != null) {
+ // Get attachmentRelation from modelingRules if possible.
+ IAttachmentRelationMap map = modelingRules.getAttachmentRelations(graph, connection);
+ Resource att = map.get(graph, new CPTerminal(terminalElement, terminal));
+ if (att != null) {
+ //System.out.println("modeling rules attachment: " + NameUtils.getSafeLabel(graph, att));
+ attachmentRelation = att;
+ }
+ }
+ //System.out.println("attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
+
+ // Get element bounds to decide allowed terminal direction(s)
+ IElement te = graph.syncRequest(DiagramRequests.getElement(canvas, diagram, terminalElement, null));
+
+ // Fetch the flow width
+ float lw = FlowConnectionStyle.DEFAULT_LINE_WIDTH;
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Float width = graph.getPossibleRelatedValue(connection, sr.FlowConnection_width, Bindings.FLOAT);
+ if (width != null)
+ lw = width;
+
+ if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
+ // Valve behaves differently. The flow must start inside the valve bounds
+ ValveSceneGraph vs = te.getElementClass().getSingleItem(ValveSceneGraph.class);
+ Rectangle2D size = new Rectangle2D.Double();
+ vs.getValveBounds(te, size);
+ Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(size, terminalElementTr);
+ size = (Rectangle2D) shp;
+ bounds.setFrame(new Rectangle2D.Double(size.getCenterX() - (lw/2), size.getCenterY() - (lw/2), lw, lw));
+ } else {
+ // Basic bounds
+ bounds = ElementUtils.getElementShape(te).getBounds2D();
+ Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(bounds, terminalElementTr);
+ bounds.setFrame(shp.getBounds2D());
+ }
+
+ x = bounds.getCenterX();
+ y = bounds.getCenterY();
+
+ // Expand bounds by 4mm to make the connections enter the terminals
+ // at a straight angle and from a distance instead of coming in
+ // "horizontally".
+ //GeometryUtils.expandRectangle(bounds, 4);
+
+ minx = bounds.getMinX();
+ miny = bounds.getMinY();
+ maxx = bounds.getMaxX();
+ maxy = bounds.getMaxY();
+
+ Integer allowedDirections = graph.getPossibleRelatedValue(terminal, DIA.Terminal_AllowedDirections, Bindings.INTEGER);
+
+ // Valve behaves differently. Allowed directions depend on the orientation of the valve
+ if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
+ if(graph.hasStatement(terminalElement, sr.ValveSymbol_orientation, sr.Vertical)) {
+ allowedDirections = 10; // Directions up and down (1010)
+ } else {
+ allowedDirections = 5; // Directions left and right (0101)
+ }
+ }
+ if (allowedDirections != null) {
+ direction |= allowedDirections;
+ } else {
+ direction |= RouteGraphConnectionClass.shortestDirectionOutOfBounds(x, y, bounds);
+ }
+
+ backendonnections.add(
+ new BackendConnection(
+ toEdgeEnd(graph, attachmentRelation, EdgeEnd.Begin),
+ terminalElement,
+ terminal)
+ );
+
+ if (direction == 0)
+ // Accept any horizontal/vertical direction if nothing is defined
+ direction = 0xf;
+
+ //System.out.println("load line style: " + NameUtils.getSafeLabel(graph, attachmentRelation));
+ ILineEndStyle endStyle = loadLineEndStyle(graph, te, attachmentRelation, color, lw);
+
+ RouteTerminal routeTerminal = rg.addBigTerminal(/*x, y,*/ minx, miny, maxx, maxy, /*direction,*/ endStyle);
+ routeTerminal.setData( RouteGraphConnection.serialize(graph, connector) );
+
+ nodes.add( connector );
+ nodeByData.put( connector, routeTerminal );
+
+ for (Resource connectedTo : graph.getObjects(connector, DIA.AreConnected)) {
+ links.add( new EdgeResource(connectedTo, connector) );
+ }
+ }
+
+ // Finish route graph loading by Linking route nodes together
+ for (EdgeResource link : links) {
+ RouteNode n1 = nodeByData.get(link.first());
+ RouteNode n2 = nodeByData.get(link.second());
+ if (n1 == null || n2 == null) {
+ System.err.println("Stray connection link found: " + link.toString(graph));
+ continue;
+ }
+ rg.link(n1, n2);
+ }
+
+ // Load connection line style
+ ConnectionStyle style = readConnectionStyle(graph, modelingRules, connection, element);
+ StyledRouteGraphRenderer renderer = new StyledRouteGraphRenderer(style);
+
+ // Finish element load
+ element.setHint(RouteGraphConnectionClass.KEY_ROUTEGRAPH, rg);
+ element.setHint(RouteGraphConnectionClass.KEY_RENDERER, renderer);
+ element.setHint(RouteGraphConnectionClass.KEY_PICK_TOLERANCE, 0.5);
+
+ // Initialize ConnectionEntity in element
+ // NOTE: MUST use the mapped element with class CE, not the connection (element) were loading into.
+ // GDS will synchronize element into mappedElement in a controlled manner.
+ element.setHint(ElementHints.KEY_CONNECTION_ENTITY, new CE(diagram, connection, element, backendonnections));
+
+ // Setup graph writeback support for route graph modifications
+ final Session session = graph.getSession();
+ element.setHint(RouteGraphConnectionClass.KEY_RG_LISTENER, new IRouteGraphListener() {
+ @Override
+ public void routeGraphChanged(RouteGraphChangeEvent event) {
+ scheduleSynchronize(session, connection, event);
+ }
+ });
+
+ final Map<String, Pair<Resource, Object>> properties = new HashMap<>();
+ for (Resource predicate : graph.getPredicates(connection)) {
+ if (graph.isSubrelationOf(predicate, L0.HasProperty)) {
+ String name = graph.getPossibleRelatedValue(predicate, L0.HasName, Bindings.STRING);
+ Object value = graph.getPossibleRelatedValue(connection, predicate);
+ if (name != null && value != null) {
+ properties.put(name, Pair.make(predicate, value));
+ }
+ }
+ }
+ element.setHint(DiagramHints.PROPERTIES, properties);
+ }
+
+ private EdgeEnd toEdgeEnd(ReadGraph graph, Resource attachmentRelation, EdgeEnd defaultValue)
+ throws DatabaseException {
+ if (graph.isSubrelationOf(attachmentRelation, DIA.IsTailConnectorOf))
+ return EdgeEnd.Begin;
+ if (graph.isSubrelationOf(attachmentRelation, DIA.IsHeadConnectorOf))
+ return EdgeEnd.End;
+ return defaultValue;
+ }
+
+ private ConnectionStyle readConnectionStyle(ReadGraph graph, IModelingRules modelingRules, Resource connection,
+ IElement element) throws DatabaseException {
+ Resource connectionType = null;
+ if (modelingRules != null)
+ connectionType = modelingRules.getConnectionType(graph, connection);
+ if (connectionType == null)
+ connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
+
+ ConnectionVisuals cv = null;
+ if (connectionType != null)
+ cv = graph.syncRequest(DiagramRequests.getConnectionVisuals(connectionType),
+ TransientCacheListener.<ConnectionVisuals> instance());
+
+
+ Color lineColor = element.getHint(ElementHints.KEY_TEXT_COLOR);
+ if (lineColor == null)
+ lineColor = (cv != null && cv.toColor() != null) ? cv.toColor() : Color.DARK_GRAY;
+
+ Stroke lineStroke = cv != null ? cv.stroke : null;
+ if (lineStroke == null)
+ lineStroke = new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, null, 0);
+
+ return new FlowConnectionStyle(
+ lineColor,
+ lineStroke,
+ connection);
+ }
+
+ /**
+ * @param graph
+ * @param STR
+ * @param connection
+ * @param connector
+ * @return connection relation statement from diagram connection connector
+ * to a node
+ * @throws DatabaseException
+ */
+ private static Statement findTerminalStatement(ReadGraph graph, StructuralResource2 STR, Resource connection,
+ Resource connector) throws DatabaseException {
+ for (Statement stm : graph.getStatements(connector, STR.Connects)) {
+ if (connection.equals(stm.getObject()))
+ continue;
+ return stm;
+ }
+ return null;
+ }
+
+ public ILineEndStyle loadLineEndStyle(ReadGraph graph, IElement te, Resource attachmentRelation, Color color, float lineWidth)
+ throws DatabaseException {
+ ILineEndStyle style;
+ // TODO: change bounds according to terminal type: Very small rectangle for Valves, Text box size for Stocks and Clouds
+ if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
+ style = new FlowArrowLineStyle("none 0 0 0", color);
+ } else {
+ if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector)) {
+ float arrowSize = lineWidth * 1.3f;
+ style = new FlowArrowLineStyle("fill " + arrowSize + " " + arrowSize + " 0", color);
+ } else {
+ style = new FlowArrowLineStyle("none 0 0 0", color);
+ }
+ }
+ return style;
+ }
+
+ /**
+ * @param graph
+ * @param element
+ * @return
+ * @throws DatabaseException
+ */
+ private static AffineTransform getWorldTransform(ReadGraph graph, Resource element) throws DatabaseException {
+ ModelingResources MOD = ModelingResources.getInstance(graph);
+ AffineTransform result = DiagramGraphUtil.getAffineTransform(graph, element);
+ while (true) {
+ Resource parentComponent = graph.getPossibleObject(element, MOD.HasParentComponent);
+ if (parentComponent == null)
+ return result;
+ element = graph.getPossibleObject(parentComponent, MOD.ComponentToElement);
+ if (element == null)
+ return result;
+ AffineTransform tr = DiagramGraphUtil.getAffineTransform(graph, element);
+ tr.setToTranslation(tr.getTranslateX(), tr.getTranslateY());
+ result.preConcatenate(tr);
+ }
+ }
+
+
+ protected void scheduleSynchronize(Session session, Resource connection, RouteGraphChangeEvent event) {
+ session.asyncRequest(RouteGraphConnection.synchronizer(connection, event));
+ }
+
+ /**
+ * Must have this in order for {@link TopologicalSelectionExpander} to work.
+ * Otherwise this is pretty useless and should be deprecated altogether.
+ *
+ * @see ElementHints#KEY_CONNECTION_ENTITY
+ */
+ static class CE implements ConnectionEntity {
+
+
+ private IDiagram diagram;
+
+ private transient DataElementMap dataMap;
+
+ /**
+ * The connection instance resource in the graph backend.
+ */
+ final Resource connection;
+
+ /**
+ * The connection entity element which is a part of the diagram.
+ */
+ IElement connectionElement;
+
+ /**
+ * @see #getTerminalConnections(Collection)
+ */
+ final Set<BackendConnection> backendConnections;
+
+ /**
+ * Cache.
+ */
+ Set<Connection> terminalConnections;
+
+
+ public CE(IDiagram diagram, Resource connection, IElement connectionElement, Set<BackendConnection> backendConnections) {
+ if (connectionElement == null)
+ throw new NullPointerException("null connection element");
+ this.diagram = diagram;
+ this.dataMap = diagram.getDiagramClass().getSingleItem(DataElementMap.class);
+ this.connection = connection;
+ this.connectionElement = connectionElement;
+ this.backendConnections = backendConnections;
+ IElement ce = getConnection0();
+ if (ce != null)
+ this.connectionElement = ce;
+ }
+
+ public IElement getConnection0() {
+ IElement connectionElement = dataMap.getElement(diagram, connection);
+ return connectionElement;
+ }
+
+ @Override
+ public IElement getConnection() {
+ IElement c = getConnection0();
+ if (c == null)
+ c = this.connectionElement;
+ return c;
+ }
+
+ public Object getConnectionObject() {
+ return connection;
+ }
+
+ public IElement getConnectionElement() {
+ return connectionElement;
+ }
+
+ @Override
+ public Collection<IElement> getBranchPoints(Collection<IElement> result) {
+ return result != null ? result : Collections.<IElement> emptyList();
+ }
+
+ @Override
+ public Collection<IElement> getSegments(Collection<IElement> result) {
+ return result != null ? result : Collections.<IElement> emptyList();
+ }
+
+ @Override
+ public Collection<Connection> getTerminalConnections(Collection<Connection> result) {
+ if (terminalConnections == null)
+ terminalConnections = calculateTerminalConnections();
+ if (result == null)
+ result = new ArrayList<Connection>(terminalConnections);
+ else
+ result.addAll(terminalConnections);
+ return terminalConnections;
+ }
+
+ private Set<Connection> calculateTerminalConnections() {
+ DataElementMap dem = diagram.getDiagramClass().getSingleItem(DataElementMap.class);
+ Set<Connection> result = new HashSet<Connection>();
+ ArrayList<Terminal> ts = new ArrayList<Terminal>();
+ for (BackendConnection bc : backendConnections) {
+ IElement e = dem.getElement(diagram, bc.node);
+ if (e == null)
+ continue;
+ TerminalTopology tt = e.getElementClass().getSingleItem(TerminalTopology.class);
+ tt.getTerminals(e, ts);
+ for (Terminal t : ts) {
+ if (t instanceof ResourceTerminal) {
+ ResourceTerminal rt = (ResourceTerminal) t;
+ if (bc.terminal.equals(rt.getResource())) {
+ result.add(new Connection(connectionElement, bc.end, e, t));
+ break;
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public void setListener(ConnectionListener listener) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "[resource=" + connection + ", connectionElement=" + connectionElement
+ + "]";
+ }
+
+ }
+
+ public static class BackendConnection {
+ public final Resource node;
+ public final Resource terminal;
+ public final EdgeEnd end;
+ public BackendConnection(EdgeEnd end, Resource node, Resource terminal) {
+ assert end != null;
+ assert node != null;
+ assert terminal != null;
+ this.end = end;
+ this.node = node;
+ this.terminal = terminal;
+ }
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (!(obj instanceof Connection))
+ return false;
+ Connection other = (Connection) obj;
+ return other.terminal == terminal
+ && other.node == node
+ && other.end == end;
+ }
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + end.hashCode();
+ result = prime * result + ((node == null) ? 0 : node.hashCode());
+ result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());
+ return result;
+ }
+ @Override
+ public String toString() {
+ return "BackendConnection[node=" + node + ", terminal=" + terminal + ", end=" + end + "]";
+ }
+ }
+
+}
+
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.elements.profiles;\r
-\r
-import java.awt.geom.AffineTransform;\r
-import java.awt.geom.Rectangle2D;\r
-import java.util.ArrayList;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.diagram.G2DUtils;\r
-import org.simantics.diagram.elements.TextNode;\r
-import org.simantics.diagram.profile.StyleBase;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.project.IProject;\r
-import org.simantics.scenegraph.INode;\r
-import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
-import org.simantics.scenegraph.g2d.nodes.SingleElementNode;\r
-import org.simantics.scenegraph.profile.EvaluationContext;\r
-import org.simantics.scenegraph.profile.Observer;\r
-import org.simantics.scenegraph.profile.common.ProfileVariables;\r
-import org.simantics.scenegraph.utils.GeometryUtils;\r
-import org.simantics.scenegraph.utils.NodeUtil;\r
-import org.simantics.scl.runtime.tuple.Tuple2;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.Functions;\r
-import org.simantics.sysdyn.adapter.VariableRVIUtils;\r
-import org.simantics.sysdyn.manager.SysdynDataSet;\r
-import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Triple;\r
-import org.simantics.utils.ui.color.Color;\r
-import org.simantics.utils.ui.color.ColorGradient;\r
-import org.simantics.utils.ui.color.ColorValue;\r
-\r
-/**\r
- * Profile style definition for simulation playback mode. Works only with SimulationPlaybackExperiment\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class SimulationPlaybackStyle extends StyleBase<Triple<AffineTransform, Double, ColorGradient>> {\r
-\r
- Resource gradientResource;\r
- ColorGradient cg;\r
- byte[] gradient;\r
-\r
- /**\r
- * Determine if style needs to be redrawn and return objects that are needed to redraw the style.\r
- * \r
- * @return All necessary components that are needed to draw this style\r
- */\r
- @Override\r
- public Triple<AffineTransform, Double, ColorGradient> calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException {\r
-\r
- // Find SimulationPlaybackExperiment\r
- IProject project = SimanticsUI.getProject();\r
- IExperimentManager em = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = em.getActiveExperiment();\r
- if(!(experiment instanceof SysdynPlaybackExperiment))\r
- return null;\r
-\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- DiagramResource dr = DiagramResource.getInstance(graph);\r
-\r
- ColorGradient cg = null;\r
-\r
- Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
- if (component == null)\r
- return null;\r
-\r
- try {\r
-\r
- // Find Variable for this component\r
- String dv = graph.getPossibleRelatedValue(runtimeDiagram, dr.RuntimeDiagram_HasVariable);\r
- Variable rootVariable = graph.getPossibleAdapter(graph.getRootLibrary(), Variable.class);\r
- if (rootVariable == null) \r
- return null;\r
- Variable diagramVariable = rootVariable.browsePossible(graph, dv.substring(6));\r
- if(diagramVariable == null) \r
- return null;\r
-\r
- Variable var = diagramVariable.browsePossible(graph, component);\r
- if(var == null)\r
- return null;\r
-\r
- // Get simulation result values for this component\r
- // Get values\r
- Variable dsVariable = var.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
- Object object = null;\r
- if(dsVariable != null)\r
- object = dsVariable.getValue(graph);\r
- if(object == null || !(object instanceof ArrayList<?>))\r
- return null;\r
-\r
- ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
-\r
- for(Object o : (ArrayList<?>)object) {\r
- if(o instanceof SysdynDataSet)\r
- datasets.add((SysdynDataSet)o);\r
- }\r
-\r
- if(datasets.size() == 0)\r
- return null;\r
-\r
- if(datasets.size() > 1) {\r
- String range = datasets.get(0).name.substring(\r
- datasets.get(0).name.indexOf('[') + 1,\r
- datasets.get(0).name.indexOf(']'));\r
- int size = range.split(",").length;\r
- String[] filter = new String[size];\r
- for(int i = 0; i < size; i++)\r
- filter[i] = "Sum";\r
-\r
- ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);\r
- if(result2 != null) {\r
- datasets = result2;\r
- }\r
-\r
- }\r
-\r
- // The datasets list should always be size == 1\r
- SysdynDataSet dataset = datasets.get(0);\r
- \r
- // Get values (or sum of values)\r
- double[] va = dataset.values;\r
- if(va.length < 2)\r
- return null;\r
-\r
- // Get simulation timesteps for this component\r
- double[] ta = dataset.times;\r
- if(ta == null || ta.length < 2)\r
- return null;\r
-\r
- if(va.length == 0 || va.length == 2)\r
- return null;\r
-\r
- // Get playback time from the experiment run\r
- Double time = null;\r
- if(diagramVariable != null) {\r
- Variable timeVar = diagramVariable.browsePossible(graph, "#" + Functions.TIME + "#");\r
- if(timeVar != null)\r
- time = timeVar.getValue(graph, Bindings.DOUBLE);\r
- }\r
-\r
- if(time == null)\r
- return null;\r
-\r
- // Find minimum and maximum values for this variable\r
- double min = va[0], max = va[0];\r
- for(double d : va) {\r
- if(d < min) \r
- min = d;\r
- if(d > max)\r
- max = d;\r
- }\r
-\r
- // Find the index in time and value arrays for this time \r
- // (time steps may vary, we need to loop to find the correct time) \r
- int index = 0;\r
- if(ta[ta.length - 1] - time > ta[ta.length / 2] ) {\r
- index = ta.length - 1;\r
- while(ta[index] > time && index > 0)\r
- index--;\r
- } else {\r
- while(ta[index] < time && index < ta.length - 1)\r
- index++;\r
- }\r
-\r
- double value = va[index];\r
-\r
- // Calculate where the value is located between min and max values [0..1]. \r
- double multiplier = (value - min) / (max - min);\r
-\r
-\r
- // Get the transform of this element\r
- AffineTransform at = (AffineTransform) DiagramGraphUtil.getAffineTransform(graph, element, G2DResource.getInstance(graph).HasTransform, true).clone();\r
-\r
- // Find the gradient used to draw this style\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- Resource gradient = graph.getPossibleObject(experiment.getResource(), g2d.HasColorGradient);\r
- if(this.gradientResource == null || !this.gradientResource.equals(gradient)) {\r
- ArrayList<ColorValue> colorValues = new ArrayList<ColorValue>();\r
- for(Resource placement : graph.syncRequest(new ObjectsWithType(gradient, g2d.HasColorPlacement, g2d.ColorPlacement))) {\r
- Double position = graph.getPossibleRelatedValue(placement, g2d.HasGradientPosition, Bindings.DOUBLE);\r
- Resource rColor = graph.getPossibleObject(placement, g2d.HasColor);\r
- if (rColor != null) {\r
- colorValues.add(new ColorValue(new Color((java.awt.Color) G2DUtils.getObject(graph, rColor)), position));\r
- }\r
- }\r
- cg = new ColorGradient(colorValues, ColorGradient.HSV);\r
- } else {\r
- cg = this.cg;\r
- }\r
-\r
- return new Triple<AffineTransform, Double, ColorGradient>(at, multiplier, cg);\r
-\r
- } catch(Exception ignore) {\r
- ignore.printStackTrace();\r
- }\r
- return null;\r
- }\r
-\r
- @Override\r
- public void styleResultChanged(Observer observer, Resource runtimeDiagram, Resource element, Triple<AffineTransform, Double, ColorGradient> result) {\r
- if (result != null)\r
- values.put(new Tuple2(runtimeDiagram, element), result);\r
- else\r
- values.remove(new Tuple2(runtimeDiagram, element));\r
- observer.update();\r
- }\r
-\r
- /**\r
- * Apply style\r
- */\r
- @Override\r
- public void applyStyleForNode(EvaluationContext observer, INode _node, Triple<AffineTransform, Double, ColorGradient> result) {\r
- Double multiplier;\r
- if (result != null && (multiplier = result.second) != null && !multiplier.isNaN()) {\r
-\r
- // Create a node that will show the style effect\r
- A node = ProfileVariables.claimChild(_node, "", "playbackColour", A.class, observer);\r
- if (node == null)\r
- return;\r
-\r
- AffineTransform at = result.first;\r
-\r
- if(this.cg == null || !this.cg.equals(result.third)) {\r
- this.cg = result.third;\r
- this.gradient = cg.getGradientArray(101);\r
- }\r
-\r
- // Get integer values for red, green and blue\r
- int i = (int)(multiplier * 100);\r
- int r = (int)(gradient[i * 3 + 0] & 0xff);\r
- int g = (int)(gradient[i * 3 + 1] & 0xff);\r
- int b = (int)(gradient[i * 3 + 2] & 0xff);\r
- // Get color with r, g and b\r
- java.awt.Color c = new java.awt.Color(r, g, b, 200);\r
-\r
- // Create a node for the style\r
- INode n = NodeUtil.getNearestChildByClass((SingleElementNode)_node, TextNode.class);\r
- Rectangle2D expandedElementBounds = GeometryUtils.expandRectangle( NodeUtil.getLocalElementBounds(n), 0.0);\r
- node.setFill(true);\r
- node.setColor(c);\r
- node.setStroke(null);\r
- node.setValue("shape", expandedElementBounds);\r
- node.setTransform(at);\r
-\r
- // Find z-index for the TextNode associated with the element and place the style node just below that text node \r
- int zIndex = -1;\r
- if(n != null) {\r
- at = ((TextNode)n).getTransform();\r
- zIndex = ((TextNode)n).getZIndex() - 1;\r
- } else {\r
- n = _node;\r
- }\r
- node.setZIndex(zIndex);\r
-\r
-\r
- } else {\r
- cleanupStyleForNode(_node);\r
- }\r
- }\r
-\r
- @Override\r
- protected void cleanupStyleForNode(INode node) {\r
- ProfileVariables.denyChild(node, "", "playbackColour");\r
- }\r
-\r
-\r
- /**\r
- * Dummy class for displaying the style\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
- public static class A extends ShapeNode {\r
-\r
- private static final long serialVersionUID = -5273246617906214956L;\r
-\r
- @Override\r
- public Rectangle2D getBoundsInLocal() {\r
- return null;\r
- }\r
-\r
- @Override\r
- public Rectangle2D getBoundsInLocal(boolean b) {\r
- return null;\r
- }\r
-\r
- @Override\r
- public Rectangle2D getBounds() {\r
- return null;\r
- }\r
-\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.elements.profiles;
+
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+import java.util.ArrayList;
+
+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.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.diagram.G2DUtils;
+import org.simantics.diagram.elements.TextNode;
+import org.simantics.diagram.profile.StyleBase;
+import org.simantics.diagram.stubs.DiagramResource;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.project.IProject;
+import org.simantics.scenegraph.INode;
+import org.simantics.scenegraph.g2d.nodes.ShapeNode;
+import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
+import org.simantics.scenegraph.profile.EvaluationContext;
+import org.simantics.scenegraph.profile.Observer;
+import org.simantics.scenegraph.profile.common.ProfileVariables;
+import org.simantics.scenegraph.utils.GeometryUtils;
+import org.simantics.scenegraph.utils.NodeUtil;
+import org.simantics.scl.runtime.tuple.Tuple2;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.Functions;
+import org.simantics.sysdyn.adapter.VariableRVIUtils;
+import org.simantics.sysdyn.manager.SysdynDataSet;
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;
+import org.simantics.utils.datastructures.Triple;
+import org.simantics.utils.ui.color.Color;
+import org.simantics.utils.ui.color.ColorGradient;
+import org.simantics.utils.ui.color.ColorValue;
+
+/**
+ * Profile style definition for simulation playback mode. Works only with SimulationPlaybackExperiment
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class SimulationPlaybackStyle extends StyleBase<Triple<AffineTransform, Double, ColorGradient>> {
+
+ Resource gradientResource;
+ ColorGradient cg;
+ byte[] gradient;
+
+ /**
+ * Determine if style needs to be redrawn and return objects that are needed to redraw the style.
+ *
+ * @return All necessary components that are needed to draw this style
+ */
+ @Override
+ public Triple<AffineTransform, Double, ColorGradient> calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException {
+
+ // Find SimulationPlaybackExperiment
+ IProject project = Simantics.getProject();
+ IExperimentManager em = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = em.getActiveExperiment();
+ if(!(experiment instanceof SysdynPlaybackExperiment))
+ return null;
+
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ DiagramResource dr = DiagramResource.getInstance(graph);
+
+ ColorGradient cg = null;
+
+ Resource component = graph.getPossibleObject(element, mr.ElementToComponent);
+ if (component == null)
+ return null;
+
+ try {
+
+ // Find Variable for this component
+ String dv = graph.getPossibleRelatedValue(runtimeDiagram, dr.RuntimeDiagram_HasVariable);
+ Variable rootVariable = graph.getPossibleAdapter(graph.getRootLibrary(), Variable.class);
+ if (rootVariable == null)
+ return null;
+ Variable diagramVariable = rootVariable.browsePossible(graph, dv.substring(6));
+ if(diagramVariable == null)
+ return null;
+
+ Variable var = diagramVariable.browsePossible(graph, component);
+ if(var == null)
+ return null;
+
+ // Get simulation result values for this component
+ // Get values
+ Variable dsVariable = var.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");
+ Object object = null;
+ if(dsVariable != null)
+ object = dsVariable.getValue(graph);
+ if(object == null || !(object instanceof ArrayList<?>))
+ return null;
+
+ ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();
+
+ for(Object o : (ArrayList<?>)object) {
+ if(o instanceof SysdynDataSet)
+ datasets.add((SysdynDataSet)o);
+ }
+
+ if(datasets.size() == 0)
+ return null;
+
+ if(datasets.size() > 1) {
+ String range = datasets.get(0).name.substring(
+ datasets.get(0).name.indexOf('[') + 1,
+ datasets.get(0).name.indexOf(']'));
+ int size = range.split(",").length;
+ String[] filter = new String[size];
+ for(int i = 0; i < size; i++)
+ filter[i] = "Sum";
+
+ ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);
+ if(result2 != null) {
+ datasets = result2;
+ }
+
+ }
+
+ // The datasets list should always be size == 1
+ SysdynDataSet dataset = datasets.get(0);
+
+ // Get values (or sum of values)
+ double[] va = dataset.values;
+ if(va.length < 2)
+ return null;
+
+ // Get simulation timesteps for this component
+ double[] ta = dataset.times;
+ if(ta == null || ta.length < 2)
+ return null;
+
+ if(va.length == 0 || va.length == 2)
+ return null;
+
+ // Get playback time from the experiment run
+ Double time = null;
+ if(diagramVariable != null) {
+ Variable timeVar = diagramVariable.browsePossible(graph, "#" + Functions.TIME + "#");
+ if(timeVar != null)
+ time = timeVar.getValue(graph, Bindings.DOUBLE);
+ }
+
+ if(time == null)
+ return null;
+
+ // Find minimum and maximum values for this variable
+ double min = va[0], max = va[0];
+ for(double d : va) {
+ if(d < min)
+ min = d;
+ if(d > max)
+ max = d;
+ }
+
+ // Find the index in time and value arrays for this time
+ // (time steps may vary, we need to loop to find the correct time)
+ int index = 0;
+ if(ta[ta.length - 1] - time > ta[ta.length / 2] ) {
+ index = ta.length - 1;
+ while(ta[index] > time && index > 0)
+ index--;
+ } else {
+ while(ta[index] < time && index < ta.length - 1)
+ index++;
+ }
+
+ double value = va[index];
+
+ // Calculate where the value is located between min and max values [0..1].
+ double multiplier = (value - min) / (max - min);
+
+
+ // Get the transform of this element
+ AffineTransform at = (AffineTransform) DiagramGraphUtil.getAffineTransform(graph, element, G2DResource.getInstance(graph).HasTransform, true).clone();
+
+ // Find the gradient used to draw this style
+ G2DResource g2d = G2DResource.getInstance(graph);
+ Resource gradient = graph.getPossibleObject(experiment.getResource(), g2d.HasColorGradient);
+ if(this.gradientResource == null || !this.gradientResource.equals(gradient)) {
+ ArrayList<ColorValue> colorValues = new ArrayList<ColorValue>();
+ for(Resource placement : graph.syncRequest(new ObjectsWithType(gradient, g2d.HasColorPlacement, g2d.ColorPlacement))) {
+ Double position = graph.getPossibleRelatedValue(placement, g2d.HasGradientPosition, Bindings.DOUBLE);
+ Resource rColor = graph.getPossibleObject(placement, g2d.HasColor);
+ if (rColor != null) {
+ colorValues.add(new ColorValue(new Color((java.awt.Color) G2DUtils.getObject(graph, rColor)), position));
+ }
+ }
+ cg = new ColorGradient(colorValues, ColorGradient.HSV);
+ } else {
+ cg = this.cg;
+ }
+
+ return new Triple<AffineTransform, Double, ColorGradient>(at, multiplier, cg);
+
+ } catch(Exception ignore) {
+ ignore.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ public void styleResultChanged(Observer observer, Resource runtimeDiagram, Resource element, Triple<AffineTransform, Double, ColorGradient> result) {
+ if (result != null)
+ values.put(new Tuple2(runtimeDiagram, element), result);
+ else
+ values.remove(new Tuple2(runtimeDiagram, element));
+ observer.update();
+ }
+
+ /**
+ * Apply style
+ */
+ @Override
+ public void applyStyleForNode(EvaluationContext observer, INode _node, Triple<AffineTransform, Double, ColorGradient> result) {
+ Double multiplier;
+ if (result != null && (multiplier = result.second) != null && !multiplier.isNaN()) {
+
+ // Create a node that will show the style effect
+ A node = ProfileVariables.claimChild(_node, "", "playbackColour", A.class, observer);
+ if (node == null)
+ return;
+
+ AffineTransform at = result.first;
+
+ if(this.cg == null || !this.cg.equals(result.third)) {
+ this.cg = result.third;
+ this.gradient = cg.getGradientArray(101);
+ }
+
+ // Get integer values for red, green and blue
+ int i = (int)(multiplier * 100);
+ int r = (int)(gradient[i * 3 + 0] & 0xff);
+ int g = (int)(gradient[i * 3 + 1] & 0xff);
+ int b = (int)(gradient[i * 3 + 2] & 0xff);
+ // Get color with r, g and b
+ java.awt.Color c = new java.awt.Color(r, g, b, 200);
+
+ // Create a node for the style
+ INode n = NodeUtil.getNearestChildByClass((SingleElementNode)_node, TextNode.class);
+ Rectangle2D expandedElementBounds = GeometryUtils.expandRectangle( NodeUtil.getLocalElementBounds(n), 0.0);
+ node.setFill(true);
+ node.setColor(c);
+ node.setStroke(null);
+ node.setValue("shape", expandedElementBounds);
+ node.setTransform(at);
+
+ // Find z-index for the TextNode associated with the element and place the style node just below that text node
+ int zIndex = -1;
+ if(n != null) {
+ at = ((TextNode)n).getTransform();
+ zIndex = ((TextNode)n).getZIndex() - 1;
+ } else {
+ n = _node;
+ }
+ node.setZIndex(zIndex);
+
+
+ } else {
+ cleanupStyleForNode(_node);
+ }
+ }
+
+ @Override
+ protected void cleanupStyleForNode(INode node) {
+ ProfileVariables.denyChild(node, "", "playbackColour");
+ }
+
+
+ /**
+ * Dummy class for displaying the style
+ *
+ * @author Teemu Lempinen
+ *
+ */
+ public static class A extends ShapeNode {
+
+ private static final long serialVersionUID = -5273246617906214956L;
+
+ @Override
+ public Rectangle2D getBoundsInLocal() {
+ return null;
+ }
+
+ @Override
+ public Rectangle2D getBoundsInLocal(boolean b) {
+ return null;
+ }
+
+ @Override
+ public Rectangle2D getBounds() {
+ return null;
+ }
+
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.dialogs.IDialogSettings;\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.window.Window;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.Simantics;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.ResourceRead;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.request.PossibleModel;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ui.Activator;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.ui.workbench.dialogs.ResourceSelectionDialog3;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-public class AssignIC extends AbstractHandler {\r
-\r
- private Resource query(Resource experiment) throws DatabaseException {\r
-\r
- Map<Resource, Pair<String, ImageDescriptor>> map = Simantics.getSession().syncRequest(new ResourceRead<Map<Resource, Pair<String, ImageDescriptor>>>(experiment) {\r
-\r
- @Override\r
- public Map<Resource, Pair<String, ImageDescriptor>> perform(ReadGraph graph) throws DatabaseException {\r
- Map<Resource, Pair<String, ImageDescriptor>> result = new HashMap<Resource, Pair<String, ImageDescriptor>>();\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
- Resource model = graph.syncRequest(new PossibleModel(resource));\r
- for(Resource r : graph.syncRequest(new ObjectsWithType(model, L0.ConsistsOf, SYSDYN.InitialCondition))) {\r
- String name = NameUtils.getSafeName(graph, r);\r
- result.put(r, new Pair<String, ImageDescriptor>(name, null));\r
- }\r
- return result;\r
- }\r
- \r
- });\r
- \r
- Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();\r
- ResourceSelectionDialog3<Resource> dialog = new ResourceSelectionDialog3<Resource>(shell, map, "Select connection point type") {\r
- @Override\r
- protected IDialogSettings getBaseDialogSettings() {\r
- return Activator.getDefault().getDialogSettings();\r
- }\r
- };\r
- if (dialog.open() == Window.OK) {\r
- Object[] result = dialog.getResult();\r
- if (result != null && result.length == 1) {\r
- final Resource res = (Resource)result[0];\r
- return res;\r
- }\r
- }\r
- \r
- return null;\r
-\r
- }\r
- \r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- ISelection selection = HandlerUtil.getCurrentSelection(event);\r
- final Resource experiment = ResourceAdaptionUtils.toSingleResource(selection);\r
- if (experiment == null)\r
- return null;\r
-\r
- try {\r
-\r
- final Resource ic = query(experiment);\r
- if(ic == null)\r
- return null;\r
-\r
- Simantics.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- graph.markUndoPoint();\r
- SysdynResource SYSDYN = SysdynResource.getInstance(graph);\r
-\r
- graph.deny(experiment, SYSDYN.Experiment_ic);\r
- graph.claim(experiment, SYSDYN.Experiment_ic, ic);\r
- Layer0Utils.addCommentMetadata(graph, "Assigned new IC " + NameUtils.getSafeName(graph, ic) + " to experiment " + NameUtils.getSafeLabel(graph, experiment));\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return null;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.dialogs.IDialogSettings;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.window.Window;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+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.ObjectsWithType;
+import org.simantics.db.common.request.ResourceRead;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.request.PossibleModel;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ui.Activator;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.ui.workbench.dialogs.ResourceSelectionDialog3;
+import org.simantics.utils.datastructures.Pair;
+
+public class AssignIC extends AbstractHandler {
+
+ public static Object handleStatic(Resource experiment) throws ExecutionException {
+ return executeImpl(experiment);
+ }
+
+ private static Resource query(Resource experiment) throws DatabaseException {
+
+ Map<Resource, Pair<String, ImageDescriptor>> map = Simantics.getSession().syncRequest(new ResourceRead<Map<Resource, Pair<String, ImageDescriptor>>>(experiment) {
+
+ @Override
+ public Map<Resource, Pair<String, ImageDescriptor>> perform(ReadGraph graph) throws DatabaseException {
+ Map<Resource, Pair<String, ImageDescriptor>> result = new HashMap<Resource, Pair<String, ImageDescriptor>>();
+ Layer0 L0 = Layer0.getInstance(graph);
+ SysdynResource SYSDYN = SysdynResource.getInstance(graph);
+ Resource model = graph.syncRequest(new PossibleModel(resource));
+ for(Resource r : graph.syncRequest(new ObjectsWithType(model, L0.ConsistsOf, SYSDYN.InitialCondition))) {
+ String name = NameUtils.getSafeName(graph, r);
+ result.put(r, new Pair<String, ImageDescriptor>(name, null));
+ }
+ return result;
+ }
+
+ });
+
+ Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
+ ResourceSelectionDialog3<Resource> dialog = new ResourceSelectionDialog3<Resource>(shell, map, "Select connection point type") {
+ @Override
+ protected IDialogSettings getBaseDialogSettings() {
+ return Activator.getDefault().getDialogSettings();
+ }
+ };
+ if (dialog.open() == Window.OK) {
+ Object[] result = dialog.getResult();
+ if (result != null && result.length == 1) {
+ final Resource res = (Resource)result[0];
+ return res;
+ }
+ }
+
+ return null;
+
+ }
+
+
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection selection = HandlerUtil.getCurrentSelection(event);
+ final Resource experiment = ResourceAdaptionUtils.toSingleResource(selection);
+ if (experiment == null)
+ return null;
+ return(executeImpl(experiment));
+ }
+
+ private static Object executeImpl(Resource experiment) throws ExecutionException {
+ try {
+
+ final Resource ic = query(experiment);
+ if(ic == null)
+ return null;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ graph.markUndoPoint();
+ SysdynResource SYSDYN = SysdynResource.getInstance(graph);
+
+ graph.deny(experiment, SYSDYN.Experiment_ic);
+ graph.claim(experiment, SYSDYN.Experiment_ic, ic);
+ Layer0Utils.addCommentMetadata(graph, "Assigned new IC " + NameUtils.getSafeName(graph, ic) + " to experiment " + NameUtils.getSafeLabel(graph, experiment));
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class DisposeExperiment extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- HandlerUtils.saveBeforeExperimentRun(event);\r
- \r
- IProject project = SimanticsUI.getProject();\r
- IExperimentManager manager = \r
- project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if (experiment != null)\r
- experiment.shutdown(null);\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.Simantics;
+import org.simantics.project.IProject;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+public class DisposeExperiment extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ IProject project = Simantics.getProject();
+ IExperimentManager manager =
+ project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if (experiment != null)
+ experiment.shutdown(null);
+ return null;
+ }
+
+}
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.annotation.ui.AnnotationUtils;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class NewAnnotationTypeHandler extends AbstractHandler {\r
-\r
- /**\r
- * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource\r
- */\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
- if(res == null) {\r
- @SuppressWarnings("unchecked")\r
- AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
- if (node == null)\r
- return null;\r
- res = node.data;\r
- }\r
-\r
- final Resource parent = res;\r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- AnnotationUtils.newAnnotationType(graph, parent);\r
- }\r
- \r
- });\r
- \r
- return null;\r
- \r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.annotation.ui.AnnotationUtils;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class NewAnnotationTypeHandler extends AbstractHandler {
+
+ /**
+ * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);
+ if(res == null) {
+ @SuppressWarnings("unchecked")
+ AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);
+ if (node == null)
+ return null;
+ res = node.data;
+ }
+
+ final Resource parent = res;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ AnnotationUtils.newAnnotationType(graph, parent);
+ }
+
+ });
+
+ return null;
+
+ }
+
+}
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.modeling.ui.actions.NewLibrary;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class NewLibraryHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
- if(res == null) {\r
- @SuppressWarnings("unchecked")\r
- AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
- if (node == null)\r
- return null;\r
- res = node.data;\r
- }\r
-\r
- final Resource parent = res;\r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- NewLibrary.createLibrary(graph, parent);\r
- }\r
- \r
- });\r
- \r
- return null;\r
- \r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.modeling.ui.actions.NewLibrary;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class NewLibraryHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);
+ if(res == null) {
+ @SuppressWarnings("unchecked")
+ AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);
+ if (node == null)
+ return null;
+ res = node.data;
+ }
+
+ final Resource parent = res;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ NewLibrary.createLibrary(graph, parent);
+ }
+
+ });
+
+ return null;
+
+ }
+
+}
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.modeling.ModelingUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class NewSCLModuleHandler extends AbstractHandler {\r
-\r
- /**\r
- * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource\r
- */\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
- if(res == null) {\r
- @SuppressWarnings("unchecked")\r
- AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
- if (node == null)\r
- return null;\r
- res = node.data;\r
- }\r
-\r
- final Resource parent = res;\r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- ModelingUtils.createSCLModuleDefault(graph, parent);\r
- }\r
- \r
- });\r
- \r
- return null;\r
- \r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.modeling.ModelingUtils;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class NewSCLModuleHandler extends AbstractHandler {
+
+ /**
+ * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ Resource res = AdaptionUtils.adaptToSingle(sel, Resource.class);
+ if(res == null) {
+ @SuppressWarnings("unchecked")
+ AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);
+ if (node == null)
+ return null;
+ res = node.data;
+ }
+
+ final Resource parent = res;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ ModelingUtils.createSCLModuleDefault(graph, parent);
+ }
+
+ });
+
+ return null;
+
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.dialogs.MessageDialog;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.CancelTransactionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-/**\r
- * @author Tuukka Lehtonen\r
- */\r
-public class RemoveNodeHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
- if (resources.length == 0)\r
- return null;\r
-\r
- MessageDialog dialog = new MessageDialog(shell, "Remove Item", null, "Are you sure?", 0,\r
- new String[] { "OK", "Cancel" }, 0);\r
- dialog.create();\r
- if (dialog.open() == 0)\r
- deleteItem(resources);\r
-\r
- return null;\r
- }\r
-\r
- public static void deleteItem(final Resource[] resources) {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {\r
- for (Resource r : resources)\r
- RemoverUtil.remove(graph, r);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ExceptionUtils.logAndShowError(e);\r
- }\r
- }\r
-\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.CancelTransactionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.ExceptionUtils;
+
+/**
+ * @author Tuukka Lehtonen
+ */
+public class RemoveNodeHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ Resource[] resources = ResourceAdaptionUtils.toResources(sel);
+ if (resources.length == 0)
+ return null;
+
+ MessageDialog dialog = new MessageDialog(shell, "Remove Item", null, "Are you sure?", 0,
+ new String[] { "OK", "Cancel" }, 0);
+ dialog.create();
+ if (dialog.open() == 0)
+ deleteItem(resources);
+
+ return null;
+ }
+
+ public static void deleteItem(final Resource[] resources) {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException {
+ for (Resource r : resources)
+ RemoverUtil.remove(graph, r);
+ }
+ });
+ } catch (DatabaseException e) {
+ ExceptionUtils.logAndShowError(e);
+ }
+ }
+
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IDynamicExperiment;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynExperiment;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class RunBasicExperiment extends AbstractHandler implements IElementUpdater {\r
- \r
- public static final String COMMAND = "org.simantics.sysdyn.ui.run";\r
- \r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- HandlerUtils.saveBeforeExperimentRun(event);\r
-\r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof IDynamicExperiment)\r
- ((IDynamicExperiment)experiment).simulate(true);\r
- return null;\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof SysdynExperiment) {\r
- ExperimentState state = experiment.getState();\r
- if(state == ExperimentState.RUNNING) {\r
- this.setBaseEnabled(false);\r
- } else {\r
- this.setBaseEnabled(true);\r
- }\r
- } \r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers;
+
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IDynamicExperiment;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynExperiment;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+public class RunBasicExperiment extends AbstractHandler implements IElementUpdater {
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.run";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof IDynamicExperiment)
+ ((IDynamicExperiment)experiment).simulate(true);
+ return null;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof SysdynExperiment) {
+ ExperimentState state = experiment.getState();
+ if(state == ExperimentState.RUNNING) {
+ this.setBaseEnabled(false);
+ } else {
+ this.setBaseEnabled(true);
+ }
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.simantics.simulation.experiment.IDynamicExperiment;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class SaveResultsHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- HandlerUtils.saveBeforeExperimentRun(event);\r
- \r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof IDynamicExperiment) {\r
- ((IDynamicExperiment)experiment).saveState();\r
- }\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.IDynamicExperiment;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+public class SaveResultsHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof IDynamicExperiment) {
+ ((IDynamicExperiment)experiment).saveState();
+ }
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.IEditorPart;\r
-import org.eclipse.ui.PartInitException;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.exception.MissingVariableException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.modeling.ComponentUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.editor.DiagramViewer;\r
-import org.simantics.sysdyn.ui.editor.SysdynEditorInput;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
-\r
-\r
-public class ShowModuleHandler extends AbstractHandler {\r
-\r
- private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- ISelection s = HandlerUtil.getCurrentSelectionChecked(event);\r
- final Resource resources[] = ResourceAdaptionUtils.toResources(s);\r
- IEditorPart editor = (IEditorPart)HandlerUtil.getActiveEditor(event);\r
- if (!(editor instanceof DiagramEditor))\r
- return null;\r
- final DiagramViewer viewer = (DiagramViewer) ((DiagramEditor) editor).getViewer();\r
- if (viewer == null)\r
- return null;\r
- \r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
-\r
- DiagramResource dr = DiagramResource.getInstance(graph);\r
- Resource runtime = viewer.getRuntime();\r
- String uri = graph.getPossibleRelatedValue(runtime, dr.RuntimeDiagram_HasVariable, Bindings.STRING);\r
- Variable parent = Variables.getVariable(graph, uri);\r
- final Resource model = Variables.getModel(graph, parent);\r
- \r
- for(Resource element : resources) {\r
-\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- StructuralResource2 st = StructuralResource2.getInstance(graph);\r
- \r
- final Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
- final Resource componentType = graph.getPossibleType(component, sr.Module);\r
- final Resource configuration = graph.getPossibleObject(componentType, st.IsDefinedBy);\r
- final Resource diagram = ComponentUtils.getPossibleCompositeDiagram(graph, configuration);\r
-\r
- Variable variable;\r
- String rvi = "";\r
- try {\r
- variable = parent.browse(graph, component);\r
- rvi = Variables.getRVI(graph, variable);\r
- } catch (MissingVariableException e ) {\r
- variable = Variables.getVariable(graph, graph.getURI(component));\r
- }\r
- final String finalRvi = rvi;\r
- \r
-\r
- \r
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- try {\r
- String editorId = EDITOR_ID;\r
- WorkbenchUtils.openEditor(editorId, new SysdynEditorInput(editorId, diagram, model, finalRvi));\r
- } catch (PartInitException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
- \r
- }\r
- \r
- }\r
- });\r
- \r
- return null;\r
- }\r
- \r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+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;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.exception.MissingVariableException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.diagram.stubs.DiagramResource;
+import org.simantics.modeling.ComponentUtils;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.editor.DiagramViewer;
+import org.simantics.sysdyn.ui.editor.SysdynEditorInput;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+
+public class ShowModuleHandler extends AbstractHandler {
+
+ private static final String EDITOR_ID = "org.simantics.sysdyn.ui.diagramViewer";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection s = HandlerUtil.getCurrentSelectionChecked(event);
+ final Resource resources[] = ResourceAdaptionUtils.toResources(s);
+ IEditorPart editor = (IEditorPart)HandlerUtil.getActiveEditor(event);
+ if (!(editor instanceof DiagramEditor))
+ return null;
+ final DiagramViewer viewer = (DiagramViewer) ((DiagramEditor) editor).getViewer();
+ if (viewer == null)
+ return null;
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+
+ DiagramResource dr = DiagramResource.getInstance(graph);
+ Resource runtime = viewer.getRuntime();
+ String uri = graph.getPossibleRelatedValue(runtime, dr.RuntimeDiagram_HasVariable, Bindings.STRING);
+ Variable parent = Variables.getVariable(graph, uri);
+ final Resource model = Variables.getModel(graph, parent);
+
+ for(Resource element : resources) {
+
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ StructuralResource2 st = StructuralResource2.getInstance(graph);
+
+ final Resource component = graph.getPossibleObject(element, mr.ElementToComponent);
+ final Resource componentType = graph.getPossibleType(component, sr.Module);
+ final Resource configuration = graph.getPossibleObject(componentType, st.IsDefinedBy);
+ final Resource diagram = ComponentUtils.getPossibleCompositeDiagram(graph, configuration);
+
+ Variable variable;
+ String rvi = "";
+ try {
+ variable = parent.browse(graph, component);
+ rvi = Variables.getRVI(graph, variable);
+ } catch (MissingVariableException e ) {
+ variable = Variables.getVariable(graph, graph.getURI(component));
+ }
+ final String finalRvi = rvi;
+
+
+
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ String editorId = EDITOR_ID;
+ WorkbenchUtils.openEditor(editorId, new SysdynEditorInput(editorId, diagram, model, finalRvi));
+ } catch (PartInitException e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+ }
+
+ }
+ });
+
+ return null;
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.Command;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.commands.State;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.commands.ICommandService;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynExperiment;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * @author Tuomas Miettinen\r
- */\r
-public class SynthesisSimulation extends AbstractHandler implements IElementUpdater {\r
-\r
- public static final String COMMAND = "org.simantics.sysdyn.ui.synthesisSimulation";\r
- public static final String STATE = "org.simantics.sysdyn.ui.synthesisSimulation.state";\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = service.getCommand(COMMAND);\r
- State state = command.getState(STATE);\r
- Boolean value = (Boolean) state.getValue();\r
- value = !value;\r
- state.setValue(value);\r
- service.refreshElements(RunBasicExperiment.COMMAND, null);\r
- \r
- Command toggleCommand = service.getCommand(ToggleSimulation.COMMAND);\r
- State toggleState = toggleCommand.getState(ToggleSimulation.STATE);\r
- toggleState.setValue(value);\r
- service.refreshElements(RunBasicExperiment.COMMAND, null);\r
- \r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof SysdynExperiment) {\r
- if(getState()) {\r
- ((SysdynExperiment)experiment).toggleSimulation(true);\r
- } else {\r
- ((SysdynExperiment)experiment).toggleSimulation(false);\r
- }\r
- }\r
- \r
- HandlerUtils.saveBeforeExperimentRun(event);\r
-\r
- return null;\r
- }\r
-\r
- public static Boolean getState() {\r
- ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = service.getCommand(COMMAND);\r
- State state = command.getState(STATE);\r
- return (Boolean)state.getValue();\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- ICommandService commandService =\r
- (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = commandService.getCommand(COMMAND);\r
- boolean checked = (Boolean) command.getState(STATE).getValue();\r
- element.setChecked(checked);\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2014 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.sysdyn.ui.handlers;
+
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.Command;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.State;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.commands.ICommandService;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynExperiment;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+/**
+ * @author Tuomas Miettinen
+ */
+public class SynthesisSimulation extends AbstractHandler implements IElementUpdater {
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.synthesisSimulation";
+ public static final String STATE = "org.simantics.sysdyn.ui.synthesisSimulation.state";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = service.getCommand(COMMAND);
+ State state = command.getState(STATE);
+ Boolean value = (Boolean) state.getValue();
+ value = !value;
+ state.setValue(value);
+ service.refreshElements(RunBasicExperiment.COMMAND, null);
+
+ Command toggleCommand = service.getCommand(ToggleSimulation.COMMAND);
+ State toggleState = toggleCommand.getState(ToggleSimulation.STATE);
+ toggleState.setValue(value);
+ service.refreshElements(RunBasicExperiment.COMMAND, null);
+
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof SysdynExperiment) {
+ if(getState()) {
+ ((SysdynExperiment)experiment).toggleSimulation(true);
+ } else {
+ ((SysdynExperiment)experiment).toggleSimulation(false);
+ }
+ }
+
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ return null;
+ }
+
+ public static Boolean getState() {
+ ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = service.getCommand(COMMAND);
+ State state = command.getState(STATE);
+ return (Boolean)state.getValue();
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ ICommandService commandService =
+ (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = commandService.getCommand(COMMAND);
+ boolean checked = (Boolean) command.getState(STATE).getValue();
+ element.setChecked(checked);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import java.util.concurrent.Semaphore;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.core.runtime.SubMonitor;\r
-import org.eclipse.core.runtime.jobs.Job;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.RequestProcessor;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.AdaptionException;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.message.MessageService;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.model.ExperimentLoadingFailed;\r
-import org.simantics.simulation.project.IExperimentActivationListener;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.ui.listeners.SysdynExperimentManagerListener;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.DataContainer;\r
-import org.simantics.utils.ui.ErrorLogger;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-import org.simantics.utils.ui.dialogs.ShowMessage;\r
-\r
-public class SysdynExperimentActivator extends AbstractHandler {\r
- /**\r
- * @param project\r
- * @param experimentManager\r
- * @param experiment\r
- */\r
- public static void scheduleActivation(RequestProcessor processor, final IProject project, final IExperimentManager experimentManager, final Resource experiment) {\r
- String jobName = "Activate Experiment";\r
- String experimentName = getName(processor, experiment);\r
- if (experimentName != null)\r
- jobName += " '" + experimentName + "'";\r
- /*\r
- // Shut down the previous active experiment\r
- IExperiment activeExperiment = experimentManager.getActiveExperiment();\r
- if (experiment != null)\r
- activeExperiment.shutdown();\r
- */\r
- // Activate a new experiment\r
- scheduleActivation(jobName, project, experimentManager, experiment);\r
- }\r
-\r
- /**\r
- * @param project\r
- * @param experimentManager\r
- * @param experiment\r
- */\r
- public static void scheduleActivation(String jobName, final IProject project, final IExperimentManager experimentManager, final Resource experiment) {\r
- new Job(jobName) {\r
- @Override\r
- protected IStatus run(final IProgressMonitor monitor) {\r
- try {\r
- return SysdynExperimentActivator.activate(monitor, project, experimentManager, experiment);\r
- } finally {\r
- monitor.done();\r
- }\r
- }\r
- }.schedule();\r
- }\r
-\r
- public static IStatus activate(IProgressMonitor monitor, IProject project, IExperimentManager experimentManager, Resource experiment) {\r
- return new SysdynExperimentActivator().activateExperiment(monitor, project, experimentManager, experiment);\r
- }\r
-\r
- private static String getName(RequestProcessor processor, final Resource resource) {\r
- try {\r
- return processor.syncRequest(new Read<String>() {\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- try {\r
- return graph.adapt(resource, String.class);\r
- } catch (AdaptionException e) {\r
- return NameUtils.getSafeName(graph, resource);\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- ErrorLogger.defaultLogWarning(e);\r
- return null;\r
- }\r
- }\r
-\r
- private IStatus activateExperiment(final IProgressMonitor monitor, final IProject project, final IExperimentManager manager, final Resource experimentResource) {\r
- final SubMonitor mon = SubMonitor.convert(monitor, "Activating experiment", 100000);\r
-\r
- SysdynExperimentManagerListener.listenManager(manager);\r
- IExperiment[] experiments = manager.getExperiments();\r
- SubMonitor shutdownMon = mon.newChild(10000);\r
- int workPerExperiment;\r
- if (experiments.length > 0)\r
- workPerExperiment = 10000 / experiments.length;\r
- else\r
- workPerExperiment = 10000;\r
- for(IExperiment e : experiments)\r
- if(e.getState() != ExperimentState.DISPOSED)\r
- e.shutdown(shutdownMon.newChild(workPerExperiment));\r
- mon.setWorkRemaining(90000);\r
-\r
- final Semaphore activated = new Semaphore(0);\r
- final DataContainer<Throwable> problem = new DataContainer<Throwable>();\r
- manager.startExperiment(experimentResource, new IExperimentActivationListener() {\r
-\r
- @Override\r
- public void onExperimentActivated(final IExperiment experiment) {\r
- MessageService.defaultLog(new org.eclipse.core.runtime.Status(IStatus.INFO, "org.simantics.simulation.ui", 0, "Activated experiment " + experiment.getIdentifier() , null));\r
- activated.release();\r
- }\r
- @Override\r
- public void onFailure(Throwable e) {\r
- problem.set(e);\r
- activated.release();\r
- }\r
- @Override\r
- public void onMessage(IStatus message) {\r
- MessageService.getDefault().log(message);\r
- /*ILogger logger = MessageService.getDefault();\r
- MultiStatus init = new MultiStatus(Activator.PLUGIN_ID, 0, "Activating experiment", null);\r
- for (String msg : messages) {\r
- init.add(new Status(IStatus.INFO, Activator.PLUGIN_ID, msg));\r
- }\r
- logger.log(init);*/\r
- }\r
- @Override\r
- public IProgressMonitor getProgressMonitor() {\r
- return mon;\r
- }\r
- }, true);\r
- try {\r
- activated.acquire();\r
- Throwable t = problem.get();\r
- if (t != null) {\r
- if (t instanceof ExperimentLoadingFailed) {\r
- ErrorLogger.defaultLogError(t);\r
- ShowMessage.showError("Experiment Activation Failed", t.getMessage());\r
- } else {\r
- ExceptionUtils.logAndShowError(t);\r
- }\r
- }\r
-\r
- return Status.OK_STATUS;\r
- //return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Experiment activation failed, see exception for details.", problem.get());\r
- } catch (InterruptedException e) {\r
- return Status.CANCEL_STATUS;\r
- }\r
- }\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ISelection selection = HandlerUtil.getCurrentSelection(event);\r
- final Resource experiment = ResourceAdaptionUtils.toSingleResource(selection);\r
- if (experiment == null)\r
- return null;\r
-\r
- final IProject project = SimanticsUI.getProject();\r
- if (project == null)\r
- return null;\r
- \r
- final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- if (experimentManager == null) {\r
- ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());\r
- return null;\r
- }\r
- \r
- SysdynExperimentActivator.scheduleActivation(SimanticsUI.getSession(), project, experimentManager, experiment);\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2014 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.sysdyn.ui.handlers;
+
+import java.util.concurrent.Semaphore;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.SubMonitor;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.RequestProcessor;
+import org.simantics.db.Resource;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.AdaptionException;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.message.MessageService;
+import org.simantics.project.IProject;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.model.ExperimentLoadingFailed;
+import org.simantics.simulation.project.IExperimentActivationListener;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.ui.listeners.SysdynExperimentManagerListener;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.DataContainer;
+import org.simantics.utils.ui.ErrorLogger;
+import org.simantics.utils.ui.ExceptionUtils;
+import org.simantics.utils.ui.dialogs.ShowMessage;
+
+public class SysdynExperimentActivator extends AbstractHandler {
+ /**
+ * @param project
+ * @param experimentManager
+ * @param experiment
+ */
+ public static void scheduleActivation(RequestProcessor processor, final IProject project, final IExperimentManager experimentManager, final Resource experiment) {
+ String jobName = "Activate Experiment";
+ String experimentName = getName(processor, experiment);
+ if (experimentName != null)
+ jobName += " '" + experimentName + "'";
+ /*
+ // Shut down the previous active experiment
+ IExperiment activeExperiment = experimentManager.getActiveExperiment();
+ if (experiment != null)
+ activeExperiment.shutdown();
+ */
+ // Activate a new experiment
+ scheduleActivation(jobName, project, experimentManager, experiment);
+ }
+
+ /**
+ * @param project
+ * @param experimentManager
+ * @param experiment
+ */
+ public static void scheduleActivation(String jobName, final IProject project, final IExperimentManager experimentManager, final Resource experiment) {
+ new Job(jobName) {
+ @Override
+ protected IStatus run(final IProgressMonitor monitor) {
+ try {
+ return SysdynExperimentActivator.activate(monitor, project, experimentManager, experiment);
+ } finally {
+ monitor.done();
+ }
+ }
+ }.schedule();
+ }
+
+ public static IStatus activate(IProgressMonitor monitor, IProject project, IExperimentManager experimentManager, Resource experiment) {
+ return new SysdynExperimentActivator().activateExperiment(monitor, project, experimentManager, experiment);
+ }
+
+ private static String getName(RequestProcessor processor, final Resource resource) {
+ try {
+ return processor.syncRequest(new Read<String>() {
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ try {
+ return graph.adapt(resource, String.class);
+ } catch (AdaptionException e) {
+ return NameUtils.getSafeName(graph, resource);
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ ErrorLogger.defaultLogWarning(e);
+ return null;
+ }
+ }
+
+ private IStatus activateExperiment(final IProgressMonitor monitor, final IProject project, final IExperimentManager manager, final Resource experimentResource) {
+ final SubMonitor mon = SubMonitor.convert(monitor, "Activating experiment", 100000);
+
+ SysdynExperimentManagerListener.listenManager(manager);
+ IExperiment[] experiments = manager.getExperiments();
+ SubMonitor shutdownMon = mon.newChild(10000);
+ int workPerExperiment;
+ if (experiments.length > 0)
+ workPerExperiment = 10000 / experiments.length;
+ else
+ workPerExperiment = 10000;
+ for(IExperiment e : experiments)
+ if(e.getState() != ExperimentState.DISPOSED)
+ e.shutdown(shutdownMon.newChild(workPerExperiment));
+ mon.setWorkRemaining(90000);
+
+ final Semaphore activated = new Semaphore(0);
+ final DataContainer<Throwable> problem = new DataContainer<Throwable>();
+ manager.startExperiment(experimentResource, new IExperimentActivationListener() {
+
+ @Override
+ public void onExperimentActivated(final IExperiment experiment) {
+ MessageService.defaultLog(new org.eclipse.core.runtime.Status(IStatus.INFO, "org.simantics.simulation.ui", 0, "Activated experiment " + experiment.getIdentifier() , null));
+ activated.release();
+ }
+ @Override
+ public void onFailure(Throwable e) {
+ problem.set(e);
+ activated.release();
+ }
+ @Override
+ public void onMessage(IStatus message) {
+ MessageService.getDefault().log(message);
+ /*ILogger logger = MessageService.getDefault();
+ MultiStatus init = new MultiStatus(Activator.PLUGIN_ID, 0, "Activating experiment", null);
+ for (String msg : messages) {
+ init.add(new Status(IStatus.INFO, Activator.PLUGIN_ID, msg));
+ }
+ logger.log(init);*/
+ }
+ @Override
+ public IProgressMonitor getProgressMonitor() {
+ return mon;
+ }
+ }, true);
+ try {
+ activated.acquire();
+ Throwable t = problem.get();
+ if (t != null) {
+ if (t instanceof ExperimentLoadingFailed) {
+ ErrorLogger.defaultLogError(t);
+ ShowMessage.showError("Experiment Activation Failed", t.getMessage());
+ } else {
+ ExceptionUtils.logAndShowError(t);
+ }
+ }
+
+ return Status.OK_STATUS;
+ //return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Experiment activation failed, see exception for details.", problem.get());
+ } catch (InterruptedException e) {
+ return Status.CANCEL_STATUS;
+ }
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection selection = HandlerUtil.getCurrentSelection(event);
+ final Resource experiment = ResourceAdaptionUtils.toSingleResource(selection);
+ if (experiment == null)
+ return null;
+
+ final IProject project = Simantics.getProject();
+ if (project == null)
+ return null;
+
+ final IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ if (experimentManager == null) {
+ ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception());
+ return null;
+ }
+
+ SysdynExperimentActivator.scheduleActivation(Simantics.getSession(), project, experimentManager, experiment);
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-public class ToggleResultActivation extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
- if (resources.length == 0)\r
- return null;\r
-\r
- toggleActivation(resources);\r
-\r
- return null;\r
- }\r
-\r
- public static void toggleActivation(final Resource[] resources) {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for(Resource r : resources) {\r
- if(graph.isInstanceOf(r, sr.Result)) {\r
- if (graph.hasStatement(r, sr.Result_showResult)) {\r
- graph.denyStatement(r, sr.Result_showResult, r);\r
- } else {\r
- graph.claim(r, sr.Result_showResult, r);\r
- }\r
- }\r
- }\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
-\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2011 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.sysdyn.ui.handlers;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+public class ToggleResultActivation extends AbstractHandler {
+
+ public static Object handleStatic(Resource[] dataset) throws ExecutionException {
+ return executeImpl(dataset);
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ Resource[] resources = ResourceAdaptionUtils.toResources(sel);
+ return executeImpl(resources);
+ }
+
+ private static Object executeImpl(Resource[] resources) throws ExecutionException {
+ if (resources.length == 0)
+ return null;
+ toggleActivation(resources);
+ return null;
+ }
+
+ public static void toggleActivation(Resource[] resources) {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for(Resource r : resources) {
+ if(graph.isInstanceOf(r, sr.Result)) {
+ if (graph.hasStatement(r, sr.Result_showResult)) {
+ graph.denyStatement(r, sr.Result_showResult, r);
+ } else {
+ graph.claim(r, sr.Result_showResult, r);
+ }
+ }
+ }
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-import java.util.Collection;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-public class ToggleResultSetActivation extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
- if (resources.length == 0)\r
- return null;\r
-\r
- toggleActivation(resources);\r
-\r
- return null;\r
- }\r
-\r
- public static void toggleActivation(final Resource[] resources) {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for(Resource r : resources) {\r
- // If there is at least one result which shown, clear them all.\r
- // If not one result is shown, show them all.\r
- boolean resultShown = false;\r
- Collection<Resource> results = graph.getObjects(r, sr.Experiment_result); \r
- for (Resource result : results) {\r
- if (graph.hasStatement(result, sr.Result_showResult)) {\r
- resultShown = true;\r
- break;\r
- }\r
- }\r
- for (Resource result : results) {\r
- if (resultShown) { \r
- graph.denyStatement(result, sr.Result_showResult, result);\r
- } else {\r
- graph.claim(result, sr.Result_showResult, result);\r
- }\r
- }\r
- }\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
-\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2011 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.sysdyn.ui.handlers;
+
+import java.util.Collection;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+public class ToggleResultSetActivation extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ Resource[] resources = ResourceAdaptionUtils.toResources(sel);
+ if (resources.length == 0)
+ return null;
+
+ toggleActivation(resources);
+
+ return null;
+ }
+
+ public static void toggleActivation(final Resource[] resources) {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for(Resource r : resources) {
+ // If there is at least one result which shown, clear them all.
+ // If not one result is shown, show them all.
+ boolean resultShown = false;
+ Collection<Resource> results = graph.getObjects(r, sr.Experiment_result);
+ for (Resource result : results) {
+ if (graph.hasStatement(result, sr.Result_showResult)) {
+ resultShown = true;
+ break;
+ }
+ }
+ for (Resource result : results) {
+ if (resultShown) {
+ graph.denyStatement(result, sr.Result_showResult, result);
+ } else {
+ graph.claim(result, sr.Result_showResult, result);
+ }
+ }
+ }
+ }
+
+ });
+ } catch (DatabaseException e) {
+
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers;\r
-\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.Command;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.commands.State;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.commands.ICommandService;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynExperiment;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ToggleSimulation extends AbstractHandler implements IElementUpdater {\r
-\r
- public static final String COMMAND = "org.simantics.sysdyn.ui.toggleSimulation";\r
- public static final String STATE = "org.simantics.sysdyn.ui.toggleSimulation.state";\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = service.getCommand(COMMAND);\r
- State state = command.getState(STATE);\r
- Boolean value = (Boolean) state.getValue();\r
- value = !value;\r
- state.setValue(value);\r
- service.refreshElements(RunBasicExperiment.COMMAND, null);\r
- \r
- Command synthesisCommand = service.getCommand(SynthesisSimulation.COMMAND);\r
- State synthesisState = synthesisCommand.getState(SynthesisSimulation.STATE);\r
- synthesisState.setValue(false);\r
- service.refreshElements(RunBasicExperiment.COMMAND, null);\r
- \r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof SysdynExperiment) {\r
- if(getState()) {\r
- ((SysdynExperiment)experiment).toggleSimulation(true);\r
- } else {\r
- ((SysdynExperiment)experiment).toggleSimulation(false);\r
- }\r
- }\r
- \r
- HandlerUtils.saveBeforeExperimentRun(event);\r
-\r
- return null;\r
- }\r
-\r
- public static Boolean getState() {\r
- ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = service.getCommand(COMMAND);\r
- State state = command.getState(STATE);\r
- return (Boolean)state.getValue();\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- ICommandService commandService =\r
- (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = commandService.getCommand(COMMAND);\r
- boolean checked = (Boolean) command.getState(STATE).getValue();\r
- element.setChecked(checked);\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2014 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.sysdyn.ui.handlers;
+
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.Command;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.State;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.commands.ICommandService;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynExperiment;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+public class ToggleSimulation extends AbstractHandler implements IElementUpdater {
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.toggleSimulation";
+ public static final String STATE = "org.simantics.sysdyn.ui.toggleSimulation.state";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = service.getCommand(COMMAND);
+ State state = command.getState(STATE);
+ Boolean value = (Boolean) state.getValue();
+ value = !value;
+ state.setValue(value);
+ service.refreshElements(RunBasicExperiment.COMMAND, null);
+
+ Command synthesisCommand = service.getCommand(SynthesisSimulation.COMMAND);
+ State synthesisState = synthesisCommand.getState(SynthesisSimulation.STATE);
+ synthesisState.setValue(false);
+ service.refreshElements(RunBasicExperiment.COMMAND, null);
+
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof SysdynExperiment) {
+ if(getState()) {
+ ((SysdynExperiment)experiment).toggleSimulation(true);
+ } else {
+ ((SysdynExperiment)experiment).toggleSimulation(false);
+ }
+ }
+
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ return null;
+ }
+
+ public static Boolean getState() {
+ ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = service.getCommand(COMMAND);
+ State state = command.getState(STATE);
+ return (Boolean)state.getValue();
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ ICommandService commandService =
+ (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = commandService.getCommand(COMMAND);
+ boolean checked = (Boolean) command.getState(STATE).getValue();
+ element.setChecked(checked);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.exports;\r
-\r
-import java.io.FileOutputStream;\r
-import java.io.IOException;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.widgets.DirectoryDialog;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-/**\r
- * Exports external function files from SysdynModelicaFunctions\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ExportExternalFunctionFilesHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- // Find shell and resources to be exported\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- final Resource[] resources = ResourceAdaptionUtils.toResources(sel);\r
- if (resources.length < 1)\r
- return null;\r
-\r
- return exportFiles(shell, resources);\r
- }\r
- \r
- /**\r
- * Exports selected file resources to files on disk. Assumes all resources are external files.\r
- * \r
- * @param shell SWT Shell\r
- * @param resources External file resources\r
- * @return null\r
- */\r
- public static Object exportFiles(Shell shell, final Resource[] resources) {\r
- \r
- // Select a path where to export the files\r
- DirectoryDialog dd = new DirectoryDialog(shell);\r
- dd.setFilterPath(Platform.getLocation().toOSString());\r
- dd.setText("Export files to...");\r
- dd.setMessage("Select a directory");\r
- final String dir = dd.open();\r
- if (dir == null) {\r
- return null;\r
- }\r
-\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- // Get byte arrays from each resource and write them to disk\r
- for(Resource r : resources) {\r
- try {\r
- String name = NameUtils.getSafeName(graph, r);\r
- FileOutputStream fos = new FileOutputStream(dir + "\\" + name);\r
- byte[] fileBArray = graph.getPossibleRelatedValue(r, sr.ExternalFunctionFile_externalFile, Bindings.BYTE_ARRAY);\r
- fos.write(fileBArray);\r
- fos.close();\r
- } catch (IOException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- }\r
- });\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.exports;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.widgets.DirectoryDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+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;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+/**
+ * Exports external function files from SysdynModelicaFunctions
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ExportExternalFunctionFilesHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ // Find shell and resources to be exported
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ final Resource[] resources = ResourceAdaptionUtils.toResources(sel);
+ if (resources.length < 1)
+ return null;
+
+ return exportFiles(shell, resources);
+ }
+
+ /**
+ * Exports selected file resources to files on disk. Assumes all resources are external files.
+ *
+ * @param shell SWT Shell
+ * @param resources External file resources
+ * @return null
+ */
+ public static Object exportFiles(Shell shell, final Resource[] resources) {
+
+ // Select a path where to export the files
+ DirectoryDialog dd = new DirectoryDialog(shell);
+ dd.setFilterPath(Platform.getLocation().toOSString());
+ dd.setText("Export files to...");
+ dd.setMessage("Select a directory");
+ final String dir = dd.open();
+ if (dir == null) {
+ return null;
+ }
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ // Get byte arrays from each resource and write them to disk
+ for(Resource r : resources) {
+ try {
+ String name = NameUtils.getSafeName(graph, r);
+ FileOutputStream fos = new FileOutputStream(dir + "\\" + name);
+ byte[] fileBArray = graph.getPossibleRelatedValue(r, sr.ExternalFunctionFile_externalFile, Bindings.BYTE_ARRAY);
+ fos.write(fileBArray);
+ fos.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ }
+ });
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.exports;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
-import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.graph.db.TransferableGraphSource;\r
-import org.simantics.graph.db.TransferableGraphs;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-/**\r
- * Exports a function library\r
- * \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ExportFunctionLibrary extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- final Resource functionLibrary = ResourceAdaptionUtils.toSingleResource(sel);\r
- if(functionLibrary == null) return null;\r
- \r
- String name = null;\r
- try {\r
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf))\r
- return null;\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));\r
- return name;\r
- \r
- }\r
- \r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- // Do not export if the resource has no name\r
- if(name == null) return null;\r
- \r
- // Find a location (and name) for the exported library using FileDialog\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
- fd.setText("Export Function Library");\r
- fd.setFileName(name);\r
- String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH);\r
- if(path.isEmpty() || !(new File(path).exists()))\r
- path = Platform.getLocation().toOSString();\r
- fd.setFilterPath(path);\r
- String[] filterExt = {"*.sysdynFunctions"};\r
- fd.setFilterExtensions(filterExt);\r
- fd.setOverwrite(true);\r
- final String selected = fd.open();\r
- if(selected == null) return null;\r
- \r
- // Save location to preference store\r
- Activator.getDefault().getPreferenceStore().setValue(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH, (new File(selected)).getParent());\r
-\r
- // Asynchronously create the file using transferable graph\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, functionLibrary);\r
- TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));\r
- try {\r
- TransferableGraphs.writeTransferableGraph(graph, "sysdynFunctionLibrary", 1, s,new File(selected));\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
-\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2013 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.sysdyn.ui.handlers.exports;
+
+import java.io.File;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
+import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
+import org.simantics.db.request.Read;
+import org.simantics.graph.db.TransferableGraphSource;
+import org.simantics.graph.db.TransferableGraphs;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+/**
+ * Exports a function library
+ *
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class ExportFunctionLibrary extends AbstractHandler {
+
+ public static Object handleStatic(Resource functionLibrary) throws ExecutionException {
+ Shell shell = WorkbenchUtils.getActiveWorkbenchWindowShell();
+ return(executeImpl(functionLibrary, shell));
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ final Resource functionLibrary = ResourceAdaptionUtils.toSingleResource(sel);
+ if(functionLibrary == null) return null;
+
+ // Find a location (and name) for the exported library using FileDialog
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ return(executeImpl(functionLibrary, shell));
+ }
+
+ private static Object executeImpl(Resource functionLibrary, Shell shell) throws ExecutionException {
+ String name = null;
+ try {
+ name = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf))
+ return null;
+ Layer0 l0 = Layer0.getInstance(graph);
+ String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));
+ return name;
+
+ }
+
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ // Do not export if the resource has no name
+ if(name == null) return null;
+
+ FileDialog fd = new FileDialog(shell, SWT.SAVE);
+ fd.setText("Export Function Library");
+ fd.setFileName(name);
+ String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH);
+ if(path.isEmpty() || !(new File(path).exists()))
+ path = Platform.getLocation().toOSString();
+ fd.setFilterPath(path);
+ String[] filterExt = {"*.sysdynFunctions"};
+ fd.setFilterExtensions(filterExt);
+ fd.setOverwrite(true);
+ final String selected = fd.open();
+ if(selected == null) return null;
+
+ // Save location to preference store
+ Activator.getDefault().getPreferenceStore().setValue(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH, (new File(selected)).getParent());
+
+ // Asynchronously create the file using transferable graph
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, functionLibrary);
+ TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
+ try {
+ TransferableGraphs.writeTransferableGraph(graph, "sysdynFunctionLibrary", 1, s,new File(selected));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.exports;\r
-\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
-\r
-/**\r
- * Exports a selected model asking the location.\r
- * Model determination is based on any resource of the model.\r
- * \r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ExportModelAsButtonHandler extends ExportModelButtonHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
- \r
- final Resource model = determineModel(event);\r
- if (model == null)\r
- return null;\r
- \r
- String selected = getAbsolutePath(model, event, true);\r
- \r
- if (selected != null) {\r
- createFile(model, selected);\r
- setExportStatus(model, selected);\r
- }\r
- \r
- return null;\r
- }\r
-\r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers.exports;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.db.Resource;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+/**
+ * Exports a selected model asking the location.
+ * Model determination is based on any resource of the model.
+ *
+ * @author Tuomas Miettinen
+ *
+ */
+public class ExportModelAsButtonHandler extends ExportModelButtonHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );
+
+ final Resource model = determineModel(event);
+ if (model == null)
+ return null;
+
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ String selected = getAbsolutePath(model, shell, true);
+
+ if (selected != null) {
+ createFile(model, selected);
+ setExportStatus(model, selected);
+ }
+
+ return null;
+ }
+
+}
+
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.exports;\r
-\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.ui.IWorkbenchPage;\r
-import org.eclipse.ui.IWorkbenchPart;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.platform.PropertyPageView;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.request.PossibleModel;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
-import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
-\r
-/**\r
- * Exports a selected model without asking the location.\r
- * Model determination is based on any resource of the model.\r
- * \r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ExportModelButtonHandler extends ExportModelHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
- \r
- final Resource model = determineModel(event);\r
- if (model == null)\r
- return null;\r
-\r
- String selected = getAbsolutePath(model, event, false);\r
- \r
- if (selected != null) {\r
- createFile(model, selected);\r
- setExportStatus(model, selected);\r
- }\r
- \r
- return null;\r
- }\r
-\r
- @Override\r
- protected Resource determineModel(ExecutionEvent event) {\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- if (sel == null) {\r
- // No selection, this is true e.g. in PropertyPageView\r
- IWorkbenchPart activePart = HandlerUtil.getActivePart(event);\r
- // In such a case get the selection the PropertyPageView point to.\r
- if (activePart instanceof PropertyPageView)\r
- sel = ((PropertyPageView)activePart).getLastSelection();\r
- }\r
- \r
- // Get the Resource of the selection\r
- Resource inputResource = ResourceAdaptionUtils.toSingleResource(sel);\r
- if (inputResource == null) {\r
- // Coner case for when export is called when some folder in model browser is selected.\r
- if (sel instanceof IStructuredSelection) {\r
- IStructuredSelection iss = (IStructuredSelection) sel;\r
- if (iss.size() == 1) {\r
- Object element = iss.getFirstElement();\r
- AbstractNode<?> a = AdaptionUtils.adaptToSingle(element, AbstractNode.class);\r
- if (a != null)\r
- inputResource = (Resource)a.data;\r
- }\r
- }\r
- }\r
- \r
- // When the selection doesn't have a resource, use the currently active diagram.\r
- if (inputResource == null) {\r
- IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();\r
- DiagramEditor editor = (DiagramEditor)page.getActiveEditor();\r
- if (editor != null && editor instanceof DiagramEditor) {\r
- inputResource = editor.getInputResource();\r
- } else {\r
- return null; \r
- }\r
- }\r
- \r
- // Now that we finally have determined which Resource is selected, we just need\r
- // to get the model of that Resource.\r
- Resource model;\r
- final Resource resource = inputResource;\r
- try {\r
- model = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return graph.sync(new PossibleModel(resource));\r
- }\r
- \r
- });\r
- if(model == null) return null;\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- return null;\r
- }\r
- return model;\r
- }\r
- \r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers.exports;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPart;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.platform.PropertyPageView;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.request.PossibleModel;
+import org.simantics.db.request.Read;
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;
+import org.simantics.sysdyn.ui.utils.SysdynWorkbenchUtils;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.AdaptionUtils;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+/**
+ * Exports a selected model without asking the location.
+ * Model determination is based on any resource of the model.
+ *
+ * @author Tuomas Miettinen
+ *
+ */
+public class ExportModelButtonHandler extends ExportModelHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );
+
+ final Resource model = determineModel(event);
+ if (model == null)
+ return null;
+
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ String selected = getAbsolutePath(model, shell, false);
+
+ if (selected != null) {
+ createFile(model, selected);
+ setExportStatus(model, selected);
+ }
+
+ return null;
+ }
+
+ @Override
+ protected Resource determineModel(ExecutionEvent event) {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ if (sel == null) {
+ // No selection, this is true e.g. in PropertyPageView
+ IWorkbenchPart activePart = HandlerUtil.getActivePart(event);
+ // In such a case get the selection the PropertyPageView point to.
+ if (activePart instanceof PropertyPageView)
+ sel = ((PropertyPageView)activePart).getLastSelection();
+ }
+
+ // Get the Resource of the selection
+ Resource inputResource = ResourceAdaptionUtils.toSingleResource(sel);
+ if (inputResource == null) {
+ // Coner case for when export is called when some folder in model browser is selected.
+ if (sel instanceof IStructuredSelection) {
+ IStructuredSelection iss = (IStructuredSelection) sel;
+ if (iss.size() == 1) {
+ Object element = iss.getFirstElement();
+ AbstractNode<?> a = AdaptionUtils.adaptToSingle(element, AbstractNode.class);
+ if (a != null)
+ inputResource = (Resource)a.data;
+ }
+ }
+ }
+
+ // When the selection doesn't have a resource, use the currently active diagram.
+ if (inputResource == null) {
+ IWorkbenchPage page = SysdynWorkbenchUtils.getActivePageOfEditor();
+ DiagramEditor editor = (DiagramEditor)page.getActiveEditor();
+ if (editor != null && editor instanceof DiagramEditor) {
+ inputResource = editor.getInputResource();
+ } else {
+ return null;
+ }
+ }
+
+ // Now that we finally have determined which Resource is selected, we just need
+ // to get the model of that Resource.
+ Resource model;
+ final Resource resource = inputResource;
+ try {
+ model = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return graph.sync(new PossibleModel(resource));
+ }
+
+ });
+ if(model == null) return null;
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ return null;
+ }
+ return model;
+ }
+
+}
+
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.exports;\r
-\r
-import java.io.File;\r
-import java.lang.reflect.InvocationTargetException;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.NullProgressMonitor;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.jface.action.IStatusLineManager;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.modelExport.SysdynModelExporter;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
-\r
-/**\r
- * Exports a selected model\r
- * Model determination is based on the very Resource of the model.\r
- * \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ExportModelHandler extends AbstractHandler {\r
-\r
- protected static IStatusLineManager status;\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
- \r
- final Resource model = determineModel(event);\r
- if (model == null)\r
- return null;\r
- \r
- String selected = getAbsolutePath(model, event, true);\r
- \r
- if (selected != null) {\r
- createFile(model, selected);\r
- setExportStatus(model, selected);\r
- }\r
-\r
- return null;\r
- }\r
- \r
- /**\r
- * Create the export file.\r
- * @param model Model which is exported.\r
- * @param fileName Full name of the file.\r
- */\r
- protected void setExportStatus(final Resource model, final String fileName) {\r
- try {\r
- String modelName = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
- \r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
- return null;\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- return graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));\r
- }\r
- \r
- });\r
- \r
- if (modelName != null)\r
- setStatus("Saved model \"" + modelName + "\" to " + fileName);\r
- \r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- /**\r
- * Create the export file.\r
- * @param model Model which is exported.\r
- * @param fileName Full name of the file.\r
- */\r
- protected void createFile(final Resource model, final String fileName) {\r
- File exportLocation = new File(fileName);\r
- try {\r
- SysdynModelExporter.exportModel(new NullProgressMonitor(), model, exportLocation, "", false);\r
- } catch (InvocationTargetException e1) {\r
- ExceptionUtils.logAndShowError("Model Export Failed", "Sysdyn model export failed, see exception for details", e1);\r
- }\r
-\r
-// // Asynchronously create the file using transferable graph\r
-// SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
-//\r
-// @Override\r
-// public void run(ReadGraph graph) throws DatabaseException {\r
-// HashMap<Resource, ExtentStatus> map = new HashMap<Resource, ExtentStatus>();\r
-// \r
-// Resource relation = graph.getPossibleResource("http://www.simantics.org/Documentation-1.1/createdBy");\r
-// if(relation != null) {\r
-// Resource createdBy = graph.getPossibleObject(model, relation);\r
-// if(createdBy != null)\r
-// map.put(createdBy, ExtentStatus.EXCLUDED);\r
-// }\r
-// \r
-// TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model);\r
-// conf.preStatus.putAll(map);\r
-// \r
-// TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));\r
-// try {\r
-// TransferableGraphs.writeTransferableGraph(graph, "sysdynModel", 1, s,new File(fileName));\r
-// } catch (Exception e) {\r
-// ExceptionUtils.logAndShowError("Model Export Failed", "Sysdyn model export failed, see exception for details", e);\r
-// \r
-// File modelFile = new File(fileName);\r
-// if (modelFile.exists())\r
-// modelFile.delete();\r
-// }\r
-// }\r
-// });\r
- }\r
- \r
- /**\r
- * Get the model Resource based on the event.\r
- * @param event\r
- * @return model Resource which the event refers to.\r
- */\r
- protected Resource determineModel(ExecutionEvent event) {\r
- // Just get the selected model.\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- final Resource model = ResourceAdaptionUtils.toSingleResource(sel);\r
- return model;\r
- }\r
- \r
- /**\r
- * Get the absolute save path for the export file and save it to the database.\r
- * @param model Model Resource which is exported.\r
- * @param event\r
- * @param saveAs true if save as... functionality is used; otherwise save \r
- * functionality is used. \r
- * @return The full path name of the exported model.\r
- * @throws ExecutionException\r
- */\r
- protected String getAbsolutePath(final Resource model, ExecutionEvent event, boolean saveAs) throws ExecutionException {\r
-\r
- // Determine the default path.\r
- String path = null;\r
- try {\r
- //If the model has been exported earlier, use that path.\r
- path = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
- return null;\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- String path = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFilePath, Bindings.STRING ));\r
- return path;\r
- \r
- }\r
- \r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- // If this is the initial save:\r
- if (path == null) {\r
- if (saveAs == false) {\r
- // Save == Save as... when there has been no earlier save. \r
- return getAbsolutePath(model, event, true);\r
- }\r
- // Use import default path.\r
- path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
- }\r
- if (saveAs == false && !(new File(path).exists())) {\r
- // Save == Save as... when the path doesn't exist. \r
- return getAbsolutePath(model, event, true);\r
- }\r
- if(path.isEmpty() || !(new File(path).exists()))\r
- path = Platform.getLocation().toOSString();\r
- \r
- // Determine the default name\r
- // FIXME: Model browser doesn't change its selection even if the selected object is removed,\r
- // so you can try to export a removed model \r
- String name = null;\r
- try {\r
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))\r
- return null;\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- // If the model has been exported earlier, use that name.\r
- // When mere Save has progressed here, there is always be the name in the database. \r
- String name = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFileName, Bindings.STRING ));\r
- if (name == null) {\r
- // If not, use the model name.\r
- name = graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));\r
- }\r
- return name;\r
- \r
- }\r
- \r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- // Do not export if the resource has no name\r
- if(name == null) return null;\r
- \r
- final String selected;\r
- String fullPath = null;\r
- if (saveAs == true) {\r
- // Find a location (and name) for the exported library using FileDialog\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
- fd.setText("Export Model");\r
- fd.setFileName(name);\r
- \r
- fd.setFilterPath(path);\r
- String[] filterExt = {"*.sysdyn"};\r
- fd.setFilterExtensions(filterExt);\r
- fd.setOverwrite(true);\r
- fullPath = fd.open();\r
- }\r
- else {\r
- // Save to the earlier location. \r
- fullPath = path;\r
- if (path.charAt(path.length() - 1) != '\\')\r
- fullPath += "\\"; // Saving to C:\ would otherwise add excess backslashes.\r
- fullPath += name;\r
- }\r
- selected = fullPath;\r
- \r
- if(selected == null) return null;\r
-\r
- // Save location to preference store\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- graph.deny(model, SR.SysdynModel_lastExportFilePath);\r
- graph.deny(model, SR.SysdynModel_lastExportFileName);\r
- graph.addLiteral(model, SR.SysdynModel_lastExportFilePath, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getParent(), Bindings.STRING);\r
- graph.addLiteral(model, SR.SysdynModel_lastExportFileName, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getName(), Bindings.STRING); \r
- }\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- \r
- return selected;\r
-\r
- }\r
- \r
- protected static void setStatus(final String message) {\r
- if (status != null)\r
- status.setMessage(message);\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers.exports;
+
+import java.io.File;
+import java.lang.reflect.InvocationTargetException;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.action.IStatusLineManager;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+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.primitiverequest.PossibleRelatedValue;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.modelExport.SysdynModelExporter;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.ExceptionUtils;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+/**
+ * Exports a selected model
+ * Model determination is based on the very Resource of the model.
+ *
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class ExportModelHandler extends AbstractHandler {
+
+ protected static IStatusLineManager status;
+
+ public static Object handleStatic(Resource model) throws ExecutionException {
+ ExportModelHandler emh = new ExportModelHandler();
+ try {
+ status = WorkbenchUtils.getStatusLine(WorkbenchUtils.getActiveWorkbenchPart().getSite());
+ } catch (NullPointerException e) {
+ e.printStackTrace();
+ }
+
+ Shell shell = WorkbenchUtils.getActiveWorkbenchWindowShell();
+ String selected = emh.getAbsolutePath(model, shell, true);
+ return emh.executeImpl(model, selected);
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );
+ final Resource model = determineModel(event);
+ if (model == null)
+ return null;
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ String selected = getAbsolutePath(model, shell, true);
+ return executeImpl(model, selected);
+ }
+
+ private Object executeImpl(Resource model, String selected) throws ExecutionException {
+ if (selected != null) {
+ createFile(model, selected);
+ setExportStatus(model, selected);
+ }
+ return null;
+ }
+
+ /**
+ * Create the export file.
+ * @param model Model which is exported.
+ * @param fileName Full name of the file.
+ */
+ protected void setExportStatus(final Resource model, final String fileName) {
+ try {
+ String modelName = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))
+ return null;
+ Layer0 l0 = Layer0.getInstance(graph);
+ return graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));
+ }
+
+ });
+
+ if (modelName != null)
+ setStatus("Saved model \"" + modelName + "\" to " + fileName);
+
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Create the export file.
+ * @param model Model which is exported.
+ * @param fileName Full name of the file.
+ */
+ protected void createFile(final Resource model, final String fileName) {
+ File exportLocation = new File(fileName);
+ try {
+ SysdynModelExporter.exportModel(new NullProgressMonitor(), model, exportLocation, "", false);
+ } catch (InvocationTargetException e1) {
+ ExceptionUtils.logAndShowError("Model Export Failed", "Sysdyn model export failed, see exception for details", e1);
+ }
+ }
+
+ /**
+ * Get the model Resource based on the event.
+ * @param event
+ * @return model Resource which the event refers to.
+ */
+ protected Resource determineModel(ExecutionEvent event) {
+ // Just get the selected model.
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ final Resource model = ResourceAdaptionUtils.toSingleResource(sel);
+ return model;
+ }
+
+ /**
+ * Get the absolute save path for the export file and save it to the database.
+ * @param model Model Resource which is exported.
+ * @param event
+ * @param saveAs true if save as... functionality is used; otherwise save
+ * functionality is used.
+ * @return The full path name of the exported model.
+ * @throws ExecutionException
+ */
+ protected String getAbsolutePath(final Resource model, Shell shell, boolean saveAs) throws ExecutionException {
+
+ // Determine the default path.
+ String path = null;
+ try {
+ //If the model has been exported earlier, use that path.
+ path = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))
+ return null;
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ String path = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFilePath, Bindings.STRING ));
+ return path;
+
+ }
+
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ // If this is the initial save:
+ if (path == null) {
+ if (saveAs == false) {
+ // Save == Save as... when there has been no earlier save.
+ return getAbsolutePath(model, shell, true);
+ }
+ // Use import default path.
+ path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);
+ }
+ if (saveAs == false && !(new File(path).exists())) {
+ // Save == Save as... when the path doesn't exist.
+ return getAbsolutePath(model, shell, true);
+ }
+ if(path.isEmpty() || !(new File(path).exists()))
+ path = Platform.getLocation().toOSString();
+
+ // Determine the default name
+ // FIXME: Model browser doesn't change its selection even if the selected object is removed,
+ // so you can try to export a removed model
+ String name = null;
+ try {
+ name = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ if (!graph.hasStatement(model, Layer0.getInstance(graph).PartOf))
+ return null;
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ // If the model has been exported earlier, use that name.
+ // When mere Save has progressed here, there is always be the name in the database.
+ String name = graph.syncRequest(new PossibleRelatedValue<String>(model, SR.SysdynModel_lastExportFileName, Bindings.STRING ));
+ if (name == null) {
+ // If not, use the model name.
+ name = graph.syncRequest(new PossibleRelatedValue<String>(model, l0.HasName, Bindings.STRING ));
+ }
+ return name;
+
+ }
+
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ // Do not export if the resource has no name
+ if(name == null) return null;
+
+ final String selected;
+ String fullPath = null;
+ if (saveAs == true) {
+ // Find a location (and name) for the exported library using FileDialog
+ FileDialog fd = new FileDialog(shell, SWT.SAVE);
+ fd.setText("Export Model");
+ fd.setFileName(name);
+
+ fd.setFilterPath(path);
+ String[] filterExt = {"*.sysdyn"};
+ fd.setFilterExtensions(filterExt);
+ fd.setOverwrite(true);
+ fullPath = fd.open();
+ }
+ else {
+ // Save to the earlier location.
+ fullPath = path;
+ if (path.charAt(path.length() - 1) != '\\')
+ fullPath += "\\"; // Saving to C:\ would otherwise add excess backslashes.
+ fullPath += name;
+ }
+ selected = fullPath;
+
+ if(selected == null) return null;
+
+ // Save location to preference store
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ graph.deny(model, SR.SysdynModel_lastExportFilePath);
+ graph.deny(model, SR.SysdynModel_lastExportFileName);
+ graph.addLiteral(model, SR.SysdynModel_lastExportFilePath, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getParent(), Bindings.STRING);
+ graph.addLiteral(model, SR.SysdynModel_lastExportFileName, SR.SysdynModel_lastExportFilePath_Inverse, l0.String, new File(selected).getName(), Bindings.STRING);
+ }
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+
+ return selected;
+
+ }
+
+ protected static void setStatus(final String message) {
+ if (status != null)
+ status.setMessage(message);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.exports;\r
-\r
-import java.io.File;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.MessageBox;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
-import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.graph.db.TransferableGraphSource;\r
-import org.simantics.graph.db.TransferableGraphs;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-/**\r
- * Exports a selected module\r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ExportModuleHandler extends AbstractHandler {\r
-\r
- /**\r
- * Temporary exception. At this phase, the system will not support exporting modules\r
- * that depend on other modules. \r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
- class ContainsDependenciesException extends DatabaseException {\r
- private static final long serialVersionUID = -1533706136673146020L;\r
- \r
- private final Collection<String> dependencies;\r
- \r
- ContainsDependenciesException(Collection<String> dependencies) {\r
- this.dependencies = dependencies;\r
- }\r
- \r
- public Collection<String> getDependencies() {\r
- return this.dependencies;\r
- }\r
- \r
- }\r
- \r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- final Resource modulesymbol = ResourceAdaptionUtils.toSingleResource(sel);\r
- if(modulesymbol == null) return null;\r
- \r
- String name = null;\r
- try {\r
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- // Start checking for module dependencies\r
- Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);\r
- if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
- return null;\r
- \r
- Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
- if (configuration == null)\r
- return null;\r
- \r
- ArrayList<String> dependencies = null;\r
- for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {\r
- if(dependencies == null)\r
- dependencies = new ArrayList<String>();\r
- String name = NameUtils.getSafeName(graph, r);\r
- String instanceOf = NameUtils.getSafeName(graph, graph.getSingleObject(r, l0.InstanceOf));\r
- dependencies.add(name + " : " + instanceOf);\r
- }\r
- if(dependencies != null && !dependencies.isEmpty())\r
- throw new ContainsDependenciesException(dependencies);\r
- // End checking for module dependencies. If dependencies were found, an exception was thrown\r
- \r
- String name = graph.getPossibleRelatedValue(component, l0.HasName, Bindings.STRING);\r
- return name;\r
- \r
- }\r
- \r
- });\r
- } catch (ContainsDependenciesException e1) {\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- MessageBox mb = new MessageBox(shell, SWT.OK);\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("This version does not support exporting modules with other module instances.\n\n");\r
- sb.append("Dependencies:\n");\r
- for(String s : e1.getDependencies())\r
- sb.append(" " + s + "\n");\r
- mb.setMessage(sb.toString());\r
- mb.setText("Module contains dependencies.");\r
- mb.open();\r
- return null;\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- \r
- // Do not export if the resource has no name\r
- if(name == null) return null;\r
- \r
- // Find a location (and name) for the exported library using FileDialog\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
- fd.setText("Export Module");\r
- fd.setFileName(name);\r
- String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODULETPATH);\r
- if(path.isEmpty() || !(new File(path).exists()))\r
- path = Platform.getLocation().toOSString();\r
- fd.setFilterPath(path);\r
- String[] filterExt = {"*.sysdynModule"};\r
- fd.setFilterExtensions(filterExt);\r
- fd.setOverwrite(true);\r
- final String selected = fd.open();\r
- if(selected == null) return null;\r
- \r
- // Save location to preference store\r
- Activator.getDefault().getPreferenceStore().setValue(ImportUtilsUI.IMPORTMODULETPATH, (new File(selected)).getParent());\r
- \r
- // Asynchronously create the file using transferable graph\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
-\r
- final Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);\r
- if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
- return;\r
- String name = graph.syncRequest(new PossibleRelatedValue<String>(component, l0.HasName, Bindings.STRING ));\r
- final ArrayList<Pair<Resource, String>> roots = new ArrayList<Pair<Resource, String>>();\r
- roots.add(Pair.make(component, name));\r
-\r
- graph.asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
-\r
- Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
- if (!graph.hasStatement(configuration, l0.PartOf, component)&& \r
- !graph.hasStatement(modulesymbol, l0.PartOf, component)) {\r
- // Make sure that configuration and symbol are included.\r
- // In old versions, they were attached to model, not to module.\r
- Resource previousPartof = graph.getSingleObject(configuration, l0.PartOf);\r
-\r
- graph.deny(configuration, l0.PartOf);\r
- graph.deny(modulesymbol, l0.PartOf);\r
- graph.claim(configuration, l0.PartOf, l0.ConsistsOf, component);\r
- graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, component);\r
-\r
- export(graph, selected, roots, component);\r
-\r
- graph.deny(configuration, l0.PartOf);\r
- graph.deny(modulesymbol, l0.PartOf);\r
- graph.claim(configuration, l0.PartOf, l0.ConsistsOf, previousPartof);\r
- graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, previousPartof);\r
- } else {\r
- // Normal export\r
- export(graph, selected, roots, component);\r
- }\r
- }\r
- });\r
-\r
- }\r
- });\r
-\r
- return null;\r
- }\r
- \r
- /**\r
- * Export module (without dependencies to other modules) and write it to file. \r
- * Disable existing enumeration replacement for during export. \r
- * \r
- * @param graph WriteGraph\r
- * @param path Path for the exported file\r
- * @param roots\r
- * @param component Module\r
- */\r
- private void export(WriteGraph graph, final String path, ArrayList<Pair<Resource, String>> roots, final Resource component) {\r
- \r
- // FIXME: Enumeration replacement handling like this is not suitable.\r
- try {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
-\r
- Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
- ArrayList<Pair<Resource, Resource>> replacements = new ArrayList<Pair<Resource, Resource>>();\r
-\r
- for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
- if(graph.hasStatement(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
- for(Resource replacement : graph.getObjects(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
- replacements.add(new Pair<Resource, Resource>(enumeration, replacement));\r
- }\r
- }\r
- }\r
- \r
- for(Pair<Resource,Resource> replacement : replacements)\r
- graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
- \r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, component);\r
- TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));\r
- try {\r
- TransferableGraphs.writeTransferableGraph(graph, "sysdynModule", 1, s,new File(path));\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- });\r
-\r
- \r
- for(Pair<Resource,Resource> replacement : replacements)\r
- graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
-\r
- } catch (RuntimeBindingConstructionException e) {\r
- e.printStackTrace();\r
-// } catch (IOException e) {\r
-// e.printStackTrace();\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2013 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.sysdyn.ui.handlers.exports;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.MessageBox;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.primitiverequest.PossibleRelatedValue;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
+import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
+import org.simantics.db.request.Read;
+import org.simantics.graph.db.TransferableGraphSource;
+import org.simantics.graph.db.TransferableGraphs;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.datastructures.Pair;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+/**
+ * Exports a selected module
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class ExportModuleHandler extends AbstractHandler {
+
+ /**
+ * Temporary exception. At this phase, the system will not support exporting modules
+ * that depend on other modules.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+ class ContainsDependenciesException extends DatabaseException {
+ private static final long serialVersionUID = -1533706136673146020L;
+
+ private final Collection<String> dependencies;
+
+ ContainsDependenciesException(Collection<String> dependencies) {
+ this.dependencies = dependencies;
+ }
+
+ public Collection<String> getDependencies() {
+ return this.dependencies;
+ }
+
+ }
+
+ public static Object handleStatic(Resource modulesymbol) throws ExecutionException {
+ Shell shell = WorkbenchUtils.getActiveWorkbenchWindowShell();
+ ExportModuleHandler emh = new ExportModuleHandler();
+ return(emh.executeImpl(modulesymbol, shell));
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ final Resource modulesymbol = ResourceAdaptionUtils.toSingleResource(sel);
+ if(modulesymbol == null) return null;
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ return(this.executeImpl(modulesymbol, shell));
+ }
+
+ private Object executeImpl(Resource modulesymbol, Shell shell) {
+
+ String name = null;
+ try {
+ name = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ // Start checking for module dependencies
+ Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);
+ if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))
+ return null;
+
+ Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);
+ if (configuration == null)
+ return null;
+
+ ArrayList<String> dependencies = null;
+ for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {
+ if(dependencies == null)
+ dependencies = new ArrayList<String>();
+ String name = NameUtils.getSafeName(graph, r);
+ String instanceOf = NameUtils.getSafeName(graph, graph.getSingleObject(r, l0.InstanceOf));
+ dependencies.add(name + " : " + instanceOf);
+ }
+ if(dependencies != null && !dependencies.isEmpty())
+ throw new ContainsDependenciesException(dependencies);
+ // End checking for module dependencies. If dependencies were found, an exception was thrown
+
+ String name = graph.getPossibleRelatedValue(component, l0.HasName, Bindings.STRING);
+ return name;
+
+ }
+
+ });
+ } catch (ContainsDependenciesException e1) {
+ MessageBox mb = new MessageBox(shell, SWT.OK);
+ StringBuilder sb = new StringBuilder();
+ sb.append("This version does not support exporting modules with other module instances.\n\n");
+ sb.append("Dependencies:\n");
+ for(String s : e1.getDependencies())
+ sb.append(" " + s + "\n");
+ mb.setMessage(sb.toString());
+ mb.setText("Module contains dependencies.");
+ mb.open();
+ return null;
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+
+ // Do not export if the resource has no name
+ if(name == null) return null;
+
+ // Find a location (and name) for the exported library using FileDialog
+
+ FileDialog fd = new FileDialog(shell, SWT.SAVE);
+ fd.setText("Export Module");
+ fd.setFileName(name);
+ String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODULETPATH);
+ if(path.isEmpty() || !(new File(path).exists()))
+ path = Platform.getLocation().toOSString();
+ fd.setFilterPath(path);
+ String[] filterExt = {"*.sysdynModule"};
+ fd.setFilterExtensions(filterExt);
+ fd.setOverwrite(true);
+ final String selected = fd.open();
+ if(selected == null) return null;
+
+ // Save location to preference store
+ Activator.getDefault().getPreferenceStore().setValue(ImportUtilsUI.IMPORTMODULETPATH, (new File(selected)).getParent());
+
+ // Asynchronously create the file using transferable graph
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+
+ final Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);
+ if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))
+ return;
+ String name = graph.syncRequest(new PossibleRelatedValue<String>(component, l0.HasName, Bindings.STRING ));
+ final ArrayList<Pair<Resource, String>> roots = new ArrayList<Pair<Resource, String>>();
+ roots.add(Pair.make(component, name));
+
+ graph.asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+
+ Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);
+ if (!graph.hasStatement(configuration, l0.PartOf, component)&&
+ !graph.hasStatement(modulesymbol, l0.PartOf, component)) {
+ // Make sure that configuration and symbol are included.
+ // In old versions, they were attached to model, not to module.
+ Resource previousPartof = graph.getSingleObject(configuration, l0.PartOf);
+
+ graph.deny(configuration, l0.PartOf);
+ graph.deny(modulesymbol, l0.PartOf);
+ graph.claim(configuration, l0.PartOf, l0.ConsistsOf, component);
+ graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, component);
+
+ export(graph, selected, roots, component);
+
+ graph.deny(configuration, l0.PartOf);
+ graph.deny(modulesymbol, l0.PartOf);
+ graph.claim(configuration, l0.PartOf, l0.ConsistsOf, previousPartof);
+ graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, previousPartof);
+ } else {
+ // Normal export
+ export(graph, selected, roots, component);
+ }
+ }
+ });
+
+ }
+ });
+
+ return null;
+ }
+
+ /**
+ * Export module (without dependencies to other modules) and write it to file.
+ * Disable existing enumeration replacement for during export.
+ *
+ * @param graph WriteGraph
+ * @param path Path for the exported file
+ * @param roots
+ * @param component Module
+ */
+ private void export(WriteGraph graph, final String path, ArrayList<Pair<Resource, String>> roots, final Resource component) {
+
+ // FIXME: Enumeration replacement handling like this is not suitable.
+ try {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+
+ Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);
+ ArrayList<Pair<Resource, Resource>> replacements = new ArrayList<Pair<Resource, Resource>>();
+
+ for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {
+ if(graph.hasStatement(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {
+ for(Resource replacement : graph.getObjects(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {
+ replacements.add(new Pair<Resource, Resource>(enumeration, replacement));
+ }
+ }
+ }
+
+ for(Pair<Resource,Resource> replacement : replacements)
+ graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, component);
+ TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
+ try {
+ TransferableGraphs.writeTransferableGraph(graph, "sysdynModule", 1, s,new File(path));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ });
+
+
+ for(Pair<Resource,Resource> replacement : replacements)
+ graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);
+
+ } catch (RuntimeBindingConstructionException e) {
+ e.printStackTrace();
+// } catch (IOException e) {
+// e.printStackTrace();
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.game;\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
-import org.simantics.sysdyn.ui.handlers.RunBasicExperiment;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Handler for initializing and reloading game experiments.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ReloadGameExperimentHandler extends RunBasicExperiment {\r
- \r
- private boolean started = false;\r
- private boolean initialized = false;\r
- \r
- \r
- public static final String COMMAND = "org.simantics.sysdyn.ui.reloadGame";\r
- \r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- SysdynGameExperimentBase game = getGameExperiment();\r
- if(game != null)\r
- game.simulate(true);\r
- return null;\r
- }\r
- \r
- /**\r
- * Find currently active game experiment\r
- * @return Currently active game experiment or null if game experiment not active\r
- */\r
- private SysdynGameExperimentBase getGameExperiment() {\r
- // Find active experiment\r
- IProject project = SimanticsUI.peekProject();\r
- if (project == null)\r
- return null;\r
- \r
- IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
-\r
- IExperiment active = manager.getActiveExperiment();\r
- if (!(active instanceof SysdynGameExperimentBase))\r
- return null;\r
- \r
- return (SysdynGameExperimentBase) active;\r
- }\r
- \r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- // Disable button while initializign a model\r
- super.updateElement(element, parameters);\r
- \r
- \r
- // Change tooltip according to the current status\r
- SysdynGameExperimentBase game = getGameExperiment(); \r
-\r
- if(game == null) {\r
- started = false;\r
- initialized = false;\r
- return;\r
- }\r
- \r
- ExperimentState state = game.getState();\r
- \r
- if(state==ExperimentState.INITIALIZING) {\r
- started = false;\r
- initialized = false;\r
- } else if(state==ExperimentState.RUNNING) {\r
- started = true;\r
- initialized = false;\r
- } else if(state==ExperimentState.STOPPED) {\r
- if(started && !initialized) {\r
- initialized = true;\r
- } \r
- }\r
- \r
- \r
- if(initialized) {\r
- element.setTooltip("Reload Game");\r
- } else {\r
- element.setTooltip("Initialize Game");\r
- }\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.handlers.game;
+
+import java.util.Map;
+
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.project.IProject;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;
+import org.simantics.sysdyn.ui.handlers.RunBasicExperiment;
+
+/**
+ * Handler for initializing and reloading game experiments.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ReloadGameExperimentHandler extends RunBasicExperiment {
+
+ private boolean started = false;
+ private boolean initialized = false;
+
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.reloadGame";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ SysdynGameExperimentBase game = getGameExperiment();
+ if(game != null)
+ game.simulate(true);
+ return null;
+ }
+
+ /**
+ * Find currently active game experiment
+ * @return Currently active game experiment or null if game experiment not active
+ */
+ private SysdynGameExperimentBase getGameExperiment() {
+ // Find active experiment
+ IProject project = Simantics.peekProject();
+ if (project == null)
+ return null;
+
+ IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+
+ IExperiment active = manager.getActiveExperiment();
+ if (!(active instanceof SysdynGameExperimentBase))
+ return null;
+
+ return (SysdynGameExperimentBase) active;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ // Disable button while initializign a model
+ super.updateElement(element, parameters);
+
+
+ // Change tooltip according to the current status
+ SysdynGameExperimentBase game = getGameExperiment();
+
+ if(game == null) {
+ started = false;
+ initialized = false;
+ return;
+ }
+
+ ExperimentState state = game.getState();
+
+ if(state==ExperimentState.INITIALIZING) {
+ started = false;
+ initialized = false;
+ } else if(state==ExperimentState.RUNNING) {
+ started = true;
+ initialized = false;
+ } else if(state==ExperimentState.STOPPED) {
+ if(started && !initialized) {
+ initialized = true;
+ }
+ }
+
+
+ if(initialized) {
+ element.setTooltip("Reload Game");
+ } else {
+ element.setTooltip("Initialize Game");
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.game;\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Handler for stepping game simulations\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class StepHandler extends AbstractHandler implements IElementUpdater {\r
- \r
- public static String COMMAND = "org.simantics.sysdyn.ui.step";\r
- \r
- private boolean started = false;\r
- private boolean initialized = false;\r
- private boolean running = false; \r
- \r
- private SysdynGameExperimentBase getGameExperiment() {\r
- // Find active experiment\r
- IProject project = SimanticsUI.peekProject();\r
- if (project == null)\r
- return null;\r
- \r
- IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
-\r
- IExperiment active = manager.getActiveExperiment();\r
- if (!(active instanceof SysdynGameExperimentBase))\r
- return null;\r
- \r
- return (SysdynGameExperimentBase) active;\r
- }\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- HandlerUtils.saveBeforeExperimentRun(event);\r
- \r
- SysdynGameExperimentBase game = getGameExperiment();\r
- if(game != null)\r
- game.simulateDuration(game.getStepDuration());\r
- return null;\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- \r
- // Disable button when model has not been initialized and change tooltip accordingly\r
- SysdynGameExperimentBase game = getGameExperiment(); \r
-\r
- if(game == null) {\r
- started = false;\r
- initialized = false;\r
- return;\r
- }\r
- \r
- ExperimentState state = game.getState();\r
- \r
- if(state==ExperimentState.INITIALIZING) {\r
- started = false;\r
- initialized = false;\r
- running = false;\r
- } else if(state==ExperimentState.RUNNING) {\r
- started = true;\r
- initialized = initialized == true ? true : false;\r
- running = true;\r
- } else if(state==ExperimentState.STOPPED) {\r
- if(started && !initialized) {\r
- initialized = true;\r
- } \r
- running = false;\r
- }\r
- \r
- if(initialized) {\r
- if(!running)\r
- this.setBaseEnabled(true);\r
- else\r
- this.setBaseEnabled(false);\r
- element.setTooltip("Step");\r
- } else {\r
- this.setBaseEnabled(false);\r
- element.setTooltip("Initialize Game First");\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.handlers.game;
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.project.IProject;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+/**
+ * Handler for stepping game simulations
+ * @author Teemu Lempinen
+ *
+ */
+public class StepHandler extends AbstractHandler implements IElementUpdater {
+
+ public static String COMMAND = "org.simantics.sysdyn.ui.step";
+
+ private boolean started = false;
+ private boolean initialized = false;
+ private boolean running = false;
+
+ private SysdynGameExperimentBase getGameExperiment() {
+ // Find active experiment
+ IProject project = Simantics.peekProject();
+ if (project == null)
+ return null;
+
+ IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+
+ IExperiment active = manager.getActiveExperiment();
+ if (!(active instanceof SysdynGameExperimentBase))
+ return null;
+
+ return (SysdynGameExperimentBase) active;
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ SysdynGameExperimentBase game = getGameExperiment();
+ if(game != null)
+ game.simulateDuration(game.getStepDuration());
+ return null;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+
+ // Disable button when model has not been initialized and change tooltip accordingly
+ SysdynGameExperimentBase game = getGameExperiment();
+
+ if(game == null) {
+ started = false;
+ initialized = false;
+ return;
+ }
+
+ ExperimentState state = game.getState();
+
+ if(state==ExperimentState.INITIALIZING) {
+ started = false;
+ initialized = false;
+ running = false;
+ } else if(state==ExperimentState.RUNNING) {
+ started = true;
+ initialized = initialized == true ? true : false;
+ running = true;
+ } else if(state==ExperimentState.STOPPED) {
+ if(started && !initialized) {
+ initialized = true;
+ }
+ running = false;
+ }
+
+ if(initialized) {
+ if(!running)
+ this.setBaseEnabled(true);
+ else
+ this.setBaseEnabled(false);
+ element.setTooltip("Step");
+ } else {
+ this.setBaseEnabled(false);
+ element.setTooltip("Initialize Game First");
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.imports;\r
-\r
-import java.io.File;\r
-import java.io.FileInputStream;\r
-import java.io.IOException;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-/**\r
- * Imports external functions to SysdynModelicaFunctions using FileDialog.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ImportExternalFunctionFilesHandler extends AbstractHandler {\r
-\r
- public static final String[] C_EXTENSIONS = {"*.c","*.h","*.a","*.o"};\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- Pair<String, String[]> selected = importFiles(shell, "Import...", C_EXTENSIONS);\r
- if(selected.second == null || selected.second.length < 1) return null;\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- // TODO: include files to database\r
- }\r
- });\r
- \r
- return null;\r
- }\r
- \r
- /**\r
- * Opens a {@link FileDialog} to select the imported files.\r
- * \r
- * @param shell SWT Shell\r
- * @param text Header text for the FileDialog\r
- * @param filter Filters for the FileDialog\r
- * @return File names and paths for the files to be imported\r
- */\r
- public static Pair<String, String[]> importFiles(Shell shell, String text, String[] filter) {\r
- FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
- fd.setText(text);\r
- fd.setFilterPath(Platform.getLocation().toOSString());\r
- fd.setFilterExtensions(filter);\r
- fd.open();\r
- return new Pair<String, String[]>(fd.getFilterPath(), fd.getFileNames());\r
- }\r
- \r
- \r
- /**\r
- * Saves the given files as byte arrays to a function\r
- * \r
- * @param graph WriteGraph\r
- * @param function Function where the files are to be added\r
- * @param files Files to be added\r
- * @throws DatabaseException\r
- */\r
- public static void addFilesToFunction(WriteGraph graph, Resource function, Pair<String, String[]> files) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- if(!graph.isInstanceOf(function, sr.SysdynModelicaFunction))\r
- return;\r
-\r
- for(String filename : files.second) {\r
- File file = new File(files.first, filename);\r
- \r
- String name = file.getName();\r
- \r
- Resource externalFile = GraphUtils.create2(graph, \r
- sr.ExternalFunctionFile,\r
- l0.PartOf, function,\r
- l0.HasName, name);\r
- \r
- try {\r
- byte[] fileBArray = new byte[(int)file.length()];\r
- FileInputStream fis = new FileInputStream(file);\r
- fis.read(fileBArray);\r
- graph.claimLiteral(externalFile, sr.ExternalFunctionFile_externalFile, fileBArray, Bindings.BYTE_ARRAY);\r
- fis.close();\r
- } catch (IOException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- }\r
- \r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.imports;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.datastructures.Pair;
+
+/**
+ * Imports external functions to SysdynModelicaFunctions using FileDialog.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ImportExternalFunctionFilesHandler extends AbstractHandler {
+
+ public static final String[] C_EXTENSIONS = {"*.c","*.h","*.a","*.o"};
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ Pair<String, String[]> selected = importFiles(shell, "Import...", C_EXTENSIONS);
+ if(selected.second == null || selected.second.length < 1) return null;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ // TODO: include files to database
+ }
+ });
+
+ return null;
+ }
+
+ /**
+ * Opens a {@link FileDialog} to select the imported files.
+ *
+ * @param shell SWT Shell
+ * @param text Header text for the FileDialog
+ * @param filter Filters for the FileDialog
+ * @return File names and paths for the files to be imported
+ */
+ public static Pair<String, String[]> importFiles(Shell shell, String text, String[] filter) {
+ FileDialog fd = new FileDialog(shell, SWT.OPEN);
+ fd.setText(text);
+ fd.setFilterPath(Platform.getLocation().toOSString());
+ fd.setFilterExtensions(filter);
+ fd.open();
+ return new Pair<String, String[]>(fd.getFilterPath(), fd.getFileNames());
+ }
+
+
+ /**
+ * Saves the given files as byte arrays to a function
+ *
+ * @param graph WriteGraph
+ * @param function Function where the files are to be added
+ * @param files Files to be added
+ * @throws DatabaseException
+ */
+ public static void addFilesToFunction(WriteGraph graph, Resource function, Pair<String, String[]> files) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ if(!graph.isInstanceOf(function, sr.SysdynModelicaFunction))
+ return;
+
+ for(String filename : files.second) {
+ File file = new File(files.first, filename);
+
+ String name = file.getName();
+
+ Resource externalFile = GraphUtils.create2(graph,
+ sr.ExternalFunctionFile,
+ l0.PartOf, function,
+ l0.HasName, name);
+
+ try {
+ byte[] fileBArray = new byte[(int)file.length()];
+ FileInputStream fis = new FileInputStream(file);
+ fis.read(fileBArray);
+ graph.claimLiteral(externalFile, sr.ExternalFunctionFile_externalFile, fileBArray, Bindings.BYTE_ARRAY);
+ fis.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.imports;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.core.runtime.jobs.Job;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.DatabaseJob;\r
-import org.simantics.db.Resource;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Imports an exported function library (or shared function library) transferable graph. \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ImportFunctionLibrary extends AbstractHandler {\r
- \r
- /**\r
- * Called from a functions folder node\r
- */\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- Resource r = ResourceAdaptionUtils.toSingleResource(sel);\r
- if(r == null) {\r
- FunctionsFolder mn = AdaptionUtils.adaptToSingle(sel, FunctionsFolder.class);\r
- r = mn.data;\r
- }\r
- if(r == null) return null;\r
- \r
- final Resource functionLibrary = r;\r
- \r
- \r
- // Get a transferable graph file\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
- fd.setText("Import Function Library");\r
- \r
- String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH);\r
- if(path.isEmpty() || !(new File(path).exists()))\r
- path = Platform.getLocation().toOSString();\r
- fd.setFilterPath(path);\r
- String[] filterExt = {"*.sysdynFunctions; *.tg", "*.*"};\r
- fd.setFilterExtensions(filterExt);\r
- final String selected = fd.open();\r
- if(selected == null) return null;\r
-\r
- Job job = new DatabaseJob("Import function") {\r
-\r
- @Override\r
- protected IStatus run(IProgressMonitor monitor) {\r
- IStatus status = ImportUtilsUI.importFunctionLibrary(functionLibrary, selected, monitor);\r
- return status;\r
- }\r
- };\r
-\r
- job.setUser(true);\r
- job.schedule();\r
-\r
- return null;\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.imports;
+
+import java.io.File;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.DatabaseJob;
+import org.simantics.db.Resource;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.AdaptionUtils;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+/**
+ * Imports an exported function library (or shared function library) transferable graph.
+ * @author Teemu Lempinen
+ *
+ */
+public class ImportFunctionLibrary extends AbstractHandler {
+
+ /**
+ * Static way of executing the module import
+ * @param event
+ * @return
+ * @throws ExecutionException
+ */
+ public static Object handleStatic(Resource functionLibrary) throws ExecutionException {
+ Shell shell = WorkbenchUtils.getActiveWorkbenchWindowShell();
+ return(executeImpl(functionLibrary, shell));
+ }
+
+ /**
+ * Called from a functions folder node
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ Resource r = ResourceAdaptionUtils.toSingleResource(sel);
+ if(r == null) {
+ FunctionsFolder mn = AdaptionUtils.adaptToSingle(sel, FunctionsFolder.class);
+ r = mn.data;
+ }
+ if(r == null) return null;
+
+ final Resource functionLibrary = r;
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ return(executeImpl(functionLibrary, shell));
+ }
+
+ private static Object executeImpl(Resource functionLibrary, Shell shell) {
+ FileDialog fd = new FileDialog(shell, SWT.OPEN);
+ fd.setText("Import Function Library");
+
+ String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTFUNCTIONLIBRARYPATH);
+ if(path.isEmpty() || !(new File(path).exists()))
+ path = Platform.getLocation().toOSString();
+ fd.setFilterPath(path);
+ String[] filterExt = {"*.sysdynFunctions; *.tg", "*.*"};
+ fd.setFilterExtensions(filterExt);
+ final String selected = fd.open();
+ if(selected == null) return null;
+
+ Job job = new DatabaseJob("Import function") {
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IStatus status = ImportUtilsUI.importFunctionLibrary(functionLibrary, selected, monitor);
+ return status;
+ }
+ };
+
+ job.setUser(true);
+ job.schedule();
+
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.imports;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.modelImport.MdlParser;\r
-import org.simantics.sysdyn.modelImport.model.Model;\r
-import org.simantics.sysdyn.modelImport.model.WriteContext;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-/**\r
- * Class for importing Vensim models (.mdl) to Simantics SysDyn using MdlParser \r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ImportMdlHandler extends AbstractHandler {\r
-\r
- public static String IMPORTMDLTPATH = "IMPORT_MDL_PATH";\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- final Resource project = SimanticsUI.getProject().get();\r
- if(project == null) return null;\r
-\r
- // Get the .mdl file\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
- fd.setText("Import .mdl");\r
- String path = Activator.getDefault().getPreferenceStore().getString(IMPORTMDLTPATH);\r
- if(path.isEmpty() || !(new File(path).exists()))\r
- path = Platform.getLocation().toOSString();\r
- fd.setFilterPath(path);\r
- String[] filterExt = {"*.mdl"};\r
- fd.setFilterExtensions(filterExt);\r
- String selected = fd.open();\r
- if(selected == null) return null;\r
-\r
- File file = new File(selected);\r
- if(!file.isFile()) return null;\r
- \r
- Activator.getDefault().getPreferenceStore().setValue(IMPORTMDLTPATH, (new File(selected)).getParent());\r
- \r
- // Convert Vensim model to Simantics SysDyn format using MdlParser\r
- final Model model;\r
- try {\r
- model = new MdlParser().parse(file);\r
- }\r
- catch (Exception e) {\r
- ExceptionUtils.logAndShowError(e);\r
- return null;\r
- }\r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- model.write(graph, project, new WriteContext());\r
- }\r
- });\r
- \r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.imports;
+
+import java.io.File;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.modelImport.MdlParser;
+import org.simantics.sysdyn.modelImport.model.Model;
+import org.simantics.sysdyn.modelImport.model.WriteContext;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.utils.ui.ExceptionUtils;
+
+/**
+ * Class for importing Vensim models (.mdl) to Simantics SysDyn using MdlParser
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ImportMdlHandler extends AbstractHandler {
+
+ public static String IMPORTMDLTPATH = "IMPORT_MDL_PATH";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ final Resource project = Simantics.getProject().get();
+ if(project == null) return null;
+
+ // Get the .mdl file
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ FileDialog fd = new FileDialog(shell, SWT.OPEN);
+ fd.setText("Import .mdl");
+ String path = Activator.getDefault().getPreferenceStore().getString(IMPORTMDLTPATH);
+ if(path.isEmpty() || !(new File(path).exists()))
+ path = Platform.getLocation().toOSString();
+ fd.setFilterPath(path);
+ String[] filterExt = {"*.mdl"};
+ fd.setFilterExtensions(filterExt);
+ String selected = fd.open();
+ if(selected == null) return null;
+
+ File file = new File(selected);
+ if(!file.isFile()) return null;
+
+ Activator.getDefault().getPreferenceStore().setValue(IMPORTMDLTPATH, (new File(selected)).getParent());
+
+ // Convert Vensim model to Simantics SysDyn format using MdlParser
+ final Model model;
+ try {
+ model = new MdlParser().parse(file);
+ }
+ catch (Exception e) {
+ ExceptionUtils.logAndShowError(e);
+ return null;
+ }
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ model.write(graph, project, new WriteContext());
+ }
+ });
+
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.imports;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.core.runtime.jobs.Job;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.DatabaseJob;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.db.Resource;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Imports modules from exported transferable graph files.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ImportModuleHandler extends AbstractHandler {\r
-\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
-\r
- @SuppressWarnings("unchecked")\r
- AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource model = node.data;\r
-\r
- // Get imported transferable graph file using FileDialog\r
- Shell shell = HandlerUtil.getActiveShellChecked(event);\r
- FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
- fd.setText("Import Module");\r
-\r
- String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODULETPATH);\r
- if(path.isEmpty() || !(new File(path).exists()))\r
- path = Platform.getLocation().toOSString();\r
- fd.setFilterPath(path);\r
- String[] filterExt = {"*.sysdynModule; *.tg", "*.*"};\r
- fd.setFilterExtensions(filterExt);\r
- final String selected = fd.open();\r
- if(selected == null) return null;\r
- \r
- Job job = new DatabaseJob("Import module") {\r
-\r
- @Override\r
- protected IStatus run(IProgressMonitor monitor) {\r
- IStatus status = ImportUtilsUI.importModuleFile(model, selected, monitor);\r
- return status;\r
- }\r
- };\r
- job.setUser(true);\r
- job.schedule();\r
-\r
- return null;\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.imports;
+
+import java.io.File;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.DatabaseJob;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.db.Resource;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
+import org.simantics.utils.ui.AdaptionUtils;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+/**
+ * Imports modules from exported transferable graph files.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ImportModuleHandler extends AbstractHandler {
+
+
+ /**
+ * Static way of executing the module import
+ * @param event
+ * @return
+ * @throws ExecutionException
+ */
+ public static Object handleStatic(Resource model) throws ExecutionException {
+ Shell shell = WorkbenchUtils.getActiveWorkbenchWindowShell();
+ return(executeImpl(model, shell));
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ @SuppressWarnings("unchecked")
+ AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);
+ if (node == null)
+ return null;
+
+ final Resource model = node.data;
+
+ // Get imported transferable graph file using FileDialog
+ Shell shell = HandlerUtil.getActiveShellChecked(event);
+ return(executeImpl(model, shell));
+ }
+
+ private static Object executeImpl(Resource model, Shell shell) {
+ FileDialog fd = new FileDialog(shell, SWT.OPEN);
+ fd.setText("Import Module");
+
+ String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODULETPATH);
+ if(path.isEmpty() || !(new File(path).exists()))
+ path = Platform.getLocation().toOSString();
+ fd.setFilterPath(path);
+ String[] filterExt = {"*.sysdynModule; *.tg", "*.*"};
+ fd.setFilterExtensions(filterExt);
+ final String selected = fd.open();
+ if(selected == null) return null;
+
+ Job job = new DatabaseJob("Import module") {
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ IStatus status = ImportUtilsUI.importModuleFile(model, selected, monitor);
+ return status;
+ }
+ };
+ job.setUser(true);
+ job.schedule();
+
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.util.Collections;\r
-import java.util.UUID;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Handler for creating a new Bar Chart\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewBarChartHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
-\r
- ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource model = node.data; \r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
- G2DResource g2d = G2DResource.getInstance(g);\r
-\r
- String label = NameUtils.findFreshLabel(g, "Bar Chart", model);\r
- \r
- Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
- l0.HasName, "BarChart" + UUID.randomUUID().toString(),\r
- l0.HasLabel, label,\r
- l0.PartOf, model,\r
- jfree.Chart_visibleBorder, true,\r
- jfree.Chart_borderWidth, 3,\r
- jfree.Chart_visibleLegend, false\r
- );\r
- \r
- g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
-\r
- GraphUtils.create2(g, jfree.TextTitle,\r
- l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Bar Chart Title",\r
- jfree.Title_position, jfree.Top,\r
- l0.PartOf, jfreechart);\r
-\r
- Resource domainAxis = GraphUtils.create2(g, jfree.CategoryAxis,\r
- l0.HasName, "CategoryAxis" + UUID.randomUUID().toString());\r
- \r
- Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString());\r
-\r
- Resource renderer = GraphUtils.create2(g, jfree.BarRenderer);\r
- \r
- Resource dataset = GraphUtils.create2(g, jfree.CategoryDataset,\r
- l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
- jfree.Dataset_mapToDomainAxis, domainAxis,\r
- jfree.Dataset_mapToRangeAxis, rangeAxis,\r
- jfree.Dataset_seriesList, ListUtils.create(g, Collections.<Resource>emptyList()),\r
- jfree.Dataset_renderer, renderer);\r
-\r
- GraphUtils.create2(g, jfree.CategoryPlot,\r
- l0.HasName, "Category plot" + UUID.randomUUID().toString(),\r
- l0.PartOf, jfreechart,\r
- jfree.Plot_domainAxis, domainAxis,\r
- jfree.Plot_rangeAxis, rangeAxis,\r
- jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),\r
- l0.ConsistsOf, dataset,\r
- l0.ConsistsOf, domainAxis,\r
- l0.ConsistsOf, rangeAxis);\r
- Layer0Utils.addCommentMetadata(g, "Created new Bar Chart " + label + " " + jfreechart);\r
- }\r
-\r
- });\r
- \r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import java.util.Collections;
+import java.util.UUID;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Handler for creating a new Bar Chart
+ * @author Teemu Lempinen
+ *
+ */
+public class NewBarChartHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);
+ if (node == null)
+ return null;
+
+ final Resource model = node.data;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(g);
+ G2DResource g2d = G2DResource.getInstance(g);
+
+ String label = NameUtils.findFreshLabel(g, "Bar Chart", model);
+
+ Resource jfreechart = GraphUtils.create2(g, jfree.Chart,
+ l0.HasName, "BarChart" + UUID.randomUUID().toString(),
+ l0.HasLabel, label,
+ l0.PartOf, model,
+ jfree.Chart_visibleBorder, true,
+ jfree.Chart_borderWidth, 3,
+ jfree.Chart_visibleLegend, false
+ );
+
+ g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});
+
+ GraphUtils.create2(g, jfree.TextTitle,
+ l0.HasName, "TextTitle" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Bar Chart Title",
+ jfree.Title_position, jfree.Top,
+ l0.PartOf, jfreechart);
+
+ Resource domainAxis = GraphUtils.create2(g, jfree.CategoryAxis,
+ l0.HasName, "CategoryAxis" + UUID.randomUUID().toString());
+
+ Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString());
+
+ Resource renderer = GraphUtils.create2(g, jfree.BarRenderer);
+
+ Resource dataset = GraphUtils.create2(g, jfree.CategoryDataset,
+ l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),
+ jfree.Dataset_mapToDomainAxis, domainAxis,
+ jfree.Dataset_mapToRangeAxis, rangeAxis,
+ jfree.Dataset_seriesList, ListUtils.create(g, Collections.<Resource>emptyList()),
+ jfree.Dataset_renderer, renderer);
+
+ GraphUtils.create2(g, jfree.CategoryPlot,
+ l0.HasName, "Category plot" + UUID.randomUUID().toString(),
+ l0.PartOf, jfreechart,
+ jfree.Plot_domainAxis, domainAxis,
+ jfree.Plot_rangeAxis, rangeAxis,
+ jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),
+ l0.ConsistsOf, dataset,
+ l0.ConsistsOf, domainAxis,
+ l0.ConsistsOf, rangeAxis);
+ Layer0Utils.addCommentMetadata(g, "Created new Bar Chart " + label + " " + jfreechart);
+ }
+
+ });
+
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Creates a new Enumeration node to a configuration or module\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewEnumerationNodeHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- final Resource resource = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
- \r
- // Find the actual configuration. Possible cases for resource are sr.Configuration, sr.ModuleSymbol or sr.Module.\r
- Resource configuration = null;\r
- if(g.isInstanceOf(resource, sr.Configuration)) {\r
- configuration = resource;\r
- } else if(g.isInheritedFrom(resource, sr.ModuleSymbol)) {\r
- Resource module = g.getPossibleObject(resource,ModelingResources.getInstance(g).SymbolToComponentType);\r
- configuration = g.getPossibleObject(module, StructuralResource2.getInstance(g).IsDefinedBy);\r
- } else {\r
- Resource instanceOf = g.getSingleObject(resource, l0.InstanceOf);\r
- if(g.isInheritedFrom(instanceOf, sr.Module)) {\r
- configuration = g.getPossibleObject(instanceOf, StructuralResource2.getInstance(g).IsDefinedBy);\r
- } else {\r
- return;\r
- }\r
- }\r
-\r
- // Create the enumeartion\r
- \r
- String name = NameUtils.findFreshName(g, "Enum", configuration, l0.ConsistsOf, "%s%d");\r
- \r
- GraphUtils.create2(g, \r
- sr.Enumeration,\r
- l0.HasName, name,\r
- sr.Enumeration_enumerationIndexList, ListUtils.create(g, new ArrayList<Resource>()),\r
- l0.PartOf, configuration);\r
- Layer0Utils.addCommentMetadata(g, "Created new Enumeration " + name + " to " + g.getRelatedValue2(configuration, l0.HasLabel, Bindings.STRING));\r
- }\r
- });\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import java.util.ArrayList;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Creates a new Enumeration node to a configuration or module
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewEnumerationNodeHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ final Resource resource = AdaptionUtils.adaptToSingle(sel, Resource.class);
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+
+ // Find the actual configuration. Possible cases for resource are sr.Configuration, sr.ModuleSymbol or sr.Module.
+ Resource configuration = null;
+ if(g.isInstanceOf(resource, sr.Configuration)) {
+ configuration = resource;
+ } else if(g.isInheritedFrom(resource, sr.ModuleSymbol)) {
+ Resource module = g.getPossibleObject(resource,ModelingResources.getInstance(g).SymbolToComponentType);
+ configuration = g.getPossibleObject(module, StructuralResource2.getInstance(g).IsDefinedBy);
+ } else {
+ Resource instanceOf = g.getSingleObject(resource, l0.InstanceOf);
+ if(g.isInheritedFrom(instanceOf, sr.Module)) {
+ configuration = g.getPossibleObject(instanceOf, StructuralResource2.getInstance(g).IsDefinedBy);
+ } else {
+ return;
+ }
+ }
+
+ // Create the enumeartion
+
+ String name = NameUtils.findFreshName(g, "Enum", configuration, l0.ConsistsOf, "%s%d");
+
+ GraphUtils.create2(g,
+ sr.Enumeration,
+ l0.HasName, name,
+ sr.Enumeration_enumerationIndexList, ListUtils.create(g, new ArrayList<Resource>()),
+ l0.PartOf, configuration);
+ Layer0Utils.addCommentMetadata(g, "Created new Enumeration " + name + " to " + g.getRelatedValue2(configuration, l0.HasLabel, Bindings.STRING));
+ }
+ });
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.util.UUID;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Creates a new normal SysDyn experiment\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewExperimentNodeHandler extends AbstractHandler {\r
-\r
- /**\r
- * Assumes that it is called from a node that has a SysDyn model as its resource.\r
- */\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- ExperimentsFolder node = AdaptionUtils.adaptToSingle(sel, ExperimentsFolder.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource model = node.data;\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- String label = NameUtils.findFreshName(g, getNameSuggestion(), model, l0.ConsistsOf, l0.HasLabel, "%s%d");\r
- Resource experiment = GraphUtils.create2(g, getExperimentType(g),\r
- l0.HasName, UUID.randomUUID().toString(),\r
- l0.HasLabel, label,\r
- l0.PartOf, model);\r
- configureExperiment(g, experiment);\r
- Layer0Utils.addCommentMetadata(g, "Created new experiment " + label + " " + experiment.toString());\r
- }\r
- });\r
- return null;\r
- }\r
- \r
- /**\r
- * Override to do experiment-specific alterations\r
- */\r
- protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
- \r
- }\r
- \r
- /**\r
- * Get the type of this experiment.\r
- * \r
- * @param g ReadGraph\r
- * @return The type resource of this experiment\r
- */\r
- protected Resource getExperimentType(ReadGraph g) {\r
- return SysdynResource.getInstance(g).BasicExperiment;\r
- }\r
- \r
- /**\r
- * Returns the suggested name for this experiment.\r
- * If the name has already been taken, appropriate prefix needs to be added. \r
- * \r
- * @return Suggested name for this experiment. \r
- */\r
- protected String getNameSuggestion() {\r
- return "Experiment";\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import java.util.UUID;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+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.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.browser.nodes.ExperimentsFolder;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Creates a new normal SysDyn experiment
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewExperimentNodeHandler extends AbstractHandler {
+
+ /**
+ * Assumes that it is called from a node that has a SysDyn model as its resource.
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ ExperimentsFolder node = AdaptionUtils.adaptToSingle(sel, ExperimentsFolder.class);
+ if (node == null)
+ return null;
+
+ final Resource model = node.data;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ String label = NameUtils.findFreshName(g, getNameSuggestion(), model, l0.ConsistsOf, l0.HasLabel, "%s%d");
+ Resource experiment = GraphUtils.create2(g, getExperimentType(g),
+ l0.HasName, UUID.randomUUID().toString(),
+ l0.HasLabel, label,
+ l0.PartOf, model);
+ configureExperiment(g, experiment);
+ Layer0Utils.addCommentMetadata(g, "Created new experiment " + label + " " + experiment.toString());
+ }
+ });
+ return null;
+ }
+
+ /**
+ * Override to do experiment-specific alterations
+ */
+ public void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+
+ }
+
+ /**
+ * Get the type of this experiment.
+ *
+ * @param g ReadGraph
+ * @return The type resource of this experiment
+ */
+ public Resource getExperimentType(ReadGraph g) {
+ return SysdynResource.getInstance(g).BasicExperiment;
+ }
+
+ /**
+ * Returns the suggested name for this experiment.
+ * If the name has already been taken, appropriate prefix needs to be added.
+ *
+ * @return Suggested name for this experiment.
+ */
+ public String getNameSuggestion() {
+ return "Experiment";
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Creates a new function to a SysdynModel or Library.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewFunctionHandler extends AbstractHandler {\r
-\r
- /**\r
- * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource\r
- */\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- @SuppressWarnings("unchecked")\r
- AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource data = node.data;\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
-\r
- // Library can be either SysdynModel or L0.Library. \r
- Resource library = null;\r
- if(g.isInstanceOf(data, sr.SysdynModel) || g.isInstanceOf(data, l0.Library))\r
- library = data;\r
- else if (g.isInstanceOf(data, sr.SysdynModelicaFunction))\r
- library = g.getPossibleObject(data, l0.PartOf);\r
- \r
- if(library == null)\r
- return;\r
- \r
- \r
- String name = NameUtils.findFreshName(g, "Function", library, l0.ConsistsOf, "%s%d");\r
-\r
- Resource func = GraphUtils.create2(g, sr.SysdynModelicaFunction,\r
- l0.HasName, name,\r
- l0.HasDescription, "",\r
- sr.SysdynModelicaFunction_modelicaFunctionCode, "",\r
- l0.PartOf, library);\r
- \r
- Layer0Utils.addCommentMetadata(g, "Created new Function " + name + " " + func.toString());\r
- }\r
- });\r
- \r
- return null;\r
- }\r
-\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Creates a new function to a SysdynModel or Library.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewFunctionHandler extends AbstractHandler {
+
+ /**
+ * Assumes to be called from a node with SysdynModel, Library or SysdynModelicaFunction as its resource
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ @SuppressWarnings("unchecked")
+ AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);
+ if (node == null)
+ return null;
+
+ final Resource data = node.data;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ SysdynResource sr = SysdynResource.getInstance(g);
+
+ // Library can be either SysdynModel or L0.Library.
+ Resource library = null;
+ if(g.isInstanceOf(data, sr.SysdynModel) || g.isInstanceOf(data, l0.Library))
+ library = data;
+ else if (g.isInstanceOf(data, sr.SysdynModelicaFunction))
+ library = g.getPossibleObject(data, l0.PartOf);
+
+ if(library == null)
+ return;
+
+
+ String name = NameUtils.findFreshName(g, "Function", library, l0.ConsistsOf, "%s%d");
+
+ Resource func = GraphUtils.create2(g, sr.SysdynModelicaFunction,
+ l0.HasName, name,
+ l0.HasDescription, "",
+ sr.SysdynModelicaFunction_modelicaFunctionCode, "",
+ l0.PartOf, library);
+
+ Layer0Utils.addCommentMetadata(g, "Created new Function " + name + " " + func.toString());
+ }
+ });
+
+ return null;
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ResourceNotFoundException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Creates a new function library to a model or other library.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewFunctionLibraryHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- @SuppressWarnings("unchecked")\r
- AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);\r
- if (node == null)\r
- return null;\r
-\r
- createLibrary(node.data, false);\r
- return null;\r
- }\r
- \r
- /**\r
- * Create function library. Shared libraries are created to root, local libraries to the model. \r
- * Shared libraries can be used in other models in the project.\r
- * \r
- * @param model The initial location of the command\r
- * @param shared Shared libraries are created to root, local libraries to the model.\r
- */\r
- protected void createLibrary(final Resource model, final boolean shared) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
-\r
- if(!(g.isInstanceOf(model, sr.SysdynModel) ||\r
- g.isInstanceOf(model, sr.SysdynModelicaFunctionLibrary) ||\r
- g.isInstanceOf(model, sr.SharedFunctionOntology)))\r
- return;\r
-\r
- Resource root = model;\r
-\r
- String name = "FunctionLibrary";\r
- Resource libraryType = sr.SysdynModelicaFunctionLibrary;\r
- \r
- if(shared) {\r
- \r
- try {\r
- root = g.getResource("http://SharedOntologies");\r
- } catch (ResourceNotFoundException e) {\r
- root = g.getResource("http:/");\r
- root = GraphUtils.create2(g, l0.Library, \r
- l0.HasName, "SharedOntologies",\r
- l0.PartOf, root);\r
- }\r
- \r
- name = "Shared" + name;\r
- libraryType = sr.SharedFunctionOntology;\r
- }\r
-\r
- name = NameUtils.findFreshName(g, name, root, l0.ConsistsOf, "%s%d");\r
- \r
- Resource functionLibrary = GraphUtils.create2(g, libraryType,\r
- l0.HasName, name,\r
- l0.HasDescription, "",\r
- l0.PartOf, root);\r
- \r
- if(shared)\r
- g.claim(model, l0.IsLinkedTo, functionLibrary);\r
- \r
- Layer0Utils.addCommentMetadata(g, "Created new Function Library " + name + " " + functionLibrary.toString());\r
- }\r
- });\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.ResourceNotFoundException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Creates a new function library to a model or other library.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewFunctionLibraryHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ @SuppressWarnings("unchecked")
+ AbstractNode<Resource> node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class);
+ if (node == null)
+ return null;
+
+ createLibrary(node.data, false);
+ return null;
+ }
+
+ /**
+ * Create function library. Shared libraries are created to root, local libraries to the model.
+ * Shared libraries can be used in other models in the project.
+ *
+ * @param model The initial location of the command
+ * @param shared Shared libraries are created to root, local libraries to the model.
+ */
+ protected void createLibrary(final Resource model, final boolean shared) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ SysdynResource sr = SysdynResource.getInstance(g);
+
+ if(!(g.isInstanceOf(model, sr.SysdynModel) ||
+ g.isInstanceOf(model, sr.SysdynModelicaFunctionLibrary) ||
+ g.isInstanceOf(model, sr.SharedFunctionOntology)))
+ return;
+
+ Resource root = model;
+
+ String name = "FunctionLibrary";
+ Resource libraryType = sr.SysdynModelicaFunctionLibrary;
+
+ if(shared) {
+
+ try {
+ root = g.getResource("http://SharedOntologies");
+ } catch (ResourceNotFoundException e) {
+ root = g.getResource("http:/");
+ root = GraphUtils.create2(g, l0.Library,
+ l0.HasName, "SharedOntologies",
+ l0.PartOf, root);
+ }
+
+ name = "Shared" + name;
+ libraryType = sr.SharedFunctionOntology;
+ }
+
+ name = NameUtils.findFreshName(g, name, root, l0.ConsistsOf, "%s%d");
+
+ Resource functionLibrary = GraphUtils.create2(g, libraryType,
+ l0.HasName, name,
+ l0.HasDescription, "",
+ l0.PartOf, root);
+
+ if(shared)
+ g.claim(model, l0.IsLinkedTo, functionLibrary);
+
+ Layer0Utils.addCommentMetadata(g, "Created new Function Library " + name + " " + functionLibrary.toString());
+ }
+ });
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
-\r
-/**\r
- * Handler for creating a new Game Experiment\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewGameExperimentNodeHandler extends NewExperimentNodeHandler {\r
-\r
- protected Resource getExperimentType(ReadGraph g) {\r
- return SysdynResource.getInstance(g).GameExperiment;\r
- }\r
- \r
- /**\r
- * Override to do experiment-specific alterations\r
- */\r
- protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- graph.claimLiteral(experiment, sr.GameExperiment_stepDuration, SysdynGameExperimentBase.DEFAULT_STEP_DURATION);\r
- graph.claimLiteral(experiment, sr.GameExperiment_stepLength, SysdynGameExperimentBase.DEFAULT_STEP_LENGTH);\r
- }\r
-\r
- protected String getNameSuggestion() {\r
- return "Game Experiment";\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.handlers.newComponents;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;
+
+/**
+ * Handler for creating a new Game Experiment
+ * @author Teemu Lempinen
+ *
+ */
+public class NewGameExperimentNodeHandler extends NewExperimentNodeHandler {
+
+ public Resource getExperimentType(ReadGraph g) {
+ return SysdynResource.getInstance(g).GameExperiment;
+ }
+
+ /**
+ * Override to do experiment-specific alterations
+ */
+ public void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ graph.claimLiteral(experiment, sr.GameExperiment_stepDuration, SysdynGameExperimentBase.DEFAULT_STEP_DURATION);
+ graph.claimLiteral(experiment, sr.GameExperiment_stepLength, SysdynGameExperimentBase.DEFAULT_STEP_LENGTH);
+ }
+
+ public String getNameSuggestion() {
+ return "Game Experiment";
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.util.UUID;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Handler for creating new history dataset\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewHistoryDataHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
-\r
- final Resource experiment = AdaptionUtils.adaptToSingle(sel, Resource.class);\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
- if(!g.isInstanceOf(experiment, sr.Experiment))\r
- return; // Not called from an experiment\r
-\r
- Resource model = g.getPossibleObject(experiment, l0.PartOf);\r
- // Create the history dataset\r
- GraphUtils.create2(g, \r
- sr.HistoryDataset,\r
- l0.HasName, "HistoryDataset" + UUID.randomUUID().toString(),\r
- l0.HasLabel, NameUtils.findFreshLabel(g, "History Dataset", experiment),\r
- sr.Experiment_result_Inverse, experiment, \r
- sr.HistoryDataset_columns, Boolean.TRUE,\r
- l0.PartOf, model);\r
- }\r
- });\r
- return null;\r
- }\r
-\r
+/*******************************************************************************
+ * 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.sysdyn.ui.handlers.newComponents;
+
+import java.util.UUID;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Handler for creating new history dataset
+ * @author Teemu Lempinen
+ *
+ */
+public class NewHistoryDataHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ final Resource experiment = AdaptionUtils.adaptToSingle(sel, Resource.class);
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+ if(!g.isInstanceOf(experiment, sr.Experiment))
+ return; // Not called from an experiment
+
+ Resource model = g.getPossibleObject(experiment, l0.PartOf);
+ // Create the history dataset
+ GraphUtils.create2(g,
+ sr.HistoryDataset,
+ l0.HasName, "HistoryDataset" + UUID.randomUUID().toString(),
+ l0.HasLabel, NameUtils.findFreshLabel(g, "History Dataset", experiment),
+ sr.Experiment_result_Inverse, experiment,
+ sr.HistoryDataset_columns, Boolean.TRUE,
+ l0.PartOf, model);
+ }
+ });
+ return null;
+ }
+
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.core.runtime.jobs.Job;\r
-import org.simantics.DatabaseJob;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.utils.ModelUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Creates a new SysDyn model.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewModelHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- \r
- Job job = new DatabaseJob("Creating System Dynamics Model") {\r
- @Override\r
- protected IStatus run(IProgressMonitor monitor) {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- // Use ModelUtils to keep all model creations up-to-date\r
- ModelUtils.createModel(graph);\r
- }\r
- });\r
- return Status.OK_STATUS;\r
- } catch (DatabaseException e) {\r
- return new Status(IStatus.ERROR, Activator.PLUGIN_ID, getName() + " failed.", e);\r
- }\r
- }\r
- };\r
-// job.setUser(true);\r
- job.schedule();\r
-\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.simantics.DatabaseJob;
+import org.simantics.Simantics;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.utils.ModelUtils;
+
+/**
+ * Creates a new SysDyn model.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewModelHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+
+ Job job = new DatabaseJob("Creating System Dynamics Model") {
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ // Use ModelUtils to keep all model creations up-to-date
+ ModelUtils.createModel(graph);
+ }
+ });
+ return Status.OK_STATUS;
+ } catch (DatabaseException e) {
+ return new Status(IStatus.ERROR, Activator.PLUGIN_ID, getName() + " failed.", e);
+ }
+ }
+ };
+// job.setUser(true);
+ job.schedule();
+
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.common.utils.OrderedSetUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.Template;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.browser.actions.newActions.NewModuleTypeAction;\r
-import org.simantics.sysdyn.ui.browser.nodes.ModulesNode;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Creates a new module node for a model.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewModuleNodeHandler extends AbstractHandler {\r
-\r
- /**\r
- * Assumes to be called from a node that has a SysDyn model as its resource.\r
- */\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- \r
- ModulesNode node = AdaptionUtils.adaptToSingle(sel, ModulesNode.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource model = node.data; \r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
- Layer0X L0X = Layer0X.getInstance(g);\r
- ModelingResources mr = ModelingResources.getInstance(g);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(g);\r
- \r
- String name = NameUtils.findFreshName(g, "ModuleType", model, l0.ConsistsOf, "%s%d");\r
- \r
- Resource moduleType = g.newResource();\r
- g.claimLiteral(moduleType, l0.HasName, name);\r
- g.claim(moduleType, l0.Inherits, sr.Module);\r
- g.claim(moduleType, l0.PartOf, model);\r
- \r
- \r
- \r
- Resource configuration = GraphUtils.create2(g, \r
- sr.Configuration,\r
- l0.HasName, name + "Configuration",\r
- l0.PartOf, moduleType);\r
- \r
- g.claim(moduleType, sr2.IsDefinedBy , configuration);\r
- \r
- Resource diagram = g.newResource();\r
- g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,\r
- ArrayMap\r
- .keys("", "diagram", "name")\r
- .values(configuration, diagram, "Diagrammi")\r
- );\r
- \r
- \r
- // Remove default mapping and add sysdyn mapping\r
- for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {\r
- if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {\r
- g.deny(diagram, L0X.HasTrigger, trigger);\r
- }\r
- }\r
- \r
- Resource mapping = g.newResource();\r
- g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);\r
- g.claim(diagram, L0X.HasTrigger, mapping);\r
- \r
- Resource moduleSymbol = g.newResource();\r
- g.claimLiteral(moduleSymbol, l0.HasName, name + " Symbol");\r
- g.claimLiteral(moduleSymbol, l0.HasLabel, name + " Symbol");\r
- g.claim(moduleSymbol, l0.Inherits, sr.ModuleSymbol);\r
- g.claim(moduleSymbol, mr.SymbolToComponentType, moduleType);\r
- g.claim(moduleSymbol, l0.PartOf, moduleType);\r
- \r
- Resource terminal = g.newResource();\r
- g.claim(terminal, l0.InstanceOf, sr.SysdynTerminal);\r
- Resource relation = NewModuleTypeAction.createTerminalRelation(g, moduleSymbol, sr.IsHeadOfTerminal, sr.Variable_isHeadOf);\r
- DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal, relation); \r
- \r
- Resource terminal2 = g.newResource();\r
- g.claim(terminal2, l0.InstanceOf, sr.SysdynTerminal);\r
- relation = NewModuleTypeAction.createTerminalRelation(g, moduleSymbol, sr.IsTailOfTerminal, sr.Variable_isTailOf);\r
- DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal2, relation);\r
- \r
- g.claim(moduleSymbol, sr2.IsDefinedBy, OrderedSetUtils.create(g, sr2.Composite, terminal, terminal2));\r
- \r
- Layer0Utils.addCommentMetadata(g, "Created new Module Type " + name + " " + moduleType.toString());\r
- }\r
- });\r
- return null;\r
- }\r
- \r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.common.utils.OrderedSetUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.Template;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.operation.Layer0X;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.browser.actions.newActions.NewModuleTypeAction;
+import org.simantics.sysdyn.ui.browser.nodes.ModulesNode;
+import org.simantics.utils.datastructures.ArrayMap;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Creates a new module node for a model.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewModuleNodeHandler extends AbstractHandler {
+
+ /**
+ * Assumes to be called from a node that has a SysDyn model as its resource.
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ ModulesNode node = AdaptionUtils.adaptToSingle(sel, ModulesNode.class);
+ if (node == null)
+ return null;
+
+ final Resource model = node.data;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+ Layer0X L0X = Layer0X.getInstance(g);
+ ModelingResources mr = ModelingResources.getInstance(g);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(g);
+
+ String name = NameUtils.findFreshName(g, "ModuleType", model, l0.ConsistsOf, "%s%d");
+
+ Resource moduleType = g.newResource();
+ g.claimLiteral(moduleType, l0.HasName, name);
+ g.claim(moduleType, l0.Inherits, sr.Module);
+ g.claim(moduleType, l0.PartOf, model);
+
+
+
+ Resource configuration = GraphUtils.create2(g,
+ sr.Configuration,
+ l0.HasName, name + "Configuration",
+ l0.PartOf, moduleType);
+
+ g.claim(moduleType, sr2.IsDefinedBy , configuration);
+
+ Resource diagram = g.newResource();
+ g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,
+ ArrayMap
+ .keys("", "diagram", "name")
+ .values(configuration, diagram, "Diagrammi")
+ );
+
+
+ // Remove default mapping and add sysdyn mapping
+ for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {
+ if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {
+ g.deny(diagram, L0X.HasTrigger, trigger);
+ }
+ }
+
+ Resource mapping = g.newResource();
+ g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);
+ g.claim(diagram, L0X.HasTrigger, mapping);
+
+ Resource moduleSymbol = g.newResource();
+ g.claimLiteral(moduleSymbol, l0.HasName, name + " Symbol");
+ g.claimLiteral(moduleSymbol, l0.HasLabel, name + " Symbol");
+ g.claim(moduleSymbol, l0.Inherits, sr.ModuleSymbol);
+ g.claim(moduleSymbol, mr.SymbolToComponentType, moduleType);
+ g.claim(moduleSymbol, l0.PartOf, moduleType);
+
+ Resource terminal = g.newResource();
+ g.claim(terminal, l0.InstanceOf, sr.SysdynTerminal);
+ Resource relation = NewModuleTypeAction.createTerminalRelation(g, moduleSymbol, sr.IsHeadOfTerminal, sr.Variable_isHeadOf);
+ DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal, relation);
+
+ Resource terminal2 = g.newResource();
+ g.claim(terminal2, l0.InstanceOf, sr.SysdynTerminal);
+ relation = NewModuleTypeAction.createTerminalRelation(g, moduleSymbol, sr.IsTailOfTerminal, sr.Variable_isTailOf);
+ DiagramGraphUtil.addConnectionPoint(g, moduleSymbol, terminal2, relation);
+
+ g.claim(moduleSymbol, sr2.IsDefinedBy, OrderedSetUtils.create(g, sr2.Composite, terminal, terminal2));
+
+ Layer0Utils.addCommentMetadata(g, "Created new Module Type " + name + " " + moduleType.toString());
+ }
+ });
+ return null;
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.util.Collections;\r
-import java.util.UUID;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Handler for craeting a new Pie Chart\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewPieChartHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- \r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
-\r
- ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource model = node.data; \r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
- G2DResource g2d = G2DResource.getInstance(g);\r
-\r
- String label = NameUtils.findFreshLabel(g, "Pie Chart", model);\r
- \r
- Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
- l0.HasName, "PieChart" + UUID.randomUUID().toString(),\r
- l0.HasLabel, label,\r
- l0.PartOf, model,\r
- jfree.Chart_visibleBorder, true,\r
- jfree.Chart_borderWidth, 3);\r
- g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
-\r
- GraphUtils.create2(g, jfree.TextTitle,\r
- l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Pie Chart Title",\r
- jfree.Title_position, jfree.Top,\r
- l0.PartOf, jfreechart);\r
- \r
- Resource dataset = GraphUtils.create2(g, jfree.PieDataset,\r
- l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),\r
- jfree.Dataset_seriesList, ListUtils.create(g, Collections.<Resource>emptyList())\r
- );\r
-\r
- GraphUtils.create2(g, jfree.PiePlot,\r
- l0.HasName, "PiePlot" + UUID.randomUUID().toString(),\r
- l0.PartOf, jfreechart,\r
- l0.ConsistsOf, dataset\r
- );\r
- Layer0Utils.addCommentMetadata(g, "Created new Pie Chart " + label + " " + jfreechart);\r
- \r
- }\r
-\r
- });\r
- \r
- return null;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import java.util.Collections;
+import java.util.UUID;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Handler for craeting a new Pie Chart
+ * @author Teemu Lempinen
+ *
+ */
+public class NewPieChartHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);
+ if (node == null)
+ return null;
+
+ final Resource model = node.data;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(g);
+ G2DResource g2d = G2DResource.getInstance(g);
+
+ String label = NameUtils.findFreshLabel(g, "Pie Chart", model);
+
+ Resource jfreechart = GraphUtils.create2(g, jfree.Chart,
+ l0.HasName, "PieChart" + UUID.randomUUID().toString(),
+ l0.HasLabel, label,
+ l0.PartOf, model,
+ jfree.Chart_visibleBorder, true,
+ jfree.Chart_borderWidth, 3);
+ g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});
+
+ GraphUtils.create2(g, jfree.TextTitle,
+ l0.HasName, "TextTitle" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Pie Chart Title",
+ jfree.Title_position, jfree.Top,
+ l0.PartOf, jfreechart);
+
+ Resource dataset = GraphUtils.create2(g, jfree.PieDataset,
+ l0.HasName, "CategoryDataset" + UUID.randomUUID().toString(),
+ jfree.Dataset_seriesList, ListUtils.create(g, Collections.<Resource>emptyList())
+ );
+
+ GraphUtils.create2(g, jfree.PiePlot,
+ l0.HasName, "PiePlot" + UUID.randomUUID().toString(),
+ l0.PartOf, jfreechart,
+ l0.ConsistsOf, dataset
+ );
+ Layer0Utils.addCommentMetadata(g, "Created new Pie Chart " + label + " " + jfreechart);
+
+ }
+
+ });
+
+ return null;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.awt.Color;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-/**\r
- * Creates a new playback experiment.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewPlaybackExperimentNodeHandler extends NewExperimentNodeHandler {\r
-\r
- protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- Resource defaultGradient = GraphUtils.create2(graph, g2d.ColorGradient);\r
- graph.claim(experiment, g2d.HasColorGradient, defaultGradient);\r
-\r
- Resource placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
- g2d.HasGradientPosition, 0.0);\r
- graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(0, 62, 133).getColorComponents(new float[4]));\r
- graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
- \r
- placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
- g2d.HasGradientPosition, 1.0);\r
- graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(255, 230, 0).getColorComponents(new float[4]));\r
- graph.claim(defaultGradient, g2d.HasColorPlacement, placement);\r
- }\r
-\r
- protected Resource getExperimentType(ReadGraph g) {\r
- return SysdynResource.getInstance(g).PlaybackExperiment;\r
- }\r
-\r
- protected String getNameSuggestion() {\r
- return "Playback Experiment";\r
- }\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import java.awt.Color;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Creates a new playback experiment.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class NewPlaybackExperimentNodeHandler extends NewExperimentNodeHandler {
+
+ public void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+ G2DResource g2d = G2DResource.getInstance(graph);
+ Resource defaultGradient = GraphUtils.create2(graph, g2d.ColorGradient);
+ graph.claim(experiment, g2d.HasColorGradient, defaultGradient);
+
+ Resource placement = GraphUtils.create2(graph, g2d.ColorPlacement,
+ g2d.HasGradientPosition, 0.0);
+ graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(0, 62, 133).getColorComponents(new float[4]));
+ graph.claim(defaultGradient, g2d.HasColorPlacement, placement);
+
+ placement = GraphUtils.create2(graph, g2d.ColorPlacement,
+ g2d.HasGradientPosition, 1.0);
+ graph.claimLiteral(placement, g2d.HasColor, g2d.Color, new Color(255, 230, 0).getColorComponents(new float[4]));
+ graph.claim(defaultGradient, g2d.HasColorPlacement, placement);
+ }
+
+ public Resource getExperimentType(ReadGraph g) {
+ return SysdynResource.getInstance(g).PlaybackExperiment;
+ }
+
+ public String getNameSuggestion() {
+ return "Playback Experiment";
+ }
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-\r
-/**\r
- * Creates a new sensitivity analysis experiment.\r
- * \r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class NewSensitivityAnalysisExperimentNodeHandler extends NewExperimentNodeHandler {\r
-\r
- @Override\r
- protected void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- \r
- Resource method = GraphUtils.create2(graph, sr.RandomGenerator);\r
- graph.claim(experiment, sr.SensitivityAnalysisExperiment_method, method);\r
-\r
- Resource distribution = GraphUtils.create2(graph, sr.UniformDistribution,\r
- sr.UniformDistribution_minValue, 0.0,\r
- sr.UniformDistribution_maxValue, 10.0);\r
- \r
- Resource parameter = GraphUtils.create2(graph, sr.SensitivityAnalysisExperiment_Parameter,\r
- sr.SensitivityAnalysisExperiment_Parameter_propabilityDistribution, distribution,\r
- sr.SensitivityAnalysisExperiment_Parameter_variable, ChartUtils.emptyVariableName,\r
- L0.PartOf, experiment);\r
- \r
- ArrayList<Resource> parameterList = new ArrayList<Resource>();\r
- parameterList.add(parameter);\r
- \r
- graph.claim(experiment, sr.SensitivityAnalysisExperiment_parameterList, ListUtils.create(graph, parameterList));\r
- }\r
-\r
- @Override\r
- protected Resource getExperimentType(ReadGraph g) {\r
- return SysdynResource.getInstance(g).SensitivityAnalysisExperiment;\r
- }\r
-\r
- @Override\r
- protected String getNameSuggestion() {\r
- return "Sensitivity Experiment";\r
- }\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import java.util.ArrayList;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Creates a new sensitivity analysis experiment.
+ *
+ * @author Tuomas Miettinen
+ *
+ */
+public class NewSensitivityAnalysisExperimentNodeHandler extends NewExperimentNodeHandler {
+
+ @Override
+ public void configureExperiment(WriteGraph graph, Resource experiment) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 L0 = Layer0.getInstance(graph);
+
+ Resource method = GraphUtils.create2(graph, sr.RandomGenerator);
+ graph.claim(experiment, sr.SensitivityAnalysisExperiment_method, method);
+
+ Resource distribution = GraphUtils.create2(graph, sr.UniformDistribution,
+ sr.UniformDistribution_minValue, 0.0,
+ sr.UniformDistribution_maxValue, 10.0);
+
+ Resource parameter = GraphUtils.create2(graph, sr.SensitivityAnalysisExperiment_Parameter,
+ sr.SensitivityAnalysisExperiment_Parameter_propabilityDistribution, distribution,
+ sr.SensitivityAnalysisExperiment_Parameter_variable, ChartUtils.emptyVariableName,
+ L0.PartOf, experiment);
+
+ ArrayList<Resource> parameterList = new ArrayList<Resource>();
+ parameterList.add(parameter);
+
+ graph.claim(experiment, sr.SensitivityAnalysisExperiment_parameterList, ListUtils.create(graph, parameterList));
+ }
+
+ @Override
+ public Resource getExperimentType(ReadGraph g) {
+ return SysdynResource.getInstance(g).SensitivityAnalysisExperiment;
+ }
+
+ @Override
+ public String getNameSuggestion() {
+ return "Sensitivity Experiment";
+ }
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.awt.Color;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.UUID;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class NewSensitivityChartHandler extends AbstractHandler {\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
-\r
- ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource model = node.data; \r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
- G2DResource g2d = G2DResource.getInstance(g);\r
- SysdynResource SR = SysdynResource.getInstance(g);\r
-\r
- String label = NameUtils.findFreshLabel(g, "SensitivityChart", model);\r
- \r
- Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
- l0.HasName, "SensitivityChart" + UUID.randomUUID().toString(),\r
- l0.HasLabel, label,\r
- l0.PartOf, model,\r
- jfree.Chart_visibleBorder, true,\r
- jfree.Chart_borderWidth, 3);\r
- g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
-\r
- GraphUtils.create2(g, jfree.TextTitle,\r
- l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Chart Title",\r
- jfree.Title_position, jfree.Top,\r
- l0.PartOf, jfreechart);\r
-\r
- Resource domainAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
- jfree.variableRVI, "/time",\r
- l0.HasLabel, "Time");\r
- Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "");\r
-\r
- Resource renderer = GraphUtils.create2(g, jfree.DeviationRenderer);\r
- \r
- Color[] colors = {\r
- new Color(255, 255, 64),\r
- new Color(0, 255, 0),\r
- new Color(0, 0, 255),\r
- new Color(128, 128, 128),\r
- new Color(192, 192, 192)\r
- };\r
- \r
- float[] colorContainer = new float[] {0, 0, 0, 1};\r
-\r
- ArrayList<Resource> confidenceBounds = new ArrayList<Resource>();\r
- confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
- SR.Charts_SensitivityDataset_ConfidenceBound_percent, 25.0\r
- )); \r
- g.claimLiteral(confidenceBounds.get(0), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[0].getColorComponents(colorContainer));\r
- \r
- \r
- confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
- SR.Charts_SensitivityDataset_ConfidenceBound_percent, 50.0\r
- )); \r
- g.claimLiteral(confidenceBounds.get(1), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[1].getColorComponents(colorContainer));\r
-\r
- confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
- SR.Charts_SensitivityDataset_ConfidenceBound_percent, 75.0\r
- )); \r
- g.claimLiteral(confidenceBounds.get(2), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[2].getColorComponents(colorContainer));\r
-\r
- confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,\r
- SR.Charts_SensitivityDataset_ConfidenceBound_percent, 100.0\r
- )); \r
- g.claimLiteral(confidenceBounds.get(3), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[3].getColorComponents(colorContainer));\r
-\r
- confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound\r
- )); \r
- g.claimLiteral(confidenceBounds.get(4), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[4].getColorComponents(colorContainer));\r
-\r
- \r
- Resource dataset = GraphUtils.create2(g, SR.Charts_SensitivityDataset,\r
- l0.HasName, "SensitivityDataset" + UUID.randomUUID().toString(),\r
- jfree.Dataset_mapToDomainAxis, domainAxis,\r
- jfree.Dataset_mapToRangeAxis, rangeAxis,\r
- jfree.Dataset_seriesList, ListUtils.create(g, new ArrayList<Resource>()),\r
- jfree.Dataset_renderer, renderer,\r
- SR.Charts_SensitivityDataset_confidenceBounds, ListUtils.create(g, confidenceBounds)\r
- );\r
- \r
- ChartUtils.createSeries(g, dataset, null);\r
- \r
-\r
-\r
-\r
- GraphUtils.create2(g, SR.Charts_SensitivityPlot,\r
- l0.HasName, "SensitivityPlot" + UUID.randomUUID().toString(),\r
- l0.PartOf, jfreechart,\r
- jfree.Plot_domainAxis, domainAxis,\r
- jfree.Plot_rangeAxis, rangeAxis,\r
- jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),\r
- l0.ConsistsOf, dataset,\r
- l0.ConsistsOf, domainAxis,\r
- l0.ConsistsOf, rangeAxis);\r
- Layer0Utils.addCommentMetadata(g, "Created new Sensitivity Chart " + label + " " + jfreechart);\r
- }\r
-\r
- });\r
-\r
-\r
-\r
- return null;\r
- }\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.handlers.newComponents;
+
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.UUID;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class NewSensitivityChartHandler extends AbstractHandler {
+
+ public static Object handleStatic(Resource model) throws ExecutionException {
+ return(executeImpl(model));
+ }
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);
+ if (node == null)
+ return null;
+
+ final Resource model = node.data;
+ return(executeImpl(model));
+ }
+
+ private static Object executeImpl(Resource model) throws ExecutionException {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(g);
+ G2DResource g2d = G2DResource.getInstance(g);
+ SysdynResource SR = SysdynResource.getInstance(g);
+
+ String label = NameUtils.findFreshLabel(g, "SensitivityChart", model);
+
+ Resource jfreechart = GraphUtils.create2(g, jfree.Chart,
+ l0.HasName, "Sensitivity Chart" + UUID.randomUUID().toString(),
+ l0.HasLabel, label,
+ l0.PartOf, model,
+ jfree.Chart_visibleBorder, true,
+ jfree.Chart_borderWidth, 3);
+ g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});
+
+ GraphUtils.create2(g, jfree.TextTitle,
+ l0.HasName, "TextTitle" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Chart Title",
+ jfree.Title_position, jfree.Top,
+ l0.PartOf, jfreechart);
+
+ Resource domainAxis = GraphUtils.create2(g, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),
+ jfree.variableRVI, "/time",
+ l0.HasLabel, "Time");
+ Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),
+ l0.HasLabel, "");
+
+ Resource renderer = GraphUtils.create2(g, jfree.DeviationRenderer);
+
+ Color[] colors = {
+ new Color(255, 255, 64),
+ new Color(0, 255, 0),
+ new Color(0, 0, 255),
+ new Color(128, 128, 128),
+ new Color(192, 192, 192)
+ };
+
+ float[] colorContainer = new float[] {0, 0, 0, 1};
+
+ ArrayList<Resource> confidenceBounds = new ArrayList<Resource>();
+ confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,
+ SR.Charts_SensitivityDataset_ConfidenceBound_percent, 25.0
+ ));
+ g.claimLiteral(confidenceBounds.get(0), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[0].getColorComponents(colorContainer));
+
+
+ confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,
+ SR.Charts_SensitivityDataset_ConfidenceBound_percent, 50.0
+ ));
+ g.claimLiteral(confidenceBounds.get(1), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[1].getColorComponents(colorContainer));
+
+ confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,
+ SR.Charts_SensitivityDataset_ConfidenceBound_percent, 75.0
+ ));
+ g.claimLiteral(confidenceBounds.get(2), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[2].getColorComponents(colorContainer));
+
+ confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound,
+ SR.Charts_SensitivityDataset_ConfidenceBound_percent, 100.0
+ ));
+ g.claimLiteral(confidenceBounds.get(3), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[3].getColorComponents(colorContainer));
+
+ confidenceBounds.add(GraphUtils.create2(g, SR.Charts_SensitivityDataset_ConfidenceBound
+ ));
+ g.claimLiteral(confidenceBounds.get(4), SR.Charts_SensitivityDataset_ConfidenceBound_color, g2d.Color, colors[4].getColorComponents(colorContainer));
+
+
+ Resource dataset = GraphUtils.create2(g, SR.Charts_SensitivityDataset,
+ l0.HasName, "SensitivityDataset" + UUID.randomUUID().toString(),
+ jfree.Dataset_mapToDomainAxis, domainAxis,
+ jfree.Dataset_mapToRangeAxis, rangeAxis,
+ jfree.Dataset_seriesList, ListUtils.create(g, new ArrayList<Resource>()),
+ jfree.Dataset_renderer, renderer,
+ SR.Charts_SensitivityDataset_confidenceBounds, ListUtils.create(g, confidenceBounds)
+ );
+
+ ChartUtils.createSeries(g, dataset, null);
+
+ GraphUtils.create2(g, SR.Charts_SensitivityPlot,
+ l0.HasName, "SensitivityPlot" + UUID.randomUUID().toString(),
+ l0.PartOf, jfreechart,
+ jfree.Plot_domainAxis, domainAxis,
+ jfree.Plot_rangeAxis, rangeAxis,
+ jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),
+ l0.ConsistsOf, dataset,
+ l0.ConsistsOf, domainAxis,
+ l0.ConsistsOf, rangeAxis);
+ Layer0Utils.addCommentMetadata(g, "Created new Sensitivity Chart " + label + " " + jfreechart);
+ }
+
+ });
+ return null;
+ }
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.sysdyn.utils.SheetUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-/**\r
- * Creates a new spreadsheet sheet to a book.\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class NewSpreadSheetHandler extends AbstractHandler {\r
-\r
- /**\r
- * Called from a node that has a book as its resource.\r
- */\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
- final Resource book = ResourceAdaptionUtils.toSingleResource(sel);\r
- if(book == null) return null;\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- graph.markUndoPoint();\r
- Resource sheet = SheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50});\r
- Layer0Utils.addCommentMetadata(graph, "Created new Spreadsheet " + NameUtils.getSafeName(graph, sheet) + " " + sheet.toString());\r
- }\r
- }); \r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.spreadsheet.util.SpreadsheetUtils;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+/**
+ * Creates a new spreadsheet sheet to a book.
+ * @author Teemu Lempinen
+ *
+ */
+public class NewSpreadSheetHandler extends AbstractHandler {
+
+ /**
+ * Called from a node that has a book as its resource.
+ */
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+ final Resource book = ResourceAdaptionUtils.toSingleResource(sel);
+ if(book == null) return null;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ graph.markUndoPoint();
+ Resource sheet = SpreadsheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50});
+ Layer0Utils.addCommentMetadata(graph, "Created new Spreadsheet " + NameUtils.getSafeName(graph, sheet) + " " + sheet.toString());
+ }
+ });
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.newComponents;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.UUID;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Handler for creating a new XYLineChart in model browser\r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class NewXYLineChartHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
-\r
-\r
- ISelection sel = HandlerUtil.getCurrentSelection(event);\r
-\r
- ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);\r
- if (node == null)\r
- return null;\r
-\r
- final Resource model = node.data; \r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.markUndoPoint();\r
- Layer0 l0 = Layer0.getInstance(g);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(g);\r
- G2DResource g2d = G2DResource.getInstance(g);\r
- \r
- String label = NameUtils.findFreshLabel(g, "Chart", model);\r
- \r
- Resource jfreechart = GraphUtils.create2(g, jfree.Chart,\r
- l0.HasName, "Chart" + UUID.randomUUID().toString(),\r
- l0.HasLabel, label,\r
- l0.PartOf, model,\r
- jfree.Chart_visibleBorder, true,\r
- jfree.Chart_borderWidth, 3);\r
- g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});\r
-\r
- GraphUtils.create2(g, jfree.TextTitle,\r
- l0.HasName, "TextTitle" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Chart Title",\r
- jfree.Title_position, jfree.Top,\r
- l0.PartOf, jfreechart);\r
-\r
- Resource domainAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
- jfree.variableRVI, "/time",\r
- l0.HasLabel, "Time");\r
- Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,\r
- l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),\r
- l0.HasLabel, "Y-axis");\r
- \r
- Resource renderer = GraphUtils.create2(g, jfree.XYLineRenderer);\r
-\r
- Resource dataset = GraphUtils.create2(g, jfree.XYDataset,\r
- l0.HasName, "XYDataset" + UUID.randomUUID().toString(),\r
- jfree.Dataset_mapToDomainAxis, domainAxis,\r
- jfree.Dataset_mapToRangeAxis, rangeAxis,\r
- jfree.Dataset_seriesList, ListUtils.create(g, new ArrayList<Resource>()),\r
- jfree.Dataset_renderer, renderer);\r
-\r
- GraphUtils.create2(g, jfree.XYPlot,\r
- l0.HasName, "XYPlot" + UUID.randomUUID().toString(),\r
- l0.PartOf, jfreechart,\r
- jfree.Plot_domainAxis, domainAxis,\r
- jfree.Plot_rangeAxis, rangeAxis,\r
- jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),\r
- l0.ConsistsOf, dataset,\r
- l0.ConsistsOf, domainAxis,\r
- l0.ConsistsOf, rangeAxis);\r
- Layer0Utils.addCommentMetadata(g, "Created new Line Chart " + label + " " + jfreechart);\r
- }\r
-\r
- });\r
-\r
-\r
-\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.newComponents;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.UUID;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.ui.browser.nodes.ChartsFolder;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Handler for creating a new XYLineChart in model browser
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class NewXYLineChartHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+
+
+ ISelection sel = HandlerUtil.getCurrentSelection(event);
+
+ ChartsFolder node = AdaptionUtils.adaptToSingle(sel, ChartsFolder.class);
+ if (node == null)
+ return null;
+
+ final Resource model = node.data;
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.markUndoPoint();
+ Layer0 l0 = Layer0.getInstance(g);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(g);
+ G2DResource g2d = G2DResource.getInstance(g);
+
+ String label = NameUtils.findFreshLabel(g, "Chart", model);
+
+ Resource jfreechart = GraphUtils.create2(g, jfree.Chart,
+ l0.HasName, "Chart" + UUID.randomUUID().toString(),
+ l0.HasLabel, label,
+ l0.PartOf, model,
+ jfree.Chart_visibleBorder, true,
+ jfree.Chart_borderWidth, 3);
+ g.claimLiteral(jfreechart, jfree.Chart_borderColor, g2d.Color, new float[] {0,0,0,1});
+
+ GraphUtils.create2(g, jfree.TextTitle,
+ l0.HasName, "TextTitle" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Chart Title",
+ jfree.Title_position, jfree.Top,
+ l0.PartOf, jfreechart);
+
+ Resource domainAxis = GraphUtils.create2(g, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),
+ jfree.variableRVI, "/time",
+ l0.HasLabel, "Time");
+ Resource rangeAxis = GraphUtils.create2(g, jfree.NumberAxis,
+ l0.HasName, "NumberAxis" + UUID.randomUUID().toString(),
+ l0.HasLabel, "Y-axis");
+
+ Resource renderer = GraphUtils.create2(g, jfree.XYLineRenderer);
+
+ Resource dataset = GraphUtils.create2(g, jfree.XYDataset,
+ l0.HasName, "XYDataset" + UUID.randomUUID().toString(),
+ jfree.Dataset_mapToDomainAxis, domainAxis,
+ jfree.Dataset_mapToRangeAxis, rangeAxis,
+ jfree.Dataset_seriesList, ListUtils.create(g, new ArrayList<Resource>()),
+ jfree.Dataset_renderer, renderer);
+
+ GraphUtils.create2(g, jfree.XYPlot,
+ l0.HasName, "XYPlot" + UUID.randomUUID().toString(),
+ l0.PartOf, jfreechart,
+ jfree.Plot_domainAxis, domainAxis,
+ jfree.Plot_rangeAxis, rangeAxis,
+ jfree.Plot_rangeAxisList, ListUtils.create(g, Collections.singletonList(rangeAxis)),
+ l0.ConsistsOf, dataset,
+ l0.ConsistsOf, domainAxis,
+ l0.ConsistsOf, rangeAxis);
+ Layer0Utils.addCommentMetadata(g, "Created new Line Chart " + label + " " + jfreechart);
+ }
+
+ });
+
+
+
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.sensitivityAnalysis;\r
-\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IDynamicExperiment;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynExperiment;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Handler for starting a sensitivity analysis simulation\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class RunSensitivityAnalysisExperiment extends AbstractHandler implements IElementUpdater {\r
- \r
- public static final String COMMAND = "org.simantics.sysdyn.ui.runSensitivityAnalysis";\r
- \r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- // Current functionality is normal run experiment\r
- \r
- HandlerUtils.saveBeforeExperimentRun(event);\r
- \r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof IDynamicExperiment)\r
- ((IDynamicExperiment)experiment).simulate(true);\r
- return null;\r
- }\r
-\r
- // What does this method do, is this needed?\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof SysdynExperiment) {\r
- ExperimentState state = experiment.getState();\r
- if(state == ExperimentState.RUNNING) {\r
- this.setBaseEnabled(false);\r
- } else {\r
- this.setBaseEnabled(true);\r
- }\r
- } \r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers.sensitivityAnalysis;
+
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IDynamicExperiment;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynExperiment;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+/**
+ * Handler for starting a sensitivity analysis simulation
+ * @author Tuomas Miettinen
+ *
+ */
+public class RunSensitivityAnalysisExperiment extends AbstractHandler implements IElementUpdater {
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.runSensitivityAnalysis";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ // Current functionality is normal run experiment
+
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof IDynamicExperiment)
+ ((IDynamicExperiment)experiment).simulate(true);
+ return null;
+ }
+
+ // What does this method do, is this needed?
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof SysdynExperiment) {
+ ExperimentState state = experiment.getState();
+ if(state == ExperimentState.RUNNING) {
+ this.setBaseEnabled(false);
+ } else {
+ this.setBaseEnabled(true);
+ }
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.sensitivityAnalysis;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.simantics.simulation.experiment.IDynamicExperiment;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Save the results of a sensitivity analysis experiment\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class SaveResultsHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- // Current functionality is normal run experiment\r
- \r
- HandlerUtils.saveBeforeExperimentRun(event);\r
- \r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof IDynamicExperiment) {\r
- ((IDynamicExperiment)experiment).saveState();\r
- }\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers.sensitivityAnalysis;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.IDynamicExperiment;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+/**
+ * Save the results of a sensitivity analysis experiment
+ * @author Tuomas Miettinen
+ *
+ */
+public class SaveResultsHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ // Current functionality is normal run experiment
+
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof IDynamicExperiment) {
+ ((IDynamicExperiment)experiment).saveState();
+ }
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.sensitivityAnalysis;\r
-\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.Command;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.core.commands.State;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.commands.ICommandService;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynExperiment;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Handle for the Toggle Simulation button. When the button is down, the\r
- * simulation is run every time the model is changed.\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ToggleSimulation extends AbstractHandler implements IElementUpdater {\r
-\r
- public static final String COMMAND = "org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation";\r
- public static final String STATE = "org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation.state";\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- // Current functionality is normal run experiment\r
- HandlerUtils.saveBeforeExperimentRun(event);\r
-\r
- ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = service.getCommand(COMMAND);\r
- State state = command.getState(STATE);\r
- Boolean value = (Boolean) state.getValue();\r
- value = !value;\r
- state.setValue(value);\r
- service.refreshElements(RunSensitivityAnalysisExperiment.COMMAND, null);\r
- \r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment instanceof SysdynExperiment) {\r
- if(getState()) {\r
- ((SysdynExperiment)experiment).toggleSimulation(true);\r
- } else {\r
- ((SysdynExperiment)experiment).toggleSimulation(false);\r
- }\r
- }\r
- \r
- return null;\r
- }\r
-\r
- public static Boolean getState() {\r
- ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = service.getCommand(COMMAND);\r
- State state = command.getState(STATE);\r
- return (Boolean)state.getValue();\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- ICommandService commandService =\r
- (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- Command command = commandService.getCommand(COMMAND);\r
- boolean checked = (Boolean) command.getState(STATE).getValue();\r
- element.setChecked(checked);\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.handlers.sensitivityAnalysis;
+
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.Command;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.commands.State;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.commands.ICommandService;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynExperiment;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+/**
+ * Handle for the Toggle Simulation button. When the button is down, the
+ * simulation is run every time the model is changed.
+ * @author Tuomas Miettinen
+ *
+ */
+public class ToggleSimulation extends AbstractHandler implements IElementUpdater {
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation";
+ public static final String STATE = "org.simantics.sysdyn.ui.toggleSensitivityAnalysisSimulation.state";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ // Current functionality is normal run experiment
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = service.getCommand(COMMAND);
+ State state = command.getState(STATE);
+ Boolean value = (Boolean) state.getValue();
+ value = !value;
+ state.setValue(value);
+ service.refreshElements(RunSensitivityAnalysisExperiment.COMMAND, null);
+
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment instanceof SysdynExperiment) {
+ if(getState()) {
+ ((SysdynExperiment)experiment).toggleSimulation(true);
+ } else {
+ ((SysdynExperiment)experiment).toggleSimulation(false);
+ }
+ }
+
+ return null;
+ }
+
+ public static Boolean getState() {
+ ICommandService service = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = service.getCommand(COMMAND);
+ State state = command.getState(STATE);
+ return (Boolean)state.getValue();
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ ICommandService commandService =
+ (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ Command command = commandService.getCommand(COMMAND);
+ boolean checked = (Boolean) command.getState(STATE).getValue();
+ element.setChecked(checked);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class PlaybackExperimentHandler extends AbstractHandler implements IElementUpdater {\r
- \r
- public static final String COMMAND = "org.simantics.sysdyn.ui.playback";\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
- return null;\r
- SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
- if(!spe.isPlaybackRunning())\r
- spe.startPlayback();\r
- else\r
- spe.stopPlayback();\r
- return null;\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
- return;\r
- SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment; \r
- \r
- ExperimentState state = experiment.getState();\r
- if(state == ExperimentState.RUNNING && !spe.isPlaybackRunning()) {\r
- // RUNNING == simulation, not playback\r
- this.setBaseEnabled(false);\r
- } else {\r
- this.setBaseEnabled(true);\r
- }\r
-\r
- if(spe.isPlaybackRunning()) {\r
- element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_pause.png")));\r
- element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_pause_blue.png")));\r
- } else {\r
- long duration = spe.getPlaybackDuration();\r
- if(duration == SysdynPlaybackExperiment.DURATION_SLOW) {\r
- element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_step.png")));\r
- element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_step_blue.png")));\r
- } else if(duration == SysdynPlaybackExperiment.DURATION_FAST) {\r
- element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_fastforward.png")));\r
- element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_fastforward_blue.png")));\r
- } else {\r
- element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_play.png")));\r
- element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_play_blue.png")));\r
- }\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.simulationPlayback;
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;
+import org.simantics.sysdyn.ui.Activator;
+
+public class PlaybackExperimentHandler extends AbstractHandler implements IElementUpdater {
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.playback";
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IExperimentManager manager = Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment))
+ return null;
+ SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;
+ if(!spe.isPlaybackRunning())
+ spe.startPlayback();
+ else
+ spe.stopPlayback();
+ return null;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment))
+ return;
+ SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;
+
+ ExperimentState state = experiment.getState();
+ if(state == ExperimentState.RUNNING && !spe.isPlaybackRunning()) {
+ // RUNNING == simulation, not playback
+ this.setBaseEnabled(false);
+ } else {
+ this.setBaseEnabled(true);
+ }
+
+ if(spe.isPlaybackRunning()) {
+ element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_pause.png")));
+ element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_pause_blue.png")));
+ } else {
+ long duration = spe.getPlaybackDuration();
+ if(duration == SysdynPlaybackExperiment.DURATION_SLOW) {
+ element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_step.png")));
+ element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_step_blue.png")));
+ } else if(duration == SysdynPlaybackExperiment.DURATION_FAST) {
+ element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_fastforward.png")));
+ element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_fastforward_blue.png")));
+ } else {
+ element.setIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_play.png")));
+ element.setHoverIcon(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/control_play_blue.png")));
+ }
+ }
+ }
+}
-package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
-import org.simantics.sysdyn.ui.utils.HandlerUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class PlaybackReloadHandler extends AbstractHandler {\r
-\r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- HandlerUtils.saveBeforeExperimentRun(event);\r
- \r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
- return null;\r
- SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
- spe.simulate(true);\r
- return null;\r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.handlers.simulationPlayback;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;
+import org.simantics.sysdyn.ui.utils.HandlerUtils;
+
+public class PlaybackReloadHandler extends AbstractHandler {
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ HandlerUtils.saveBeforeExperimentRun(event);
+
+ IExperimentManager manager = Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment))
+ return null;
+ SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;
+ spe.simulate(true);
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.ui.commands.IElementUpdater;\r
-import org.eclipse.ui.menus.UIElement;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class PlaybackResetHandler extends AbstractHandler implements IElementUpdater {\r
-\r
- public static final String COMMAND = "org.simantics.sysdyn.ui.playbackReset";\r
-\r
- \r
- @Override\r
- public Object execute(ExecutionEvent event) throws ExecutionException {\r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
- return null;\r
- SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
- spe.resetPlayback();\r
- return null;\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public void updateElement(UIElement element, Map parameters) {\r
- IExperimentManager manager = \r
- SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
- return;\r
- SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment; \r
-\r
- ExperimentState state = experiment.getState();\r
- if(state == ExperimentState.RUNNING && !spe.isPlaybackRunning()) {\r
- // RUNNING == simulation, not playback\r
- this.setBaseEnabled(false);\r
- } else {\r
- this.setBaseEnabled(true);\r
- }\r
-\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.simulationPlayback;
+
+import java.util.Map;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.ui.commands.IElementUpdater;
+import org.eclipse.ui.menus.UIElement;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;
+
+public class PlaybackResetHandler extends AbstractHandler implements IElementUpdater {
+
+ public static final String COMMAND = "org.simantics.sysdyn.ui.playbackReset";
+
+
+ @Override
+ public Object execute(ExecutionEvent event) throws ExecutionException {
+ IExperimentManager manager = Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment))
+ return null;
+ SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;
+ spe.resetPlayback();
+ return null;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public void updateElement(UIElement element, Map parameters) {
+ IExperimentManager manager =
+ Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment))
+ return;
+ SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;
+
+ ExperimentState state = experiment.getState();
+ if(state == ExperimentState.RUNNING && !spe.isPlaybackRunning()) {
+ // RUNNING == simulation, not playback
+ this.setBaseEnabled(false);
+ } else {
+ this.setBaseEnabled(true);
+ }
+
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.handlers.simulationPlayback;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.commands.ICommandService;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-abstract class SpeedHandler extends AbstractHandler {\r
- \r
- protected void setPlaybackSpeed(long duration) {\r
- \r
- \r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
- return;\r
- final SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;\r
- \r
- if(spe.getPlaybackDuration() == duration)\r
- return;\r
- \r
- \r
- spe.setPlaybackDuration(duration);\r
- \r
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- ICommandService commandService =\r
- (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);\r
- commandService.refreshElements(PlaybackExperimentHandler.COMMAND, null);\r
- }\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.handlers.simulationPlayback;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.commands.ICommandService;
+import org.simantics.Simantics;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;
+
+abstract class SpeedHandler extends AbstractHandler {
+
+ protected void setPlaybackSpeed(long duration) {
+
+
+ IExperimentManager manager = Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment))
+ return;
+ final SysdynPlaybackExperiment spe = (SysdynPlaybackExperiment)experiment;
+
+ if(spe.getPlaybackDuration() == duration)
+ return;
+
+
+ spe.setPlaybackDuration(duration);
+
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ ICommandService commandService =
+ (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
+ commandService.refreshElements(PlaybackExperimentHandler.COMMAND, null);
+ }
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.listeners;\r
-\r
-import java.util.HashMap;\r
-\r
-import org.eclipse.ui.IEditorPart;\r
-import org.eclipse.ui.IEditorReference;\r
-import org.eclipse.ui.IWorkbench;\r
-import org.eclipse.ui.IWorkbenchPage;\r
-import org.eclipse.ui.IWorkbenchWindow;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.simantics.Simantics;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.PossibleObjectWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.service.VirtualGraphSupport;\r
-import org.simantics.diagram.profile.Profiles;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ui.diagramEditor.DiagramEditor;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.experiment.IExperimentListener;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
-import org.simantics.sysdyn.ui.editor.DiagramViewer;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Listener for playback simulations. This listener activates and reverts the playback\r
- * profile when a playback simlation is activated or disposed.\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class SysdynPlaybackExperimentListener implements IExperimentListener {\r
-\r
- private Resource model;\r
- private Resource previousProfile;\r
-\r
- public SysdynPlaybackExperimentListener(SysdynPlaybackExperiment experiment) {\r
- this.model = experiment.getModel();\r
- activatePlaybackProfile();\r
- }\r
-\r
- @Override\r
- public void stateChanged(final ExperimentState state) {\r
- switch(state) {\r
- case DISPOSED:\r
- revertPlaybackProfiles();\r
- default:\r
- break;\r
- }\r
- }\r
-\r
- class DiagramInfo {\r
- public Resource model = null;\r
- public Resource previousProfile = null;\r
- }\r
-\r
- HashMap<Resource, DiagramInfo> previousRuntimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>(); \r
-\r
- private void activatePlaybackProfile() {\r
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- previousRuntimeDiagramsAndModelUris.clear();\r
- previousRuntimeDiagramsAndModelUris = getCurrentRuntimeDiagramInfos();\r
- activatePlaybackProfileRequest(previousRuntimeDiagramsAndModelUris);\r
- }\r
- });\r
- }\r
- \r
- private void revertPlaybackProfiles() {\r
- \r
- IProject project = SimanticsUI.getProject();\r
- if(project == null)\r
- return;\r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- \r
- if(experiment != null && experiment instanceof SysdynPlaybackExperiment && this.model.equals(experiment.getModel()))\r
- return;\r
- \r
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- final HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = getCurrentRuntimeDiagramInfos();\r
-\r
- VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);\r
- Simantics.getSession().asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- \r
- Resource model = SysdynPlaybackExperimentListener.this.model;\r
- if(model == null)\r
- return;\r
- \r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- \r
- Resource defaultProfile = graph.syncRequest(new PossibleObjectWithType(model, l0.ConsistsOf, sr.DefaultProfile));\r
- if(defaultProfile == null)\r
- return;\r
- \r
- setProfileForModel(graph, model, previousProfile == null ? defaultProfile : previousProfile);\r
- \r
- HashMap<Resource, DiagramInfo> infos = getRuntimesForModel(graph, runtimeDiagramsAndModelUris, model);\r
- for(Resource runtimeDiagram : infos.keySet()) {\r
- Resource previous = null;\r
- if(previousRuntimeDiagramsAndModelUris.containsKey(runtimeDiagram)) {\r
- previous = previousRuntimeDiagramsAndModelUris.get(runtimeDiagram).previousProfile;\r
- }\r
- setProfileForDiagram(graph, runtimeDiagram, previous == null ? defaultProfile : previous);\r
- }\r
- }\r
- });\r
- \r
- }\r
- });\r
- }\r
- \r
- /**\r
- * Run in display thread.\r
- * \r
- * @return\r
- */\r
- private HashMap<Resource, DiagramInfo> getCurrentRuntimeDiagramInfos() {\r
- HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>(); \r
- IWorkbench workBench = PlatformUI.getWorkbench();\r
- IWorkbenchWindow window = workBench.getActiveWorkbenchWindow();\r
- IWorkbenchPage[] pages = window.getPages();\r
- for(IWorkbenchPage page : pages) {\r
- for(IEditorReference reference : page.getEditorReferences()) {\r
- IEditorPart iep = reference.getEditor(false);\r
- if(iep instanceof DiagramEditor) {\r
- DiagramEditor editor = (DiagramEditor) iep;\r
- if (editor.getViewer() instanceof DiagramViewer) {\r
- DiagramViewer viewer = (DiagramViewer) editor.getViewer();\r
- Resource runtime = viewer.getRuntime();\r
- Resource model = viewer.getResourceInput2().getModel(null);\r
- DiagramInfo info = new DiagramInfo();\r
- info.model = model;\r
- runtimeDiagramsAndModelUris.put(runtime, info);\r
- }\r
- }\r
- }\r
- }\r
- return runtimeDiagramsAndModelUris;\r
- }\r
- \r
- \r
- private HashMap<Resource, DiagramInfo> getRuntimesForModel(WriteGraph graph, HashMap<Resource, DiagramInfo> allInfos, Resource model) throws DatabaseException {\r
- HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>(); \r
- for(Resource runtimeDiagram : allInfos.keySet()) {\r
- DiagramInfo di = allInfos.get(runtimeDiagram);\r
- if(di == null)\r
- continue;\r
- Resource m = di.model;\r
- if(m == null || !model.equals(m)) \r
- continue;\r
- \r
- runtimeDiagramsAndModelUris.put(runtimeDiagram, di);\r
- }\r
- return runtimeDiagramsAndModelUris;\r
- }\r
- \r
- private void activatePlaybackProfileRequest(final HashMap<Resource, DiagramInfo> allDiagramInfos) {\r
- VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);\r
- Simantics.getSession().asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- \r
- Resource model = SysdynPlaybackExperimentListener.this.model;\r
- if(model == null)\r
- return;\r
- \r
- Resource profile = getSimulationPlaybackProfile(graph, model);\r
- if(profile == null)\r
- return;\r
- \r
- DiagramResource DIA = DiagramResource.getInstance(graph);\r
-\r
- Resource current = graph.getPossibleObject(model, DIA.HasActiveProfile);\r
- previousProfile = current;\r
-\r
- if(!profile.equals(current)) {\r
- setProfileForModel(graph, model, profile);\r
- }\r
- \r
- HashMap<Resource, DiagramInfo> infos = getRuntimesForModel(graph, allDiagramInfos, model);\r
- for(Resource runtimeDiagram : infos.keySet()) {\r
- DiagramInfo di = infos.get(runtimeDiagram);\r
- current = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile);\r
- di.previousProfile = current;\r
- if(profile.equals(current)) \r
- continue;\r
- setProfileForDiagram(graph, runtimeDiagram, profile);\r
- }\r
- }\r
- });\r
- }\r
- \r
- \r
- private void setProfileForDiagram(WriteGraph graph, Resource runtimeDiagram, Resource profile) throws DatabaseException {\r
- DiagramResource DIA = DiagramResource.getInstance(graph);\r
-\r
- Resource current = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile);\r
- if(profile.equals(current)) return;\r
- \r
- if(current != null)\r
- graph.deny(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile, null, current);\r
- graph.claim(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile, null, profile);\r
-\r
- // Set this profile as the default profile for this diagram\r
- Resource configuration = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasConfiguration);\r
- graph.deny(configuration, DIA.HasActiveProfile);\r
- graph.claim(configuration, DIA.HasActiveProfile, profile);\r
- }\r
- \r
- private void setProfileForModel(WriteGraph graph, Resource model, Resource profile) throws DatabaseException {\r
- DiagramResource DIA = DiagramResource.getInstance(graph);\r
-\r
- // Set this profile as the default profile for this model\r
- graph.deny(model, DIA.HasActiveProfile);\r
- graph.claim(model, DIA.HasActiveProfile, profile);\r
- }\r
- \r
- private Resource getSimulationPlaybackProfile(WriteGraph graph, Resource model) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- SimulationResource SIMU = SimulationResource.getInstance(graph);\r
- \r
- Resource profile = graph.syncRequest(new PossibleObjectWithType(model, l0.ConsistsOf, sr.SimulationPlaybackProfile));\r
- if(profile == null) {\r
- profile = Profiles.createProfile(graph, "Simulation Playback", sr.Profiles_SimulationPlaybackColours);\r
- graph.deny(profile, l0.InstanceOf);\r
- graph.claim(profile, l0.InstanceOf, null, sr.SimulationPlaybackProfile);\r
- graph.claim(model, l0.ConsistsOf, profile);\r
- }\r
-\r
- if(!graph.hasStatement(profile, SIMU.IsActive)) {\r
- graph.claim(profile, SIMU.IsActive, sr.Profiles_SimulationPlaybackColours);\r
- }\r
- \r
- return profile;\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.listeners;
+
+import java.util.HashMap;
+
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IEditorReference;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.PossibleObjectWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.service.VirtualGraphSupport;
+import org.simantics.diagram.profile.Profiles;
+import org.simantics.diagram.stubs.DiagramResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ui.diagramEditor.DiagramEditor;
+import org.simantics.project.IProject;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.experiment.IExperimentListener;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;
+import org.simantics.sysdyn.ui.editor.DiagramViewer;
+
+/**
+ * Listener for playback simulations. This listener activates and reverts the playback
+ * profile when a playback simlation is activated or disposed.
+ * @author Teemu Lempinen
+ *
+ */
+public class SysdynPlaybackExperimentListener implements IExperimentListener {
+
+ private Resource model;
+ private Resource previousProfile;
+
+ public SysdynPlaybackExperimentListener(SysdynPlaybackExperiment experiment) {
+ this.model = experiment.getModel();
+ activatePlaybackProfile();
+ }
+
+ @Override
+ public void stateChanged(final ExperimentState state) {
+ switch(state) {
+ case DISPOSED:
+ revertPlaybackProfiles();
+ default:
+ break;
+ }
+ }
+
+ class DiagramInfo {
+ public Resource model = null;
+ public Resource previousProfile = null;
+ }
+
+ HashMap<Resource, DiagramInfo> previousRuntimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>();
+
+ private void activatePlaybackProfile() {
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ previousRuntimeDiagramsAndModelUris.clear();
+ previousRuntimeDiagramsAndModelUris = getCurrentRuntimeDiagramInfos();
+ activatePlaybackProfileRequest(previousRuntimeDiagramsAndModelUris);
+ }
+ });
+ }
+
+ private void revertPlaybackProfiles() {
+
+ IProject project = Simantics.getProject();
+ if(project == null)
+ return;
+ IExperimentManager manager = Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+
+ if(experiment != null && experiment instanceof SysdynPlaybackExperiment && this.model.equals(experiment.getModel()))
+ return;
+
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ final HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = getCurrentRuntimeDiagramInfos();
+
+ VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
+ Simantics.getSession().asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+
+ Resource model = SysdynPlaybackExperimentListener.this.model;
+ if(model == null)
+ return;
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ Resource defaultProfile = graph.syncRequest(new PossibleObjectWithType(model, l0.ConsistsOf, sr.DefaultProfile));
+ if(defaultProfile == null)
+ return;
+
+ setProfileForModel(graph, model, previousProfile == null ? defaultProfile : previousProfile);
+
+ HashMap<Resource, DiagramInfo> infos = getRuntimesForModel(graph, runtimeDiagramsAndModelUris, model);
+ for(Resource runtimeDiagram : infos.keySet()) {
+ Resource previous = null;
+ if(previousRuntimeDiagramsAndModelUris.containsKey(runtimeDiagram)) {
+ previous = previousRuntimeDiagramsAndModelUris.get(runtimeDiagram).previousProfile;
+ }
+ setProfileForDiagram(graph, runtimeDiagram, previous == null ? defaultProfile : previous);
+ }
+ }
+ });
+
+ }
+ });
+ }
+
+ /**
+ * Run in display thread.
+ *
+ * @return
+ */
+ private HashMap<Resource, DiagramInfo> getCurrentRuntimeDiagramInfos() {
+ HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>();
+ IWorkbench workBench = PlatformUI.getWorkbench();
+ IWorkbenchWindow window = workBench.getActiveWorkbenchWindow();
+ IWorkbenchPage[] pages = window.getPages();
+ for(IWorkbenchPage page : pages) {
+ for(IEditorReference reference : page.getEditorReferences()) {
+ IEditorPart iep = reference.getEditor(false);
+ if(iep instanceof DiagramEditor) {
+ DiagramEditor editor = (DiagramEditor) iep;
+ if (editor.getViewer() instanceof DiagramViewer) {
+ DiagramViewer viewer = (DiagramViewer) editor.getViewer();
+ Resource runtime = viewer.getRuntime();
+ Resource model = viewer.getResourceInput2().getModel(null);
+ DiagramInfo info = new DiagramInfo();
+ info.model = model;
+ runtimeDiagramsAndModelUris.put(runtime, info);
+ }
+ }
+ }
+ }
+ return runtimeDiagramsAndModelUris;
+ }
+
+
+ private HashMap<Resource, DiagramInfo> getRuntimesForModel(WriteGraph graph, HashMap<Resource, DiagramInfo> allInfos, Resource model) throws DatabaseException {
+ HashMap<Resource, DiagramInfo> runtimeDiagramsAndModelUris = new HashMap<Resource, DiagramInfo>();
+ for(Resource runtimeDiagram : allInfos.keySet()) {
+ DiagramInfo di = allInfos.get(runtimeDiagram);
+ if(di == null)
+ continue;
+ Resource m = di.model;
+ if(m == null || !model.equals(m))
+ continue;
+
+ runtimeDiagramsAndModelUris.put(runtimeDiagram, di);
+ }
+ return runtimeDiagramsAndModelUris;
+ }
+
+ private void activatePlaybackProfileRequest(final HashMap<Resource, DiagramInfo> allDiagramInfos) {
+ VirtualGraphSupport support = Simantics.getSession().getService(VirtualGraphSupport.class);
+ Simantics.getSession().asyncRequest(new WriteRequest(support.getWorkspacePersistent("profiles")) {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+
+ Resource model = SysdynPlaybackExperimentListener.this.model;
+ if(model == null)
+ return;
+
+ Resource profile = getSimulationPlaybackProfile(graph, model);
+ if(profile == null)
+ return;
+
+ DiagramResource DIA = DiagramResource.getInstance(graph);
+
+ Resource current = graph.getPossibleObject(model, DIA.HasActiveProfile);
+ previousProfile = current;
+
+ if(!profile.equals(current)) {
+ setProfileForModel(graph, model, profile);
+ }
+
+ HashMap<Resource, DiagramInfo> infos = getRuntimesForModel(graph, allDiagramInfos, model);
+ for(Resource runtimeDiagram : infos.keySet()) {
+ DiagramInfo di = infos.get(runtimeDiagram);
+ current = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile);
+ di.previousProfile = current;
+ if(profile.equals(current))
+ continue;
+ setProfileForDiagram(graph, runtimeDiagram, profile);
+ }
+ }
+ });
+ }
+
+
+ private void setProfileForDiagram(WriteGraph graph, Resource runtimeDiagram, Resource profile) throws DatabaseException {
+ DiagramResource DIA = DiagramResource.getInstance(graph);
+
+ Resource current = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile);
+ if(profile.equals(current)) return;
+
+ if(current != null)
+ graph.deny(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile, null, current);
+ graph.claim(runtimeDiagram, DIA.RuntimeDiagram_HasRuntimeProfile, null, profile);
+
+ // Set this profile as the default profile for this diagram
+ Resource configuration = graph.getPossibleObject(runtimeDiagram, DIA.RuntimeDiagram_HasConfiguration);
+ graph.deny(configuration, DIA.HasActiveProfile);
+ graph.claim(configuration, DIA.HasActiveProfile, profile);
+ }
+
+ private void setProfileForModel(WriteGraph graph, Resource model, Resource profile) throws DatabaseException {
+ DiagramResource DIA = DiagramResource.getInstance(graph);
+
+ // Set this profile as the default profile for this model
+ graph.deny(model, DIA.HasActiveProfile);
+ graph.claim(model, DIA.HasActiveProfile, profile);
+ }
+
+ private Resource getSimulationPlaybackProfile(WriteGraph graph, Resource model) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ SimulationResource SIMU = SimulationResource.getInstance(graph);
+
+ Resource profile = graph.syncRequest(new PossibleObjectWithType(model, l0.ConsistsOf, sr.SimulationPlaybackProfile));
+ if(profile == null) {
+ profile = Profiles.createProfile(graph, "Simulation Playback", sr.Profiles_SimulationPlaybackColours);
+ graph.deny(profile, l0.InstanceOf);
+ graph.claim(profile, l0.InstanceOf, null, sr.SimulationPlaybackProfile);
+ graph.claim(model, l0.ConsistsOf, profile);
+ }
+
+ if(!graph.hasStatement(profile, SIMU.IsActive)) {
+ graph.claim(profile, SIMU.IsActive, sr.Profiles_SimulationPlaybackColours);
+ }
+
+ return profile;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.menu;\r
-\r
-import java.awt.Color;\r
-import java.awt.Font;\r
-\r
-import org.eclipse.jface.action.ContributionItem;\r
-import org.eclipse.jface.action.IContributionItem;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.widgets.Menu;\r
-import org.eclipse.swt.widgets.MenuItem;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.diagram.G2DUtils;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.sysdyn.ui.properties.widgets.CustomFontDialog;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.contribution.DynamicMenuContribution;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-/**\r
- * Context menu contribution for modifying fonts and font colors in diagram elements\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class FontContextMenuContribution extends DynamicMenuContribution {\r
-\r
- @Override\r
- protected IContributionItem[] getContributionItems(final ReadGraph graph,\r
- Object[] selection) throws DatabaseException {\r
- if (selection.length == 0)\r
- return new IContributionItem[0];\r
-\r
- return new IContributionItem[] { new ContributionItem() {\r
-\r
- @Override\r
- public void fill(Menu menu, int index) {\r
-\r
- G2DResource G2D = G2DResource.getInstance(graph);\r
-\r
- Object[] selections = getSelectedObjects();\r
-\r
- Font font = null;\r
- Color color = null;\r
-\r
- /*\r
- * Find a common font and color for the selected elements.\r
- * \r
- * If a common font or color is not found, the initial value in dialog is empty.\r
- */\r
- try {\r
- for(Object o : selections) {\r
- Resource element = ResourceAdaptionUtils\r
- .adaptToResource(o);\r
- if(element != null) {\r
- Resource fontResource = graph.getPossibleObject(element, G2D.HasFont);\r
- if(fontResource != null) { \r
- Font newFont = G2DUtils.getFont(graph, fontResource);\r
- if(font == null) {\r
- font = newFont;\r
- }\r
-\r
- if(font != null && !font.equals(newFont)) {\r
- font = null;\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- try {\r
- for(Object o : selections) {\r
- Resource element = ResourceAdaptionUtils\r
- .adaptToResource(o);\r
- if(element != null) {\r
- Resource colorResource = graph.getPossibleObject(element, G2D.HasColor);\r
- if(colorResource != null ) {\r
- Color newColor = G2DUtils.getColor(graph, colorResource);\r
- if(color == null)\r
- color = newColor;\r
-\r
- if(color != null && !color.equals(newColor)) {\r
- color = null;\r
- break;\r
- }\r
- } \r
- }\r
- }\r
- } catch (DatabaseException e) {\r
- }\r
-\r
- // Create the menu item with a selection listener\r
- MenuItem item;\r
- item = new MenuItem(menu, SWT.PUSH);\r
-\r
- item.setText("Font...");\r
-\r
- item.addSelectionListener(new FontSelectionListener(selections, font, color));\r
- }\r
- } \r
- };\r
-\r
- }\r
-\r
- /**\r
- * Selection listener for font context menu action\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- class FontSelectionListener implements SelectionListener {\r
-\r
- private Font font;\r
- private Color color;\r
- private Object[] selections;\r
-\r
- /**\r
- * Font selection listener for context menu action in diagram\r
- * \r
- * @param selections Selected elements\r
- * @param font Possible common font for the selected elements\r
- * @param color Possible common color for the selected elements\r
- */\r
- public FontSelectionListener(Object[] selections, Font font, Color color) {\r
- this.selections = selections;\r
- this.font = font;\r
- this.color = color;\r
- }\r
-\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- // Create the dialog\r
- CustomFontDialog dialog = new CustomFontDialog(e.widget.getDisplay().getActiveShell(), "Sample");\r
-\r
- // Set possible font and color defaults\r
- if(font != null)\r
- dialog.setAWTFont(font);\r
-\r
- if(color != null)\r
- dialog.setColor(color);\r
-\r
- // Open dialog\r
- dialog.open();\r
-\r
- // Get results\r
- final Font resultFont = dialog.getAWTFont();\r
- final Color resultColor = dialog.getAWTColor();\r
-\r
- // Apply results to all selected elements\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- G2DResource G2D = G2DResource.getInstance(graph);\r
-\r
- for(Object o : selections) {\r
- Resource element = ResourceAdaptionUtils\r
- .adaptToResource(o);\r
- if(resultFont != null) {\r
- graph.deny(element, G2D.HasFont);\r
- graph.claim(element, G2D.HasFont, G2DUtils.createFont(graph, resultFont));\r
- }\r
-\r
- if(resultColor != null) {\r
- graph.deny(element, G2D.HasColor);\r
- graph.claim(element, G2D.HasColor, G2DUtils.createColor(graph, resultColor));\r
- }\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- }\r
-\r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.menu;
+
+import java.awt.Color;
+import java.awt.Font;
+
+import org.eclipse.jface.action.ContributionItem;
+import org.eclipse.jface.action.IContributionItem;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Menu;
+import org.eclipse.swt.widgets.MenuItem;
+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.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.diagram.G2DUtils;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.sysdyn.ui.properties.widgets.CustomFontDialog;
+import org.simantics.ui.contribution.DynamicMenuContribution;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+/**
+ * Context menu contribution for modifying fonts and font colors in diagram elements
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class FontContextMenuContribution extends DynamicMenuContribution {
+
+ @Override
+ protected IContributionItem[] getContributionItems(final ReadGraph graph,
+ Object[] selection) throws DatabaseException {
+ if (selection.length == 0)
+ return new IContributionItem[0];
+
+ return new IContributionItem[] { new ContributionItem() {
+
+ @Override
+ public void fill(Menu menu, int index) {
+
+ G2DResource G2D = G2DResource.getInstance(graph);
+
+ Object[] selections = getSelectedObjects();
+
+ Font font = null;
+ Color color = null;
+
+ /*
+ * Find a common font and color for the selected elements.
+ *
+ * If a common font or color is not found, the initial value in dialog is empty.
+ */
+ try {
+ for(Object o : selections) {
+ Resource element = ResourceAdaptionUtils
+ .adaptToResource(o);
+ if(element != null) {
+ Resource fontResource = graph.getPossibleObject(element, G2D.HasFont);
+ if(fontResource != null) {
+ Font newFont = G2DUtils.getFont(graph, fontResource);
+ if(font == null) {
+ font = newFont;
+ }
+
+ if(font != null && !font.equals(newFont)) {
+ font = null;
+ break;
+ }
+ }
+ }
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ try {
+ for(Object o : selections) {
+ Resource element = ResourceAdaptionUtils
+ .adaptToResource(o);
+ if(element != null) {
+ Resource colorResource = graph.getPossibleObject(element, G2D.HasColor);
+ if(colorResource != null ) {
+ Color newColor = G2DUtils.getColor(graph, colorResource);
+ if(color == null)
+ color = newColor;
+
+ if(color != null && !color.equals(newColor)) {
+ color = null;
+ break;
+ }
+ }
+ }
+ }
+ } catch (DatabaseException e) {
+ }
+
+ // Create the menu item with a selection listener
+ MenuItem item;
+ item = new MenuItem(menu, SWT.PUSH);
+
+ item.setText("Font...");
+
+ item.addSelectionListener(new FontSelectionListener(selections, font, color));
+ }
+ }
+ };
+
+ }
+
+ /**
+ * Selection listener for font context menu action
+ * @author Teemu Lempinen
+ *
+ */
+ class FontSelectionListener implements SelectionListener {
+
+ private Font font;
+ private Color color;
+ private Object[] selections;
+
+ /**
+ * Font selection listener for context menu action in diagram
+ *
+ * @param selections Selected elements
+ * @param font Possible common font for the selected elements
+ * @param color Possible common color for the selected elements
+ */
+ public FontSelectionListener(Object[] selections, Font font, Color color) {
+ this.selections = selections;
+ this.font = font;
+ this.color = color;
+ }
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ // Create the dialog
+ CustomFontDialog dialog = new CustomFontDialog(e.widget.getDisplay().getActiveShell(), "Sample");
+
+ // Set possible font and color defaults
+ if(font != null)
+ dialog.setAWTFont(font);
+
+ if(color != null)
+ dialog.setColor(color);
+
+ // Open dialog
+ dialog.open();
+
+ // Get results
+ final Font resultFont = dialog.getAWTFont();
+ final Color resultColor = dialog.getAWTColor();
+
+ // Apply results to all selected elements
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ G2DResource G2D = G2DResource.getInstance(graph);
+
+ for(Object o : selections) {
+ Resource element = ResourceAdaptionUtils
+ .adaptToResource(o);
+ if(resultFont != null) {
+ graph.deny(element, G2D.HasFont);
+ graph.claim(element, G2D.HasFont, G2DUtils.createFont(graph, resultFont));
+ }
+
+ if(resultColor != null) {
+ graph.deny(element, G2D.HasColor);
+ graph.claim(element, G2D.HasColor, G2DUtils.createColor(graph, resultColor));
+ }
+ }
+ }
+ });
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.menu;\r
-\r
-import org.eclipse.jface.action.IContributionItem;\r
-import org.eclipse.jface.resource.JFaceResources;\r
-import org.eclipse.jface.resource.LocalResourceManager;\r
-import org.eclipse.jface.resource.ResourceManager;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.ToolBar;\r
-import org.eclipse.swt.widgets.ToolItem;\r
-import org.eclipse.ui.actions.CompoundContributionItem;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.project.IProject;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
-import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.validators.DoubleValidator;\r
-\r
-\r
-/**\r
- * Contribution for adding a text field to menu bar. The text field is used \r
- * to set the duration of one simulation step. This duration is different from\r
- * the step length the simulator uses. Simulator steps as many steps that fit into\r
- * the simulation duration determined in this field.\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class GameStepDurationContribution extends CompoundContributionItem {\r
-\r
- private TrackedText stepDuration;\r
- private int width = 40;\r
- private ToolItem ti;\r
- \r
- public static String COMMAND = "org.simantics.sysdyn.ui.gameStepDuration";\r
-\r
- public GameStepDurationContribution() {\r
- super(COMMAND);\r
- }\r
-\r
- @Override\r
- protected IContributionItem[] getContributionItems() {\r
- return new IContributionItem[0];\r
- }\r
-\r
- @Override\r
- public void fill(final ToolBar parent, final int index) {\r
- IProject project = SimanticsUI.peekProject();\r
- if (project == null)\r
- return;\r
-\r
- // Find game experiment\r
- IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
-\r
- IExperiment active = manager.getActiveExperiment();\r
- if (!(active instanceof SysdynGameExperimentBase))\r
- return;\r
-\r
- final SysdynGameExperimentBase game = (SysdynGameExperimentBase) active;\r
- \r
- // Create the text\r
- \r
- ti = new ToolItem(parent, SWT.SEPARATOR, index);\r
- ti.setText("Step Duration");\r
- ti.setToolTipText("Step Duration");\r
- \r
- ISessionContext context = SimanticsUI.getSessionContext();\r
- WidgetSupportImpl support = new WidgetSupportImpl(); // Dummy widget support for using tracked text\r
-\r
- stepDuration = new TrackedText(parent, support, SWT.BORDER);\r
- ResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources(), stepDuration.getWidget());\r
- stepDuration.setColorProvider(new SysdynBasicColorProvider(resourceManager));\r
- stepDuration.setInputValidator(new DoubleValidator());\r
- stepDuration.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.GameExperiment_stepDuration));\r
- stepDuration.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.GameExperiment_stepDuration));\r
- \r
- support.fireInput(context, game.getResource());\r
- \r
- ti.setWidth(width);\r
- ti.setControl(stepDuration.getWidget());\r
-\r
- }\r
-\r
- @Override\r
- public boolean isDynamic() {\r
- return true;\r
- }\r
-\r
+/*******************************************************************************
+ * 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.sysdyn.ui.menu;
+
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.resource.LocalResourceManager;
+import org.eclipse.jface.resource.ResourceManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.menus.WorkbenchWindowControlContribution;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.TrackedText;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.project.IProject;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;
+import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;
+import org.simantics.utils.ui.validators.DoubleValidator;
+
+
+/**
+ * Contribution for adding a text field to menu bar. The text field is used
+ * to set the duration of one simulation step. This duration is different from
+ * the step length the simulator uses. Simulator steps as many steps that fit into
+ * the simulation duration determined in this field.
+ *
+ * @author Teemu Lempinen, Miro Eklund
+ *
+ */
+public class GameStepDurationContribution extends WorkbenchWindowControlContribution {
+
+ private TrackedText stepDuration;
+
+ public static String COMMAND = "org.simantics.sysdyn.ui.gameStepDuration";
+
+ public GameStepDurationContribution() {
+ super(COMMAND);
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ if(!this.stepDuration.isDisposed()) {
+ if(!this.stepDuration.getWidget().isDisposed()) {
+ this.stepDuration.getWidget().dispose();
+ }
+ }
+ }
+
+ @Override
+ protected Control createControl(Composite parent2) {
+ IProject project = Simantics.peekProject();
+ if (project == null)
+ return null;
+
+ // Find game experiment
+ IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+
+ IExperiment active = manager.getActiveExperiment();
+ if (!(active instanceof SysdynGameExperimentBase))
+ return null;
+
+ final SysdynGameExperimentBase game = (SysdynGameExperimentBase) active;
+
+ ISessionContext context = Simantics.getSessionContext();
+ WidgetSupportImpl support = new WidgetSupportImpl(); // Dummy widget support for using tracked text
+
+
+ stepDuration = new TrackedText(parent2, support, SWT.BORDER);
+ ResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources(), stepDuration.getWidget());
+ stepDuration.setColorProvider(new SysdynBasicColorProvider(resourceManager));
+ stepDuration.setInputValidator(new DoubleValidator());
+ stepDuration.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.GameExperiment_stepDuration));
+ stepDuration.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.GameExperiment_stepDuration));
+
+ support.fireInput(context, game.getResource());
+
+ return(stepDuration.getWidget());
+ }
+
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.menu;\r
-\r
-import java.text.DecimalFormat;\r
-import java.text.DecimalFormatSymbols;\r
-\r
-import org.eclipse.jface.action.ToolBarContributionItem;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Slider;\r
-import org.eclipse.swt.widgets.ToolBar;\r
-import org.eclipse.swt.widgets.ToolItem;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Contribution to the main toolbar. PlaybackSliderContribution contains a slider\r
- * that can be used to control the time in a playback experiment\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class PlaybackSliderContribution extends ToolBarContributionItem {\r
-\r
- Runnable timeListener;\r
- SysdynPlaybackExperiment spe;\r
- Slider s;\r
- Double startTime, endTime;\r
- boolean ignoreChange = false;\r
-\r
- @Override\r
- public void fill(ToolBar parent, int index)\r
- {\r
- if (parent != null) {\r
-\r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) \r
- return;\r
- spe = (SysdynPlaybackExperiment)experiment;\r
-\r
- Double[] numbers = new Double[2];\r
- try {\r
- numbers = SimanticsUI.getSession().syncRequest(new Read<Double[]>() {\r
- @Override\r
- public Double[] perform(ReadGraph graph) throws DatabaseException {\r
- Double[] numbers = new Double[2];\r
- Resource model = spe.getModel();\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime);\r
- numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime);\r
- return numbers;\r
- }\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
-\r
- // Separator ToolItem can contain a composite. Add a composite with a slider to this item\r
- ToolItem ti = new ToolItem(parent, SWT.SEPARATOR);\r
-\r
- Composite composite = new Composite(parent, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().margins(3, SWT.DEFAULT).numColumns(2).applyTo(composite);\r
- GridDataFactory.fillDefaults().applyTo(composite);\r
-\r
- s = new Slider(composite, SWT.NONE);\r
- s.setMinimum(0);\r
- s.setMaximum(100);\r
- s.setIncrement(1);\r
- s.setPageIncrement(1);\r
- s.setThumb(1);\r
-\r
- final Label label = new Label(composite, SWT.NONE);\r
- GridDataFactory.fillDefaults().hint(70, SWT.DEFAULT).applyTo(label);\r
- label.setText("0.0");\r
-\r
- ti.setWidth(270);\r
- ti.setControl(composite);\r
-\r
- startTime = numbers[0];\r
- endTime = numbers[1];\r
- \r
- // Create a DesimalFormat for rounding the time\r
- final DecimalFormat format = new DecimalFormat();\r
- format.setMinimumFractionDigits(0);\r
- format.setMaximumFractionDigits(2);\r
- DecimalFormatSymbols symbols = new DecimalFormatSymbols();\r
- symbols.setDecimalSeparator('.');\r
- symbols.setGroupingSeparator(' ');\r
- format.setDecimalFormatSymbols(symbols);\r
- \r
- // Selection listener for the slider\r
- s.addSelectionListener(new SelectionListener() {\r
-\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- Slider s = (Slider)e.widget;\r
- Double time = s.getSelection() / 99.0 * (endTime - startTime) + startTime;\r
- spe.setTimeAndContinue(time);\r
- if(!label.isDisposed()) {\r
- label.setText(format.format(time));\r
- }\r
- }\r
-\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- }\r
- });\r
-\r
- if(timeListener != null) {\r
- spe.removeTimeListener(timeListener);\r
- }\r
-\r
- // Time listener for setting the time in the slider if the time is changed somewhere else\r
- timeListener = new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- s.getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- if(!startTime.equals(spe.getStartTime()) || !endTime.equals(spe.getEndTime())) {\r
- startTime = spe.getStartTime();\r
- endTime = spe.getEndTime();\r
- }\r
- int value = (int) Math.round(((spe.getTime() - startTime) / (endTime - startTime) * 99));\r
- s.setSelection(value);\r
- label.setText(format.format(spe.getTime()));\r
- }\r
- });\r
-\r
- }\r
-\r
- };\r
- spe.addTimeListener(timeListener);\r
- }\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- if(this.timeListener != null && spe != null) {\r
- spe.removeTimeListener(timeListener);\r
- this.timeListener = null;\r
- }\r
- super.dispose();\r
-\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.menu;
+
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Slider;
+import org.eclipse.ui.menus.WorkbenchWindowControlContribution;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.project.IProject;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;
+
+/**
+ * Contribution to the main toolbar. PlaybackSliderContribution contains a slider
+ * that can be used to control the time in a playback experiment
+ *
+ * @author Teemu Lempinen, Miro Eklund
+ *
+ */
+public class PlaybackSliderContribution extends WorkbenchWindowControlContribution {
+
+ private Runnable timeListener;
+ private SysdynPlaybackExperiment spe;
+ private Double startTime, endTime;
+ boolean ignoreChange = false;
+ private Slider slider;
+ private Composite composite;
+
+ public static String COMMAND = "org.simantics.sysdyn.ui.playbackSliderContribution";
+
+ public PlaybackSliderContribution() {
+ super(COMMAND);
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ if(this.timeListener != null && spe != null) {
+ spe.removeTimeListener(timeListener);
+ this.timeListener = null;
+ }
+ if(composite != null)
+ composite.dispose();
+ if(slider != null)
+ slider.dispose();
+ }
+
+ @Override
+ protected Control createControl(Composite parent) {
+
+ IProject project = Simantics.peekProject();
+ if (project == null)
+ return null;
+
+ // Find game experiment
+ IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment))
+ return null;
+
+ spe = (SysdynPlaybackExperiment)experiment;
+
+ Double[] numbers = new Double[2];
+ try {
+ numbers = Simantics.getSession().syncRequest(new Read<Double[]>() {
+ @Override
+ public Double[] perform(ReadGraph graph) throws DatabaseException {
+ Double[] numbers = new Double[2];
+ Resource model = spe.getModel();
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ numbers[0] = graph.getRelatedValue(model, sr.SysdynModel_startTime);
+ numbers[1] = graph.getRelatedValue(model, sr.SysdynModel_stopTime);
+ return numbers;
+ }
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+
+ ISessionContext context = Simantics.getSessionContext();
+ WidgetSupportImpl support = new WidgetSupportImpl();
+ composite = new Composite(parent, SWT.NONE);
+ composite.setLayout(parent.getLayout());
+
+ slider = new Slider(composite, SWT.NONE);
+ slider.setMinimum(0);
+ slider.setMaximum(100);
+ slider.setIncrement(1);
+ slider.setPageIncrement(1);
+ slider.setThumb(1);
+
+ final Label label = new Label(composite, SWT.LEFT);
+ label.setText("0.0");
+
+ support.fireInput(context, spe.getResource());
+
+ startTime = numbers[0];
+ endTime = numbers[1];
+
+ // Create a DesimalFormat for rounding the time
+ final DecimalFormat format = new DecimalFormat();
+ format.setMinimumFractionDigits(0);
+ format.setMaximumFractionDigits(2);
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+ symbols.setDecimalSeparator('.');
+ symbols.setGroupingSeparator(' ');
+ format.setDecimalFormatSymbols(symbols);
+
+ // Selection listener for the slider
+ slider.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ Slider s = (Slider)e.widget;
+ Double time = s.getSelection() / 99.0 * (endTime - startTime) + startTime;
+ spe.setTimeAndContinue(time);
+ if(!label.isDisposed()) {
+ label.setText(format.format(time));
+ }
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ });
+
+ if(timeListener != null) {
+ spe.removeTimeListener(timeListener);
+ }
+
+ // Time listener for setting the time in the slider if the time is changed somewhere else
+ timeListener = new Runnable() {
+
+ @Override
+ public void run() {
+ slider.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if(!startTime.equals(spe.getStartTime()) || !endTime.equals(spe.getEndTime())) {
+ startTime = spe.getStartTime();
+ endTime = spe.getEndTime();
+ }
+ int value = (int) Math.round(((spe.getTime() - startTime) / (endTime - startTime) * 99));
+ slider.setSelection(value);
+ label.setText(format.format(spe.getTime()));
+ }
+ });
+
+ }
+
+ };
+ spe.addTimeListener(timeListener);
+ return(composite);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.modelica;\r
-\r
-import java.util.HashSet;\r
-import java.util.Set;\r
-\r
-import org.eclipse.core.runtime.CoreException;\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.jface.operation.IRunnableContext;\r
-import org.eclipse.jface.text.Document;\r
-import org.eclipse.jface.text.IDocument;\r
-import org.eclipse.jface.text.PaintManager;\r
-import org.eclipse.jface.text.source.AnnotationModel;\r
-import org.eclipse.jface.text.source.AnnotationPainter;\r
-import org.eclipse.jface.text.source.DefaultCharacterPairMatcher;\r
-import org.eclipse.jface.text.source.IAnnotationModel;\r
-import org.eclipse.jface.text.source.MatchingCharacterPainter;\r
-import org.eclipse.swt.graphics.Color;\r
-import org.eclipse.swt.graphics.RGB;\r
-import org.eclipse.swt.widgets.Display;\r
-import org.eclipse.ui.IEditorInput;\r
-import org.eclipse.ui.IEditorSite;\r
-import org.eclipse.ui.PartInitException;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.editors.text.TextEditor;\r
-import org.eclipse.ui.texteditor.AbstractDocumentProvider;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.modelica.ModelicaManager;\r
-import org.simantics.sysdyn.modelica.ModelicaWriter;\r
-import org.simantics.sysdyn.representation.Configuration;\r
-import org.simantics.sysdyn.representation.IElement;\r
-import org.simantics.sysdyn.representation.LoadRepresentation;\r
-import org.simantics.sysdyn.representation.Module;\r
-import org.simantics.sysdyn.representation.ModuleType;\r
-import org.simantics.sysdyn.representation.utils.RepresentationUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.workbench.ResourceEditorInput;\r
-\r
-/**\r
- * Text editor for displaying Modelica code\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class SysdynModelicaEditor extends TextEditor {\r
-\r
- AnnotationModel annotationModel = new AnnotationModel();\r
- AnnotationPainter apainter;\r
- \r
- \r
- public void init(final IEditorSite site, final IEditorInput input) throws PartInitException {\r
- super.init(site, input);\r
- try {\r
- Configuration configuration =\r
- LoadRepresentation.loadConfiguration(SimanticsUI.getSession(), ((ResourceEditorInput)input).getResource());\r
- setPartName(configuration.getLabel());\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- }\r
- \r
- public SysdynModelicaEditor() {\r
- super();\r
- showOverviewRuler();\r
- setDocumentProvider(new AbstractDocumentProvider() {\r
-\r
- @Override\r
- protected IAnnotationModel createAnnotationModel(Object element)\r
- throws CoreException {\r
- return annotationModel;\r
- }\r
-\r
- @Override\r
- protected IDocument createDocument(Object element)\r
- throws CoreException {\r
- try {\r
- Configuration configuration =\r
- LoadRepresentation.loadConfiguration(SimanticsUI.getSession(), ((ResourceEditorInput)element).getResource());\r
- \r
- HashSet<Configuration> configurations = new HashSet<Configuration>();\r
- configurations.add(configuration);\r
- getConfigurations(configuration, configurations);\r
- \r
- String version = ModelicaManager.getDefaultOMVersion();\r
- return new Document(ModelicaWriter.write(configurations, \r
- configuration.getModel().getStartTime(), \r
- configuration.getModel().getStopTime(), \r
- configuration.getModel().getSimulationStepLength(), \r
- RepresentationUtils.isGameExperimentActive(), \r
- version));\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- throw new CoreException(STATUS_ERROR);\r
- } \r
- }\r
-\r
- @Override\r
- protected void doSaveDocument(IProgressMonitor monitor,\r
- Object element, IDocument document, boolean overwrite)\r
- throws CoreException {\r
- }\r
-\r
- @Override\r
- protected IRunnableContext getOperationRunner(\r
- IProgressMonitor monitor) {\r
- return PlatformUI.getWorkbench().getActiveWorkbenchWindow();\r
- }\r
- \r
- @Override\r
- public boolean isModifiable(Object element) {\r
- return false;\r
- }\r
- \r
- @Override\r
- public boolean isReadOnly(Object element) {\r
- return true;\r
- }\r
- \r
- }); \r
- \r
- setSourceViewerConfiguration(new ModelicaSourceViewerConfiguration());\r
- \r
- }\r
- \r
- private void getConfigurations(Configuration configuration, Set<Configuration> configurations) {\r
- for(IElement e : configuration.getElements()) {\r
- if(e instanceof Module) {\r
- ModuleType mt = ((Module) e).getType();\r
- configurations.add(mt.getConfiguration());\r
- getConfigurations(mt.getConfiguration(), configurations);\r
- }\r
- }\r
- }\r
- \r
- @Override\r
- protected void createActions() {\r
- super.createActions();\r
- \r
- PaintManager paintManager = new PaintManager(getSourceViewer());\r
- MatchingCharacterPainter matchingCharacterPainter = new MatchingCharacterPainter(getSourceViewer(),\r
- new DefaultCharacterPairMatcher( new char[] {'(', ')', '{', '}', '[', ']'} ));\r
- matchingCharacterPainter.setColor(new Color(Display.getCurrent(), new RGB(160, 160, 160)));\r
- paintManager.addPainter(matchingCharacterPainter);\r
- }\r
- \r
- \r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.modelica;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.jface.operation.IRunnableContext;
+import org.eclipse.jface.text.Document;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.PaintManager;
+import org.eclipse.jface.text.source.AnnotationModel;
+import org.eclipse.jface.text.source.AnnotationPainter;
+import org.eclipse.jface.text.source.DefaultCharacterPairMatcher;
+import org.eclipse.jface.text.source.IAnnotationModel;
+import org.eclipse.jface.text.source.MatchingCharacterPainter;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorSite;
+import org.eclipse.ui.PartInitException;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.editors.text.TextEditor;
+import org.eclipse.ui.texteditor.AbstractDocumentProvider;
+import org.simantics.Simantics;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.modelica.ModelicaManager;
+import org.simantics.sysdyn.modelica.ModelicaWriter;
+import org.simantics.sysdyn.representation.Configuration;
+import org.simantics.sysdyn.representation.IElement;
+import org.simantics.sysdyn.representation.LoadRepresentation;
+import org.simantics.sysdyn.representation.Module;
+import org.simantics.sysdyn.representation.ModuleType;
+import org.simantics.sysdyn.representation.utils.RepresentationUtils;
+import org.simantics.ui.workbench.ResourceEditorInput;
+
+/**
+ * Text editor for displaying Modelica code
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class SysdynModelicaEditor extends TextEditor {
+
+ AnnotationModel annotationModel = new AnnotationModel();
+ AnnotationPainter apainter;
+
+
+ public void init(final IEditorSite site, final IEditorInput input) throws PartInitException {
+ super.init(site, input);
+ try {
+ Configuration configuration =
+ LoadRepresentation.loadConfiguration(Simantics.getSession(), ((ResourceEditorInput)input).getResource());
+ setPartName(configuration.getLabel());
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public SysdynModelicaEditor() {
+ super();
+ showOverviewRuler();
+ setDocumentProvider(new AbstractDocumentProvider() {
+
+ @Override
+ protected IAnnotationModel createAnnotationModel(Object element)
+ throws CoreException {
+ return annotationModel;
+ }
+
+ @Override
+ protected IDocument createDocument(Object element)
+ throws CoreException {
+ try {
+ Configuration configuration =
+ LoadRepresentation.loadConfiguration(Simantics.getSession(), ((ResourceEditorInput)element).getResource());
+
+ HashSet<Configuration> configurations = new HashSet<Configuration>();
+ configurations.add(configuration);
+ getConfigurations(configuration, configurations);
+
+ String version = ModelicaManager.getDefaultOMVersion();
+ return new Document(ModelicaWriter.write(configurations,
+ configuration.getModel().getStartTime(),
+ configuration.getModel().getStopTime(),
+ configuration.getModel().getSimulationStepLength(),
+ RepresentationUtils.isGameExperimentActive(),
+ version));
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ throw new CoreException(STATUS_ERROR);
+ }
+ }
+
+ @Override
+ protected void doSaveDocument(IProgressMonitor monitor,
+ Object element, IDocument document, boolean overwrite)
+ throws CoreException {
+ }
+
+ @Override
+ protected IRunnableContext getOperationRunner(
+ IProgressMonitor monitor) {
+ return PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+ }
+
+ @Override
+ public boolean isModifiable(Object element) {
+ return false;
+ }
+
+ @Override
+ public boolean isReadOnly(Object element) {
+ return true;
+ }
+
+ });
+
+ setSourceViewerConfiguration(new ModelicaSourceViewerConfiguration());
+
+ }
+
+ private void getConfigurations(Configuration configuration, Set<Configuration> configurations) {
+ for(IElement e : configuration.getElements()) {
+ if(e instanceof Module) {
+ ModuleType mt = ((Module) e).getType();
+ configurations.add(mt.getConfiguration());
+ getConfigurations(mt.getConfiguration(), configurations);
+ }
+ }
+ }
+
+ @Override
+ protected void createActions() {
+ super.createActions();
+
+ PaintManager paintManager = new PaintManager(getSourceViewer());
+ MatchingCharacterPainter matchingCharacterPainter = new MatchingCharacterPainter(getSourceViewer(),
+ new DefaultCharacterPairMatcher( new char[] {'(', ')', '{', '}', '[', ']'} ));
+ matchingCharacterPainter.setColor(new Color(Display.getCurrent(), new RGB(160, 160, 160)));
+ paintManager.addPainter(matchingCharacterPainter);
+ }
+
+
+}
+
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.StructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.StyledText;\r
-import org.eclipse.swt.custom.VerifyKeyListener;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.MouseEvent;\r
-import org.eclipse.swt.events.MouseListener;\r
-import org.eclipse.swt.events.VerifyEvent;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.eclipse.swt.widgets.TableItem;\r
-import org.eclipse.ui.IWorkbenchPartReference;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.platform.PropertyPageView;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
-import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.AsyncReadGraph;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.VirtualGraph;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.request.WriteResultRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.AsyncListener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.db.service.VirtualGraphSupport;\r
-import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynModel;\r
-import org.simantics.sysdyn.manager.SysdynModelManager;\r
-import org.simantics.sysdyn.ui.properties.widgets.ArrayExpressionCombo;\r
-import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes;\r
-import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes.ExpressionType;\r
-import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget;\r
-import org.simantics.sysdyn.ui.properties.widgets.IsOutputWidget;\r
-import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget;\r
-import org.simantics.sysdyn.ui.properties.widgets.arrays.NameAndArrayRangeModifyListener;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.DelayExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionComposite;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameInputValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Tab for displaying equation information of a variable\r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class EquationTab extends AdjustableTab implements Widget {\r
-\r
- private TrackedCombo expressionTypeCombo, unitCombo, arrayEquationCombo;\r
- private ShortcutTabWidget shortcutTabWidget;\r
- private ExpressionWidget expressionWidget;\r
- private org.eclipse.ui.IPartListener2 focusLostListener; \r
- private IWorkbenchSite site;\r
- private Button deleteExpression, newExpression;\r
- private WidgetSupportImpl support;\r
- private ExpressionComposite expressionComposite;\r
- private final WidgetSupportImpl expressionSupport = new WidgetSupportImpl();\r
- private Composite nameComposite;\r
- private Composite TypeAndUnit;\r
- private Label typeLabel;\r
- private Label unitLabel;\r
- private IsOutputWidget isOutput;\r
-\r
- public EquationTab(Object input) {\r
- super(input);\r
- }\r
-\r
- @Override\r
- public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport _support) {\r
- _support.register(this);\r
- setSupport();\r
- this.site = site;\r
- super.createControls(body, site, context, _support);\r
- }\r
- \r
- @Override\r
- protected void createControlLayoutHorizontal(boolean wideScreen) {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
-\r
- GridLayoutFactory.fillDefaults().numColumns(wideScreen ? 4 : 3).applyTo(nameComposite);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(nameComposite);\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).hint(280, SWT.DEFAULT).applyTo(arrayEquationCombo.getWidget());\r
- GridDataFactory.fillDefaults().applyTo(deleteExpression.getWidget());\r
- GridDataFactory.fillDefaults().applyTo(newExpression.getWidget());\r
-\r
- GridDataFactory.fillDefaults().span(1, wideScreen ? 2 : 3).grab(false, true).hint(250, SWT.DEFAULT).applyTo(shortcutTabWidget.getWidget());\r
-\r
- GridDataFactory.fillDefaults().span(wideScreen ? 1 : 3, 1).grab(true, false).applyTo(TypeAndUnit);\r
- GridLayoutFactory.fillDefaults().numColumns(5).applyTo(TypeAndUnit);\r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(typeLabel);\r
- GridDataFactory.fillDefaults().applyTo(expressionTypeCombo.getWidget());\r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(unitLabel);\r
- GridDataFactory.fillDefaults().grab(true, false).hint(160, SWT.DEFAULT).applyTo(unitCombo.getWidget());\r
- GridDataFactory.fillDefaults().applyTo(isOutput.getWidget());\r
-\r
- GridDataFactory.fillDefaults().span(wideScreen ? 4 : 3, 1).grab(true, true).applyTo(expressionComposite);\r
- }\r
- \r
- @Override\r
- protected void createControlLayoutVertical() {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
- \r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(nameComposite);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(nameComposite);\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(arrayEquationCombo.getWidget());\r
- GridDataFactory.fillDefaults().applyTo(deleteExpression.getWidget());\r
- GridDataFactory.fillDefaults().applyTo(newExpression.getWidget());\r
-\r
- GridDataFactory.fillDefaults().span(3, 1).applyTo(TypeAndUnit);\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(TypeAndUnit);\r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(typeLabel);\r
- GridDataFactory.fillDefaults().applyTo(expressionTypeCombo.getWidget());\r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(unitLabel);\r
- GridDataFactory.fillDefaults().grab(true, false).hint(160, SWT.DEFAULT).applyTo(unitCombo.getWidget());\r
- GridDataFactory.fillDefaults().span(3, 1).align(SWT.END, SWT.CENTER).applyTo(isOutput.getWidget());\r
-\r
- GridDataFactory.fillDefaults().span(3, 1).grab(true, true).hint(SWT.DEFAULT, 250).applyTo(expressionComposite);\r
- \r
- GridDataFactory.fillDefaults().span(3, 1).grab(true, true).hint(SWT.DEFAULT, 300).applyTo(shortcutTabWidget.getWidget());\r
- }\r
- \r
- @Override\r
- protected void createAndAddControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport _support) {\r
- // Composite for the whole tab\r
- Composite composite = new Composite(body, SWT.NONE);\r
- this.composite = composite;\r
- \r
- // Composite holding name controls and controls for adding and removing expressions\r
- nameComposite = new Composite(composite, SWT.NONE);\r
- arrayEquationCombo = new ArrayExpressionCombo(nameComposite, support, SWT.DROP_DOWN | SWT.BORDER);\r
- arrayEquationCombo.setInputValidator(new VariableNameInputValidator(support));\r
- arrayEquationCombo.addModifyListener(new NameAndArrayRangeModifyListener(support, expressionWidget, (ArrayExpressionCombo)arrayEquationCombo));\r
- deleteExpression = new Button(nameComposite, support, SWT.NONE);\r
- deleteExpression.setText("Delete");\r
- newExpression = new Button(nameComposite, support, SWT.NONE);\r
- newExpression.setText("New");\r
- \r
- // Shortcut widget. Tabular widget containing tabs for functions and connected variables\r
- shortcutTabWidget = new ShortcutTabWidget(composite, support, SWT.NONE);\r
- \r
- TypeAndUnit = new Composite(nameComposite, SWT.NONE);\r
- typeLabel = new Label(TypeAndUnit, SWT.SINGLE );\r
- typeLabel.setText("Type:");\r
- expressionTypeCombo = new TrackedCombo(TypeAndUnit, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
- unitLabel = new Label(TypeAndUnit, SWT.SINGLE );\r
- unitLabel.setText("Unit:");\r
- unitCombo = new TrackedCombo(TypeAndUnit, support, SWT.DROP_DOWN | SWT.BORDER);\r
- isOutput = new IsOutputWidget(TypeAndUnit, support, SWT.NULL);\r
- \r
- // The actual expression\r
- expressionComposite = new ExpressionComposite(nameComposite, SWT.NONE);\r
- expressionWidget = new ExpressionWidget(expressionComposite, expressionSupport, SWT.NONE);\r
- expressionWidget.setVariableTable(shortcutTabWidget.getVariableTable());\r
-\r
- addListeners(context);\r
- }\r
- \r
- private void setSupport() {\r
- support = new WidgetSupportImpl() {\r
- \r
- @Override\r
- public void fireInput(ISessionContext context, Object input) {\r
- final Variable var = AdaptionUtils.adaptToSingle(input, Variable.class);\r
- if(var != null) {\r
- Resource r;\r
- try {\r
- r = context.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph)\r
- throws DatabaseException {\r
- return var.getRepresents(graph);\r
- }\r
- });\r
- input = new StructuredSelection(r);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
- \r
- super.fireInput(context, input);\r
- }\r
- };\r
- }\r
- \r
- @Override\r
- public void setInput(ISessionContext context, final Object input) {\r
- support.fireInput(context, input);\r
- \r
- final Variable var = AdaptionUtils.adaptToSingle(input, Variable.class);\r
- final Resource variable;\r
- \r
- // Find variable resource either from Variable var or from input\r
- if(var != null)\r
- try {\r
- variable = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return var.getRepresents(graph);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- return;\r
- }\r
- else\r
- variable = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- \r
- if(var == null && variable == null)\r
- return;\r
- \r
- \r
- Resource expression = null;\r
- try {\r
- expression = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return getActiveExpression(graph, variable);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- // The variable has no expressions -> creating a new ordered set expressions and the active expression\r
- if(expression == null && variable != null) {\r
- try {\r
- expression = SimanticsUI.getSession().syncRequest(new WriteResultRequest<Resource>() {\r
-\r
- @Override\r
- public Resource perform(WriteGraph graph)\r
- throws DatabaseException {\r
- if(!graph.hasStatement(variable)) {\r
- /* Trying to create empty experiment for removed variable due to \r
- * async setInput\r
- */\r
- return null; \r
- }\r
- \r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource expressions = ListUtils.create(graph, Collections.<Resource>emptyList());\r
- graph.claim(variable, sr.Variable_expressionList, expressions);\r
- final Resource expression = graph.newResource();\r
-\r
- if(graph.isInstanceOf(variable, sr.Auxiliary) ||\r
- graph.isInstanceOf(variable, sr.Valve)) {\r
- graph.claim(expression, l0.InstanceOf, null, sr.NormalExpression);\r
- graph.claimLiteral(expression, sr.Expression_equation, "");\r
- }\r
- else if(graph.isInstanceOf(variable, sr.Stock)) {\r
- graph.claim(expression, l0.InstanceOf, null, sr.StockExpression);\r
- graph.claimLiteral(expression, sr.StockExpression_initialEquation, "");\r
- }\r
- ArrayList<Resource> addition = new ArrayList<Resource>(1);\r
- addition.add(expression);\r
- ListUtils.insertBack(graph, expressions, addition);\r
-\r
- graph.claim(variable, l0.ConsistsOf, expression);\r
-\r
- VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
- final Session session = graph.getSession();\r
- session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
- session.asyncRequest(new WriteRequest(runtime) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
- graph.deny(variable, sr.IndependentVariable_activeExpression);\r
- graph.claim(variable, sr.IndependentVariable_activeExpression, expression);\r
- }\r
- }\r
- );\r
- }\r
- });\r
- return expression;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- if(expression == null)\r
- return;\r
- }\r
-\r
- // Now the variable should have an expression\r
- SimanticsUI.getSession().asyncRequest(new Read<Pair<Boolean, Boolean>>() {\r
-\r
- /**\r
- * Find out if user can add a new expression or delete the current expression\r
- */\r
- @Override\r
- public Pair<Boolean, Boolean> perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
- if(expressions == null) {\r
- return new Pair<Boolean, Boolean>(false, false);\r
- }\r
- List<Resource> expressionList = ListUtils.toList(graph, expressions);\r
- if(expressionList.isEmpty()) {\r
- return new Pair<Boolean, Boolean>(false, false);\r
- }\r
-\r
- boolean canAdd = true;\r
- boolean canDelete = false;\r
- // If there are multiple expressions, one can be removed\r
- if(expressionList.size() > 1)\r
- canDelete = true;\r
- String defaultRange = ArrayExpressionCombo.getDefaultRange(graph, variable);\r
-\r
- /* If the variable is an array variable, a range has been set to all expressions and none of\r
- * the ranges is the default range, an expression can be added\r
- */ \r
- for(Resource expression : expressionList) {\r
- String range = graph.getPossibleRelatedValue(expression, sr.Expression_arrayRange);\r
- if(range == null || range.equals("") || range.equals(defaultRange)) {\r
- canAdd = false;\r
- break;\r
- }\r
- }\r
- return new Pair<Boolean, Boolean>(canAdd, canDelete);\r
- }\r
- }, new AsyncListener<Pair<Boolean, Boolean>>() {\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph,\r
- final Pair<Boolean, Boolean> result) {\r
- newExpression.getWidget().getDisplay().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- if(!newExpression.getWidget().isDisposed())\r
- newExpression.getWidget().setEnabled(result.first);\r
- if(!deleteExpression.getWidget().isDisposed())\r
- deleteExpression.getWidget().setEnabled(result.second); \r
- }\r
- });\r
-\r
- }\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph, Throwable throwable) {\r
- throwable.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return newExpression.getWidget().isDisposed() || deleteExpression.getWidget().isDisposed();\r
- }\r
- });\r
- \r
- // Set input to widgets using expressionSupport\r
- StructuredSelection ss = new StructuredSelection(new ExpressionWidgetInput(var, expression));\r
- expressionSupport.fireInput(context, ss);\r
- }\r
-\r
- /**\r
- * Adds listeners to widgets in this tab\r
- * \r
- * @param context ISessionContext\r
- */\r
- private void addListeners(ISessionContext context) {\r
-\r
- // Validate expression fields when a dependency has been added or removed\r
- shortcutTabWidget.addDependencyListener(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- expressionWidget.validateFields();\r
- }\r
- });\r
- \r
- // Deletes a selected expression\r
- deleteExpression.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- @Override\r
- public void apply(WriteGraph graph, final Resource input)\r
- throws DatabaseException {\r
-\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- // Currently active expression should be located in (Model sr.HasActiveExpression expression)\r
- Resource activeExpression = graph.getPossibleObject(input, sr.IndependentVariable_activeExpression);\r
- if(activeExpression == null)\r
- return;\r
-\r
- Resource expressionList = graph.getPossibleObject(input, sr.Variable_expressionList);\r
-\r
- List<Resource> list = ListUtils.toList(graph, expressionList);\r
- if(list.size() <= 1)\r
- return;\r
-\r
- // Get the previous expression in expression list to be activated\r
- int index = list.indexOf(activeExpression);\r
- \r
- ListUtils.removeElement(graph, expressionList, activeExpression);\r
- graph.deny(input, l0.ConsistsOf, activeExpression);\r
- \r
- final Resource newActive = index == 0 ? list.get(1) : list.get(index - 1);\r
-\r
- // Set newActive as active in virtual graph\r
- VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
- final Session session = graph.getSession();\r
- session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
- session.asyncRequest(new WriteRequest(runtime) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(graph.hasStatement(input, sr.IndependentVariable_activeExpression))\r
- graph.deny(input, sr.IndependentVariable_activeExpression);\r
- graph.claim(input, sr.IndependentVariable_activeExpression, newActive);\r
- }\r
- }\r
- );\r
- }\r
- });\r
- Layer0Utils.addCommentMetadata(graph, "Deleted Expression " + activeExpression + " from " + graph.getPossibleRelatedValue2(input, Layer0.getInstance(graph).HasName, Bindings.STRING));\r
- }\r
- });\r
-\r
- // Creates a new expression\r
- newExpression.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource input)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
-\r
- Resource expressions = graph.getPossibleObject(input, sr.Variable_expressionList);\r
- if(expressions == null) {\r
- return;\r
- }\r
- // Get the currently active expression\r
- Resource activeExpression = graph.getPossibleObject(input, sr.IndependentVariable_activeExpression);\r
- Resource newExpression = graph.newResource();\r
- if(activeExpression != null) {\r
- // Create a new expression based on the old expression\r
- graph.claim(newExpression, l0.InstanceOf, graph.getSingleObject(activeExpression, l0.InstanceOf));\r
- if(graph.isInstanceOf(newExpression, sr.StockExpression)) {\r
- graph.claimLiteral(newExpression, sr.StockExpression_initialEquation, "");\r
- Layer0Utils.addCommentMetadata(graph, "Created new Stock Expression " + newExpression + " for " + graph.getPossibleRelatedValue2(input, Layer0.getInstance(graph).HasName, Bindings.STRING));\r
- }\r
- } else {\r
- // If there was no active expression, create a normal expression\r
- graph.claim(newExpression, l0.InstanceOf, sr.NormalExpression);\r
- graph.claimLiteral(newExpression, sr.Expression_equation, "");\r
- Layer0Utils.addCommentMetadata(graph, "Created new Normal Expression " + newExpression + " for " + graph.getPossibleRelatedValue2(input, Layer0.getInstance(graph).HasName, Bindings.STRING));\r
- }\r
- ArrayList<Resource> addition = new ArrayList<Resource>(1);\r
- addition.add(newExpression);\r
- ListUtils.insertBack(graph, expressions, addition);\r
- graph.claim(input, l0.ConsistsOf, newExpression);\r
- }\r
- });\r
-\r
- // Item factory for expression type combo\r
- expressionTypeCombo.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
-\r
- @Override\r
- public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
-\r
- Map<String, Object> map = new HashMap<String, Object>();\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- // Select expression types based on the type of the variable\r
- final ExpressionType[] expressionTypes;\r
- if(graph.isInstanceOf(input, sr.Auxiliary))\r
- expressionTypes = ExpressionTypes.auxiliaryExpressions;\r
- else if(graph.isInstanceOf(input, sr.Stock))\r
- expressionTypes = ExpressionTypes.stockExpressions;\r
- else if(graph.isInstanceOf(input, sr.Valve))\r
- expressionTypes = ExpressionTypes.valveExpressions;\r
- else\r
- expressionTypes = new ExpressionType[] {};\r
-\r
- for(ExpressionType et : expressionTypes) {\r
- map.put(et.toString(), et);\r
- }\r
- return map;\r
- }\r
- });\r
-\r
- // Initial selection to the combo from active expression\r
- expressionTypeCombo.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
- Resource activeExpression = getActiveExpression(graph, input);\r
- if(activeExpression == null)\r
- return null;\r
- return ExpressionTypes.getExpressionType(graph, activeExpression).toString();\r
- }\r
- });\r
-\r
- // Modify listener for selecting expression type\r
- expressionTypeCombo.addModifyListener(new TextModifyListener() {\r
-\r
- @Override\r
- public void modifyText(TrackedModifyEvent e) {\r
- expressionWidget.displayExpression(e.getText(), false);\r
- expressionWidget.save(); \r
- }\r
- });\r
-\r
-\r
- // Add all units used in the model to the unit combo\r
- unitCombo.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
-\r
- @Override\r
- public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
- Map<String, Object> map = new HashMap<String, Object>();\r
-\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource model = graph.getPossibleObject(input, l0.PartOf);\r
- if (model != null) {\r
- Collection<Resource> variables = graph.getObjects(model, l0.ConsistsOf);\r
- for(Resource v : variables) {\r
- Object unit = graph.getPossibleRelatedValue(v, sr.Variable_unit);\r
- if (unit != null && !map.keySet().contains(unit)) {\r
- map.put((String)unit, (String)unit);\r
-\r
- }\r
- }\r
- }\r
- return map;\r
- }\r
- });\r
- \r
- // Set initial selection of unit combo\r
- unitCombo.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
- String unit = graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).Variable_unit);\r
- if(unit == null)\r
- return "";\r
- else \r
- return unit;\r
- }\r
- });\r
-\r
- // Modify unit\r
- unitCombo.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
-\r
- @Override\r
- public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {\r
- graph.denyValue(input, SysdynResource.getInstance(graph).Variable_unit);\r
- graph.claimLiteral(input, SysdynResource.getInstance(graph).Variable_unit, text);\r
- \r
- Resource conf = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);\r
- SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());\r
- SysdynModel sm = smm.getModel(graph, conf);\r
- sm.getMapping().domainModified(input);\r
- sm.update(graph);\r
- }\r
- });\r
-\r
-\r
- /*\r
- * Double-clicking something in shortcut tab widget\r
- * writes the clicked element into expression widget,\r
- * sets focus on expression widget and validates its fields\r
- */\r
- shortcutTabWidget.addMouseListener(new MouseListener(){\r
-\r
- @Override\r
- public void mouseDoubleClick(MouseEvent e) {\r
- Table table = (Table)e.widget;\r
- TableItem item = table.getItem(new Point(e.x, e.y));\r
- if(item != null) {\r
- final String var = (String)item.getData();\r
- table.getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- if(expressionWidget!= null) {\r
- expressionWidget.getExpression().focus();\r
- expressionWidget.getExpression().replaceSelection(var);\r
- expressionWidget.validateFieldsTimed();\r
- }\r
- }\r
- });\r
- }\r
- }\r
-\r
- @Override\r
- public void mouseDown(MouseEvent e) {\r
- expressionWidget.getExpression().focus();\r
- }\r
-\r
- @Override\r
- public void mouseUp(MouseEvent e) {\r
- }\r
-\r
- });\r
-\r
- /* Modifying an expression sets a timed validation. The timer is\r
- * reset after each modification \r
- */ \r
- expressionWidget.addModifyListener(new ModifyListener() {\r
-\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- expressionWidget.validateFieldsTimed();\r
- }\r
- });\r
- \r
- // Pressing return without shift key triggers saving the expression\r
- expressionWidget.addVerifyKeyListener(new VerifyKeyListener() {\r
-\r
- @Override\r
- public void verifyKey(VerifyEvent event) {\r
- // Check if some of the expression fields has active completion assistant\r
- boolean isAnyAssistSessionActive = false;\r
- for (int i = 0; i < expressionWidget.getExpression().getExpressionFields().size(); ++i) {\r
- if (expressionWidget.getExpression().getExpressionFields().get(i).isAssistSessionActive()) {\r
- isAnyAssistSessionActive = true;\r
- break;\r
- }\r
- }\r
- if(event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR) {\r
- if (!isAnyAssistSessionActive) {\r
- if((event.stateMask & SWT.SHIFT) == 0) {\r
- event.doit = false;\r
- ((StyledText)event.widget).getParent().forceFocus();\r
- expressionWidget.save();\r
- }\r
- } else {\r
- // When a proposed expression is selected with enter, fields are validated.\r
- expressionWidget.validateFieldsTimed();\r
- }\r
- }\r
- }\r
- });\r
- \r
- // Triggers save when equation tab loses focus\r
- if(focusLostListener == null) {\r
- focusLostListener = new org.eclipse.ui.IPartListener2()\r
- {\r
- @Override\r
- public void partInputChanged(IWorkbenchPartReference partRef) {}\r
- @Override\r
- public void partVisible(IWorkbenchPartReference partRef) {}\r
- @Override\r
- public void partHidden(IWorkbenchPartReference partRef) {}\r
- @Override\r
- public void partOpened(IWorkbenchPartReference partRef) {}\r
- @Override\r
- public void partDeactivated(IWorkbenchPartReference partRef)\r
- {\r
- if(partRef.getPart(false) instanceof PropertyPageView) {\r
- PropertyPageView ppv = (PropertyPageView)partRef.getPart(false);\r
- if(ppv.getCurrentPage() instanceof SysdynPropertyPage) {\r
- // Save expressions\r
- if(expressionWidget != null) {\r
- expressionWidget.save();\r
- }\r
-// site.getPage().removePartListener(this);\r
- }\r
- }\r
- }\r
- @Override\r
- public void partClosed(IWorkbenchPartReference partRef) {}\r
- @Override\r
- public void partBroughtToTop(IWorkbenchPartReference partRef) {}\r
- @Override\r
- public void partActivated(IWorkbenchPartReference partRef) {}\r
- };\r
- site.getPage().addPartListener(focusLostListener);\r
- }\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- if(expressionWidget != null && !(expressionWidget.getExpression() instanceof DelayExpression)) {\r
- // For delay expression this doesn't work, \r
- // but it doesn't matter since the saving is succeeded elsewhere.\r
- expressionWidget.save();\r
- }\r
- if(focusLostListener != null && site != null)\r
- site.getPage().removePartListener(focusLostListener);\r
- super.dispose();\r
- if(expressionComposite != null && !expressionComposite.isDisposed())\r
- expressionComposite.dispose();\r
- }\r
-\r
- /**\r
- * Get the currently active expression of the first expression in expression list if\r
- * no expression has been set to active\r
- * \r
- * @param graph ReadGraph\r
- * @param variable Variable\r
- * @return active expression or the first expression in variables expression list\r
- * @throws DatabaseException\r
- */\r
- private Resource getActiveExpression(ReadGraph graph, Resource variable) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource expression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression);\r
- if(expression == null) {\r
- Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
- if(expressions == null) {\r
- return null;\r
- }\r
- List<Resource> expressionList = ListUtils.toList(graph, expressions);\r
- if(expressionList.isEmpty()) {\r
- return null;\r
- }\r
- expression = expressionList.get(0);\r
- }\r
- return expression;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2012, 2014 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.sysdyn.ui.properties;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.custom.VerifyKeyListener;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.events.VerifyEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.ui.IWorkbenchPartReference;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.platform.PropertyPageView;
+import org.simantics.browsing.ui.swt.widgets.Button;
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.VirtualGraph;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.request.WriteResultRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.AsyncListener;
+import org.simantics.db.request.Read;
+import org.simantics.db.service.VirtualGraphSupport;
+import org.simantics.jfreechart.chart.properties.AdjustableTab;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynModel;
+import org.simantics.sysdyn.manager.SysdynModelManager;
+import org.simantics.sysdyn.ui.properties.widgets.ArrayExpressionCombo;
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes;
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes.ExpressionType;
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionWidget;
+import org.simantics.sysdyn.ui.properties.widgets.IsOutputWidget;
+import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget;
+import org.simantics.sysdyn.ui.properties.widgets.arrays.NameAndArrayRangeModifyListener;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.DelayExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionComposite;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput;
+import org.simantics.sysdyn.ui.properties.widgets.factories.VariableNameInputValidator;
+import org.simantics.utils.datastructures.Pair;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Tab for displaying equation information of a variable
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class EquationTab extends AdjustableTab implements Widget {
+
+ private TrackedCombo expressionTypeCombo, unitCombo, arrayEquationCombo;
+ private ShortcutTabWidget shortcutTabWidget;
+ private ExpressionWidget expressionWidget;
+ private org.eclipse.ui.IPartListener2 focusLostListener;
+ private IWorkbenchSite site;
+ private Button deleteExpression, newExpression;
+ private WidgetSupportImpl support;
+ private ExpressionComposite expressionComposite;
+ private final WidgetSupportImpl expressionSupport = new WidgetSupportImpl();
+ private Composite nameComposite;
+ private Composite TypeAndUnit;
+ private Label typeLabel;
+ private Label unitLabel;
+ private IsOutputWidget isOutput;
+
+ public EquationTab(Object input) {
+ super(input);
+ }
+
+ @Override
+ public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport _support) {
+ _support.register(this);
+ setSupport();
+ this.site = site;
+ super.createControls(body, site, context, _support);
+ }
+
+ @Override
+ protected void createControlLayoutHorizontal(boolean wideScreen) {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);
+
+ GridLayoutFactory.fillDefaults().numColumns(wideScreen ? 4 : 3).applyTo(nameComposite);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(nameComposite);
+
+ GridDataFactory.fillDefaults().grab(true, false).hint(280, SWT.DEFAULT).applyTo(arrayEquationCombo.getWidget());
+ GridDataFactory.fillDefaults().applyTo(deleteExpression.getWidget());
+ GridDataFactory.fillDefaults().applyTo(newExpression.getWidget());
+
+ GridDataFactory.fillDefaults().span(1, wideScreen ? 2 : 3).grab(false, true).hint(250, SWT.DEFAULT).applyTo(shortcutTabWidget.getWidget());
+
+ GridDataFactory.fillDefaults().span(wideScreen ? 1 : 3, 1).grab(true, false).applyTo(TypeAndUnit);
+ GridLayoutFactory.fillDefaults().numColumns(5).applyTo(TypeAndUnit);
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(typeLabel);
+ GridDataFactory.fillDefaults().applyTo(expressionTypeCombo.getWidget());
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(unitLabel);
+ GridDataFactory.fillDefaults().grab(true, false).hint(160, SWT.DEFAULT).applyTo(unitCombo.getWidget());
+ GridDataFactory.fillDefaults().applyTo(isOutput.getWidget());
+
+ GridDataFactory.fillDefaults().span(wideScreen ? 4 : 3, 1).grab(true, true).applyTo(expressionComposite);
+ }
+
+ @Override
+ protected void createControlLayoutVertical() {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);
+
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(nameComposite);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(nameComposite);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(arrayEquationCombo.getWidget());
+ GridDataFactory.fillDefaults().applyTo(deleteExpression.getWidget());
+ GridDataFactory.fillDefaults().applyTo(newExpression.getWidget());
+
+ GridDataFactory.fillDefaults().span(3, 1).applyTo(TypeAndUnit);
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(TypeAndUnit);
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(typeLabel);
+ GridDataFactory.fillDefaults().applyTo(expressionTypeCombo.getWidget());
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(unitLabel);
+ GridDataFactory.fillDefaults().grab(true, false).hint(160, SWT.DEFAULT).applyTo(unitCombo.getWidget());
+ GridDataFactory.fillDefaults().span(3, 1).align(SWT.END, SWT.CENTER).applyTo(isOutput.getWidget());
+
+ GridDataFactory.fillDefaults().span(3, 1).grab(true, true).hint(SWT.DEFAULT, 250).applyTo(expressionComposite);
+
+ GridDataFactory.fillDefaults().span(3, 1).grab(true, true).hint(SWT.DEFAULT, 300).applyTo(shortcutTabWidget.getWidget());
+ }
+
+ @Override
+ protected void createAndAddControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport _support) {
+ // Composite for the whole tab
+ Composite composite = new Composite(body, SWT.NONE);
+ this.composite = composite;
+
+ // Composite holding name controls and controls for adding and removing expressions
+ nameComposite = new Composite(composite, SWT.NONE);
+ arrayEquationCombo = new ArrayExpressionCombo(nameComposite, support, SWT.DROP_DOWN | SWT.BORDER);
+ arrayEquationCombo.setInputValidator(new VariableNameInputValidator(support));
+ arrayEquationCombo.addModifyListener(new NameAndArrayRangeModifyListener(support, expressionWidget, (ArrayExpressionCombo)arrayEquationCombo));
+ deleteExpression = new Button(nameComposite, support, SWT.NONE);
+ deleteExpression.setText("Delete");
+ newExpression = new Button(nameComposite, support, SWT.NONE);
+ newExpression.setText("New");
+
+ // Shortcut widget. Tabular widget containing tabs for functions and connected variables
+ shortcutTabWidget = new ShortcutTabWidget(composite, support, SWT.NONE);
+
+ TypeAndUnit = new Composite(nameComposite, SWT.NONE);
+ typeLabel = new Label(TypeAndUnit, SWT.SINGLE );
+ typeLabel.setText("Type:");
+ expressionTypeCombo = new TrackedCombo(TypeAndUnit, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);
+ unitLabel = new Label(TypeAndUnit, SWT.SINGLE );
+ unitLabel.setText("Unit:");
+ unitCombo = new TrackedCombo(TypeAndUnit, support, SWT.DROP_DOWN | SWT.BORDER);
+ isOutput = new IsOutputWidget(TypeAndUnit, support, SWT.NULL);
+
+ // The actual expression
+ expressionComposite = new ExpressionComposite(nameComposite, SWT.NONE);
+ expressionWidget = new ExpressionWidget(expressionComposite, expressionSupport, SWT.NONE);
+ expressionWidget.setVariableTable(shortcutTabWidget.getVariableTable());
+
+ addListeners(context);
+ }
+
+ private void setSupport() {
+ support = new WidgetSupportImpl() {
+
+ @Override
+ public void fireInput(ISessionContext context, Object input) {
+ final Variable var = AdaptionUtils.adaptToSingle(input, Variable.class);
+ if(var != null) {
+ Resource r;
+ try {
+ r = context.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph)
+ throws DatabaseException {
+ return var.getRepresents(graph);
+ }
+ });
+ input = new StructuredSelection(r);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ super.fireInput(context, input);
+ }
+ };
+ }
+
+ @Override
+ public void setInput(ISessionContext context, final Object input) {
+ support.fireInput(context, input);
+
+ final Variable var = AdaptionUtils.adaptToSingle(input, Variable.class);
+ final Resource variable;
+
+ // Find variable resource either from Variable var or from input
+ if(var != null)
+ try {
+ variable = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return var.getRepresents(graph);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ return;
+ }
+ else
+ variable = AdaptionUtils.adaptToSingle(input, Resource.class);
+
+ if(var == null && variable == null)
+ return;
+
+
+ Resource expression = null;
+ try {
+ expression = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return getActiveExpression(graph, variable);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ // The variable has no expressions -> creating a new ordered set expressions and the active expression
+ if(expression == null && variable != null) {
+ try {
+ expression = Simantics.getSession().syncRequest(new WriteResultRequest<Resource>() {
+
+ @Override
+ public Resource perform(WriteGraph graph)
+ throws DatabaseException {
+ if(!graph.hasStatement(variable)) {
+ /* Trying to create empty experiment for removed variable due to
+ * async setInput
+ */
+ return null;
+ }
+
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource expressions = ListUtils.create(graph, Collections.<Resource>emptyList());
+ graph.claim(variable, sr.Variable_expressionList, expressions);
+ final Resource expression = graph.newResource();
+
+ if(graph.isInstanceOf(variable, sr.Auxiliary) ||
+ graph.isInstanceOf(variable, sr.Valve)) {
+ graph.claim(expression, l0.InstanceOf, null, sr.NormalExpression);
+ graph.claimLiteral(expression, sr.Expression_equation, "");
+ }
+ else if(graph.isInstanceOf(variable, sr.Stock)) {
+ graph.claim(expression, l0.InstanceOf, null, sr.StockExpression);
+ graph.claimLiteral(expression, sr.StockExpression_initialEquation, "");
+ }
+ ArrayList<Resource> addition = new ArrayList<Resource>(1);
+ addition.add(expression);
+ ListUtils.insertBack(graph, expressions, addition);
+
+ graph.claim(variable, l0.ConsistsOf, expression);
+
+ VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
+ final Session session = graph.getSession();
+ session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ VirtualGraph runtime = graph.getService(VirtualGraph.class);
+ session.asyncRequest(new WriteRequest(runtime) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))
+ graph.deny(variable, sr.IndependentVariable_activeExpression);
+ graph.claim(variable, sr.IndependentVariable_activeExpression, expression);
+ }
+ }
+ );
+ }
+ });
+ return expression;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ if(expression == null)
+ return;
+ }
+
+ // Now the variable should have an expression
+ Simantics.getSession().asyncRequest(new Read<Pair<Boolean, Boolean>>() {
+
+ /**
+ * Find out if user can add a new expression or delete the current expression
+ */
+ @Override
+ public Pair<Boolean, Boolean> perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);
+ if(expressions == null) {
+ return new Pair<Boolean, Boolean>(false, false);
+ }
+ List<Resource> expressionList = ListUtils.toList(graph, expressions);
+ if(expressionList.isEmpty()) {
+ return new Pair<Boolean, Boolean>(false, false);
+ }
+
+ boolean canAdd = true;
+ boolean canDelete = false;
+ // If there are multiple expressions, one can be removed
+ if(expressionList.size() > 1)
+ canDelete = true;
+ String defaultRange = ArrayExpressionCombo.getDefaultRange(graph, variable);
+
+ /* If the variable is an array variable, a range has been set to all expressions and none of
+ * the ranges is the default range, an expression can be added
+ */
+ for(Resource expression : expressionList) {
+ String range = graph.getPossibleRelatedValue(expression, sr.Expression_arrayRange);
+ if(range == null || range.equals("") || range.equals(defaultRange)) {
+ canAdd = false;
+ break;
+ }
+ }
+ return new Pair<Boolean, Boolean>(canAdd, canDelete);
+ }
+ }, new AsyncListener<Pair<Boolean, Boolean>>() {
+
+ @Override
+ public void execute(AsyncReadGraph graph,
+ final Pair<Boolean, Boolean> result) {
+ newExpression.getWidget().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if(!newExpression.getWidget().isDisposed())
+ newExpression.getWidget().setEnabled(result.first);
+ if(!deleteExpression.getWidget().isDisposed())
+ deleteExpression.getWidget().setEnabled(result.second);
+ }
+ });
+
+ }
+
+ @Override
+ public void exception(AsyncReadGraph graph, Throwable throwable) {
+ throwable.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return newExpression.getWidget().isDisposed() || deleteExpression.getWidget().isDisposed();
+ }
+ });
+
+ // Set input to widgets using expressionSupport
+ StructuredSelection ss = new StructuredSelection(new ExpressionWidgetInput(var, expression));
+ expressionSupport.fireInput(context, ss);
+ }
+
+ /**
+ * Adds listeners to widgets in this tab
+ *
+ * @param context ISessionContext
+ */
+ private void addListeners(ISessionContext context) {
+
+ // Validate expression fields when a dependency has been added or removed
+ shortcutTabWidget.addDependencyListener(new Runnable() {
+
+ @Override
+ public void run() {
+ expressionWidget.validateFields();
+ }
+ });
+
+ // Deletes a selected expression
+ deleteExpression.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ @Override
+ public void apply(WriteGraph graph, final Resource input)
+ throws DatabaseException {
+
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ // Currently active expression should be located in (Model sr.HasActiveExpression expression)
+ Resource activeExpression = graph.getPossibleObject(input, sr.IndependentVariable_activeExpression);
+ if(activeExpression == null)
+ return;
+
+ Resource expressionList = graph.getPossibleObject(input, sr.Variable_expressionList);
+
+ List<Resource> list = ListUtils.toList(graph, expressionList);
+ if(list.size() <= 1)
+ return;
+
+ // Get the previous expression in expression list to be activated
+ int index = list.indexOf(activeExpression);
+
+ ListUtils.removeElement(graph, expressionList, activeExpression);
+ graph.deny(input, l0.ConsistsOf, activeExpression);
+
+ final Resource newActive = index == 0 ? list.get(1) : list.get(index - 1);
+
+ // Set newActive as active in virtual graph
+ VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
+ final Session session = graph.getSession();
+ session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ VirtualGraph runtime = graph.getService(VirtualGraph.class);
+ session.asyncRequest(new WriteRequest(runtime) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(graph.hasStatement(input, sr.IndependentVariable_activeExpression))
+ graph.deny(input, sr.IndependentVariable_activeExpression);
+ graph.claim(input, sr.IndependentVariable_activeExpression, newActive);
+ }
+ }
+ );
+ }
+ });
+ Layer0Utils.addCommentMetadata(graph, "Deleted Expression " + activeExpression + " from " + graph.getPossibleRelatedValue2(input, Layer0.getInstance(graph).HasName, Bindings.STRING));
+ }
+ });
+
+ // Creates a new expression
+ newExpression.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ @Override
+ public void apply(WriteGraph graph, Resource input)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ Resource expressions = graph.getPossibleObject(input, sr.Variable_expressionList);
+ if(expressions == null) {
+ return;
+ }
+ // Get the currently active expression
+ Resource activeExpression = graph.getPossibleObject(input, sr.IndependentVariable_activeExpression);
+ Resource newExpression = graph.newResource();
+ if(activeExpression != null) {
+ // Create a new expression based on the old expression
+ graph.claim(newExpression, l0.InstanceOf, graph.getSingleObject(activeExpression, l0.InstanceOf));
+ if(graph.isInstanceOf(newExpression, sr.StockExpression)) {
+ graph.claimLiteral(newExpression, sr.StockExpression_initialEquation, "");
+ Layer0Utils.addCommentMetadata(graph, "Created new Stock Expression " + newExpression + " for " + graph.getPossibleRelatedValue2(input, Layer0.getInstance(graph).HasName, Bindings.STRING));
+ }
+ } else {
+ // If there was no active expression, create a normal expression
+ graph.claim(newExpression, l0.InstanceOf, sr.NormalExpression);
+ graph.claimLiteral(newExpression, sr.Expression_equation, "");
+ Layer0Utils.addCommentMetadata(graph, "Created new Normal Expression " + newExpression + " for " + graph.getPossibleRelatedValue2(input, Layer0.getInstance(graph).HasName, Bindings.STRING));
+ }
+ ArrayList<Resource> addition = new ArrayList<Resource>(1);
+ addition.add(newExpression);
+ ListUtils.insertBack(graph, expressions, addition);
+ graph.claim(input, l0.ConsistsOf, newExpression);
+ }
+ });
+
+ // Item factory for expression type combo
+ expressionTypeCombo.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {
+
+ @Override
+ public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ // Select expression types based on the type of the variable
+ final ExpressionType[] expressionTypes;
+ if(graph.isInstanceOf(input, sr.Auxiliary))
+ expressionTypes = ExpressionTypes.auxiliaryExpressions;
+ else if(graph.isInstanceOf(input, sr.Stock))
+ expressionTypes = ExpressionTypes.stockExpressions;
+ else if(graph.isInstanceOf(input, sr.Valve))
+ expressionTypes = ExpressionTypes.valveExpressions;
+ else
+ expressionTypes = new ExpressionType[] {};
+
+ for(ExpressionType et : expressionTypes) {
+ map.put(et.toString(), et);
+ }
+ return map;
+ }
+ });
+
+ // Initial selection to the combo from active expression
+ expressionTypeCombo.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {
+
+ @Override
+ public String perform(ReadGraph graph, final Resource input) throws DatabaseException {
+ Resource activeExpression = getActiveExpression(graph, input);
+ if(activeExpression == null)
+ return null;
+ return ExpressionTypes.getExpressionType(graph, activeExpression).toString();
+ }
+ });
+
+ // Modify listener for selecting expression type
+ expressionTypeCombo.addModifyListener(new TextModifyListener() {
+
+ @Override
+ public void modifyText(TrackedModifyEvent e) {
+ expressionWidget.displayExpression(e.getText(), false);
+ expressionWidget.save();
+ }
+ });
+
+
+ // Add all units used in the model to the unit combo
+ unitCombo.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {
+
+ @Override
+ public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource model = graph.getPossibleObject(input, l0.PartOf);
+ if (model != null) {
+ Collection<Resource> variables = graph.getObjects(model, l0.ConsistsOf);
+ for(Resource v : variables) {
+ Object unit = graph.getPossibleRelatedValue(v, sr.Variable_unit);
+ if (unit != null && !map.keySet().contains(unit)) {
+ map.put((String)unit, (String)unit);
+
+ }
+ }
+ }
+ return map;
+ }
+ });
+
+ // Set initial selection of unit combo
+ unitCombo.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {
+
+ @Override
+ public String perform(ReadGraph graph, final Resource input) throws DatabaseException {
+ String unit = graph.getPossibleRelatedValue(input, SysdynResource.getInstance(graph).Variable_unit);
+ if(unit == null)
+ return "";
+ else
+ return unit;
+ }
+ });
+
+ // Modify unit
+ unitCombo.addModifyListener(new ComboModifyListenerImpl<Resource>() {
+
+ @Override
+ public void applyText(WriteGraph graph, Resource input, String text) throws DatabaseException {
+ graph.denyValue(input, SysdynResource.getInstance(graph).Variable_unit);
+ graph.claimLiteral(input, SysdynResource.getInstance(graph).Variable_unit, text);
+
+ Resource conf = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);
+ SysdynModelManager smm = SysdynModelManager.getInstance(graph.getSession());
+ SysdynModel sm = smm.getModel(graph, conf);
+ sm.getMapping().domainModified(input);
+ sm.update(graph);
+ }
+ });
+
+
+ /*
+ * Double-clicking something in shortcut tab widget
+ * writes the clicked element into expression widget,
+ * sets focus on expression widget and validates its fields
+ */
+ shortcutTabWidget.addMouseListener(new MouseListener(){
+
+ @Override
+ public void mouseDoubleClick(MouseEvent e) {
+ Table table = (Table)e.widget;
+ TableItem item = table.getItem(new Point(e.x, e.y));
+ if(item != null) {
+ final String var = (String)item.getData();
+ table.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if(expressionWidget!= null) {
+ expressionWidget.getExpression().focus();
+ expressionWidget.getExpression().replaceSelection(var);
+ expressionWidget.validateFieldsTimed();
+ }
+ }
+ });
+ }
+ }
+
+ @Override
+ public void mouseDown(MouseEvent e) {
+ expressionWidget.getExpression().focus();
+ }
+
+ @Override
+ public void mouseUp(MouseEvent e) {
+ }
+
+ });
+
+ /* Modifying an expression sets a timed validation. The timer is
+ * reset after each modification
+ */
+ expressionWidget.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ expressionWidget.validateFieldsTimed();
+ }
+ });
+
+ // Pressing return without shift key triggers saving the expression
+ expressionWidget.addVerifyKeyListener(new VerifyKeyListener() {
+
+ @Override
+ public void verifyKey(VerifyEvent event) {
+ // Check if some of the expression fields has active completion assistant
+ boolean isAnyAssistSessionActive = false;
+ for (int i = 0; i < expressionWidget.getExpression().getExpressionFields().size(); ++i) {
+ if (expressionWidget.getExpression().getExpressionFields().get(i).isAssistSessionActive()) {
+ isAnyAssistSessionActive = true;
+ break;
+ }
+ }
+ if(event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR) {
+ if (!isAnyAssistSessionActive) {
+ if((event.stateMask & SWT.SHIFT) == 0) {
+ event.doit = false;
+ ((StyledText)event.widget).getParent().forceFocus();
+ expressionWidget.save();
+ }
+ } else {
+ // When a proposed expression is selected with enter, fields are validated.
+ expressionWidget.validateFieldsTimed();
+ }
+ }
+ }
+ });
+
+ // Triggers save when equation tab loses focus
+ if(focusLostListener == null) {
+ focusLostListener = new org.eclipse.ui.IPartListener2()
+ {
+ @Override
+ public void partInputChanged(IWorkbenchPartReference partRef) {}
+ @Override
+ public void partVisible(IWorkbenchPartReference partRef) {}
+ @Override
+ public void partHidden(IWorkbenchPartReference partRef) {}
+ @Override
+ public void partOpened(IWorkbenchPartReference partRef) {}
+ @Override
+ public void partDeactivated(IWorkbenchPartReference partRef)
+ {
+ if(partRef.getPart(false) instanceof PropertyPageView) {
+ PropertyPageView ppv = (PropertyPageView)partRef.getPart(false);
+ if(ppv.getCurrentPage() instanceof SysdynPropertyPage) {
+ // Save expressions
+ if(expressionWidget != null) {
+ expressionWidget.save();
+ }
+// site.getPage().removePartListener(this);
+ }
+ }
+ }
+ @Override
+ public void partClosed(IWorkbenchPartReference partRef) {}
+ @Override
+ public void partBroughtToTop(IWorkbenchPartReference partRef) {}
+ @Override
+ public void partActivated(IWorkbenchPartReference partRef) {}
+ };
+ site.getPage().addPartListener(focusLostListener);
+ }
+ }
+
+ @Override
+ public void dispose() {
+ if(expressionWidget != null && !(expressionWidget.getExpression() instanceof DelayExpression)) {
+ // For delay expression this doesn't work,
+ // but it doesn't matter since the saving is succeeded elsewhere.
+ expressionWidget.save();
+ }
+ if(focusLostListener != null && site != null)
+ site.getPage().removePartListener(focusLostListener);
+ super.dispose();
+ if(expressionComposite != null && !expressionComposite.isDisposed())
+ expressionComposite.dispose();
+ }
+
+ /**
+ * Get the currently active expression of the first expression in expression list if
+ * no expression has been set to active
+ *
+ * @param graph ReadGraph
+ * @param variable Variable
+ * @return active expression or the first expression in variables expression list
+ * @throws DatabaseException
+ */
+ private Resource getActiveExpression(ReadGraph graph, Resource variable) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource expression = graph.getPossibleObject(variable, sr.IndependentVariable_activeExpression);
+ if(expression == null) {
+ Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);
+ if(expressions == null) {
+ return null;
+ }
+ List<Resource> expressionList = ListUtils.toList(graph, expressions);
+ if(expressionList.isEmpty()) {
+ return null;
+ }
+ expression = expressionList.get(0);
+ }
+ return expression;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2013-2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties;\r
-\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Combo;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Display;\r
-import org.eclipse.swt.widgets.Group;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.databoard.util.ObjectUtils;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.utils.LoopUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-import org.simantics.utils.datastructures.Triple;\r
-\r
-/**\r
- * Tab for displaying information of a loop\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class LoopTab extends AdjustableTab {\r
-\r
- public LoopTab(Object id) {\r
- super(id);\r
- }\r
-\r
- private Label loopItemsLabel;\r
- private TrackedCombo loopItemsDropdown;\r
- Button auto, balancing, reinforcing, other, inside, outside;\r
- TrackedText loopComment, polarityLocationText;\r
- Composite loopItems;\r
- Group commentGroup, rotationGroup;\r
- protected Resource resource;\r
- public static final String AUTO = "$$AUTO$$";\r
-\r
- @Override\r
- protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
- ISessionContext context, WidgetSupport support) {\r
- composite = new Composite(body, SWT.NONE);\r
-\r
- loopItems = new Composite(composite, SWT.NONE);\r
- loopItemsLabel = new Label(loopItems, SWT.SINGLE);\r
- loopItemsLabel.setText("Loop Items:");\r
- loopItemsDropdown = new TrackedCombo(loopItems, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
- \r
- commentGroup = new Group(composite, SWT.NONE);\r
- commentGroup.setText("Comment");\r
- \r
- auto = new Button(commentGroup, support, SWT.RADIO);\r
- auto.setText("Auto");\r
- auto.setSelectionFactory(new CommentRadioSelectionFactory(AUTO));\r
- auto.addSelectionListener(new CommentSelectionListener(context, AUTO));\r
- \r
- balancing = new Button(commentGroup, support, SWT.RADIO);\r
- balancing.setText("B");\r
- balancing.setSelectionFactory(new CommentRadioSelectionFactory("B"));\r
- balancing.addSelectionListener(new CommentSelectionListener(context, "B"));\r
- \r
- reinforcing = new Button(commentGroup, support, SWT.RADIO);\r
- reinforcing.setText("R");\r
- reinforcing.setSelectionFactory(new CommentRadioSelectionFactory("R"));\r
- reinforcing.addSelectionListener(new CommentSelectionListener(context, "R"));\r
- \r
- other = new Button(commentGroup, support, SWT.RADIO);\r
- other.setText("other");\r
- other.setSelectionFactory(new OtherCommentSelectionFactory(new String[] {null, "B", "R", AUTO}));\r
- other.addSelectionListener(new CommentSelectionListener(context, ""));\r
- \r
- loopComment = new TrackedText(commentGroup, support, SWT.BORDER);\r
- loopComment.setTextFactory(new OtherCommentStringPropertyFactory());\r
- loopComment.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.Loop_Comment));\r
- \r
- rotationGroup = new Group(composite, SWT.NONE);\r
- rotationGroup.setText("Direction of Rotation");\r
- \r
- inside = new Button(rotationGroup, support, SWT.RADIO);\r
- inside.setText("Clockwise");\r
- inside.setSelectionFactory(new ClockwiseRotationRadioSelectionFactory(true));\r
- inside.addSelectionListener(new ClockwiseRotationSelectionListener(context, true));\r
- \r
- outside = new Button(rotationGroup, support, SWT.RADIO);\r
- outside.setText("Counterclockwise");\r
- outside.setSelectionFactory(new ClockwiseRotationRadioSelectionFactory(false));\r
- outside.addSelectionListener(new ClockwiseRotationSelectionListener(context, false));\r
- \r
- addListeners(context);\r
- }\r
-\r
- private void addListeners(ISessionContext context) {\r
- // Item factory for loopItemsDropdown combo\r
- loopItemsDropdown.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
-\r
- @Override\r
- public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
-\r
- LoopTab.this.resource = input;\r
- Map<String, Object> map = new HashMap<String, Object>();\r
- List<List<Resource>> loops = LoopUtils.getAllLoopsInDiagram(graph, input);\r
- map.put("", null);\r
- for (List<Resource> loop : loops) {\r
- map.put(LoopUtils.cycleToString(graph, loop), loop);\r
- }\r
- return map;\r
- }\r
- });\r
-\r
- // Initial selection to the combo\r
- loopItemsDropdown.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph, final Resource input) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource itemListResource = graph.getPossibleObject(input, sr.Loop_Items);\r
- \r
- // If the loop hasn't been defined, return empty.\r
- if (itemListResource == null) {\r
- return "";\r
- }\r
- List<Resource> itemList = ListUtils.toPossibleList(graph, itemListResource);\r
- if (itemList == null) {\r
- return "";\r
- }\r
- \r
- // See if the defined loop still exists.\r
- List<List<Resource>> loops = LoopUtils.getAllLoopsInDiagram(graph, input);\r
- Resource first = itemList.get(0);\r
- for (List<Resource> loop : loops) {\r
- // If the loops are of different size, continue.\r
- if (loop.size() != itemList.size())\r
- continue;\r
- \r
- // If the first element of the sought loop is not found, continue. \r
- int indexOfFirst = loop.indexOf(first);\r
- if (indexOfFirst < 0) {\r
- continue;\r
- }\r
- \r
- // Check if the loops are the same,\r
- // even if they start at different Resources\r
- boolean match = true;\r
- int i = 1;// = indexOfFirst + 1;\r
- do {\r
- // Get the next Resource in the loop\r
- Resource next = loop.get((i + indexOfFirst) % loop.size());\r
- // If it is other than what should be, continue to the next loop.\r
- if (!next.equalsResource(itemList.get(i))) {\r
- match = false;\r
- break;\r
- }\r
- } while (++i != itemList.size());\r
- if (!match)\r
- continue;\r
- \r
- return LoopUtils.cycleToString(graph, loop);\r
- }\r
- \r
- // No match found, hence empty\r
- return "";\r
- }\r
- });\r
-\r
- // Modify listener for selecting loop items\r
- loopItemsDropdown.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
-\r
- @SuppressWarnings("unchecked")\r
- @Override\r
- public void applyText(WriteGraph graph, final Resource input, String text) throws DatabaseException {\r
- final Combo c = loopItemsDropdown.getWidget();\r
- Display.getDefault().asyncExec(new Runnable() {\r
- public void run() {\r
- Object o = c.getData();\r
- if (o != null && !(o instanceof HashMap<?, ?>))\r
- return;\r
- \r
- Object loopObject = ((HashMap<?, ?>)o).get(c.getText());\r
- if (loopObject == null || !(loopObject instanceof List<?>))\r
- return;\r
- \r
- final List<Resource> loop = (List<Resource>)loopObject;\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource loopResource = graph.getPossibleObject(input, sr.Loop_Items);\r
- // Delete the current list if it exists.\r
- if (loopResource != null) {\r
- List<Resource> removedList = ListUtils.toPossibleList(graph, loopResource);\r
- for (Resource r : removedList)\r
- ListUtils.removeElement(graph, loopResource, r);\r
- graph.deny(loopResource);\r
- }\r
- // Create new list.\r
- Resource newList = ListUtils.create(graph, loop);\r
- graph.claim(input, sr.Loop_Items, newList);\r
- }\r
- });\r
- }\r
- });\r
- \r
- }\r
- });\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutVertical() {\r
- GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(loopItems);\r
- GridLayoutFactory.fillDefaults().numColumns(1).applyTo(loopItems);\r
- GridDataFactory.fillDefaults().grab(false, false).applyTo(loopItemsLabel);\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(loopItemsDropdown.getWidget());\r
- \r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(composite);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(commentGroup);\r
- GridLayoutFactory.fillDefaults().numColumns(5).applyTo(commentGroup);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(loopComment.getWidget());\r
- GridDataFactory.fillDefaults().grab(false, false).applyTo(rotationGroup);\r
- GridLayoutFactory.fillDefaults().applyTo(rotationGroup);\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutHorizontal(boolean wideScreen) {\r
- GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(loopItems);\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(loopItems);\r
- GridDataFactory.fillDefaults().grab(false, false).applyTo(loopItemsLabel);\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(loopItemsDropdown.getWidget());\r
- \r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(commentGroup);\r
- GridLayoutFactory.fillDefaults().numColumns(5).applyTo(commentGroup);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(loopComment.getWidget());\r
- GridDataFactory.fillDefaults().grab(false, false).applyTo(rotationGroup);\r
- GridLayoutFactory.fillDefaults().applyTo(rotationGroup);\r
- }\r
- \r
- class OtherCommentStringPropertyFactory extends ReadFactoryImpl<Resource, String> {\r
-\r
- private final String propertyURI;\r
-\r
- public OtherCommentStringPropertyFactory() {\r
- this.propertyURI = SysdynResource.URIs.Loop_Comment;\r
- }\r
-\r
- @Override\r
- public Object getIdentity(Object inputContents) {\r
- return new Triple<Resource, String, Object>((Resource)inputContents, propertyURI, getClass());\r
- }\r
-\r
- @Override\r
- public String perform(ReadGraph graph, Resource resource) throws DatabaseException {\r
- String value = graph.getPossibleRelatedValue(resource, graph.getResource(propertyURI));;\r
- if (value == null || AUTO.equals(value))\r
- return "";\r
- return value;\r
- } \r
- }\r
- \r
- class ClockwiseRotationSelectionListener extends SelectionListenerImpl<Resource> {\r
- private boolean clockwise;\r
-\r
- public ClockwiseRotationSelectionListener(ISessionContext context, boolean clockwise) {\r
- super(context);\r
- this.clockwise = clockwise;\r
- }\r
- \r
- @Override\r
- public void apply(WriteGraph graph, Resource component) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- Resource symbol = graph.getPossibleObject(component, mr.ComponentToElement);\r
- if(symbol != null) {\r
- graph.deny(symbol, sr.LoopSymbol_Clockwise);\r
- graph.claimLiteral(symbol, sr.LoopSymbol_Clockwise, clockwise);\r
- }\r
- }\r
- \r
- }\r
- \r
- class ClockwiseRotationRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
- private boolean clockwise;\r
-\r
- public ClockwiseRotationRadioSelectionFactory(boolean clockwise) {\r
- this.clockwise = clockwise;\r
- }\r
-\r
- @Override\r
- public Object getIdentity(Object inputContents) {\r
- return new Triple<Object, Object, Class<?>>(inputContents, clockwise, getClass());\r
- }\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph, Resource component) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph); \r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- Resource symbol = graph.getPossibleObject(component, mr.ComponentToElement);\r
- if(symbol != null) {\r
- Boolean clockwise = graph.getPossibleRelatedValue(symbol, sr.LoopSymbol_Clockwise, Bindings.BOOLEAN); \r
- return ObjectUtils.objectEquals(this.clockwise, clockwise);\r
- }\r
- return Boolean.TRUE;\r
- }\r
- }\r
- \r
- class CommentSelectionListener extends SelectionListenerImpl<Resource> {\r
- private String comment;\r
-\r
- public CommentSelectionListener(ISessionContext context, String comment) {\r
- super(context);\r
- this.comment = comment;\r
- }\r
- \r
- @Override\r
- public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- graph.deny(connectionElement, sr.Loop_Comment);\r
- graph.claimLiteral(connectionElement, sr.Loop_Comment, comment.trim());\r
- }\r
- \r
- }\r
- \r
- class CommentRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
- private String comment;\r
-\r
- public CommentRadioSelectionFactory(String comment) {\r
- this.comment = comment;\r
- }\r
-\r
- @Override\r
- public Object getIdentity(Object inputContents) {\r
- return new Triple<Object, Object, Class<?>>(inputContents, comment, getClass());\r
- }\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- String comment = graph.getPossibleRelatedValue(dependencyConnection, sr.Loop_Comment, Bindings.STRING); \r
- if(comment == null && this.comment.equals(""))\r
- return true;\r
- return ObjectUtils.objectEquals(comment, this.comment);\r
- }\r
- }\r
- \r
- class OtherCommentSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
-\r
- String[] limits;\r
- \r
- public OtherCommentSelectionFactory(String[] limits) {\r
- this.limits = limits;\r
- }\r
- \r
- @Override\r
- public Object getIdentity(Object inputContents) {\r
- return new Pair<Object, Class<?>>(inputContents, getClass());\r
- }\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- String comment = graph.getPossibleRelatedValue(dependencyConnection, sr.Loop_Comment, Bindings.STRING);\r
- for(String s : limits) {\r
- if(ObjectUtils.objectEquals(comment, s))\r
- return false;\r
- }\r
- return true;\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013-2014 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.sysdyn.ui.properties;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.Button;
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;
+import org.simantics.browsing.ui.swt.widgets.TrackedText;
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.databoard.Bindings;
+import org.simantics.databoard.util.ObjectUtils;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.jfreechart.chart.properties.AdjustableTab;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.utils.LoopUtils;
+import org.simantics.utils.datastructures.Pair;
+import org.simantics.utils.datastructures.Triple;
+
+/**
+ * Tab for displaying information of a loop
+ * @author Tuomas Miettinen
+ *
+ */
+public class LoopTab extends AdjustableTab {
+
+ public LoopTab(Object id) {
+ super(id);
+ }
+
+ private Label loopItemsLabel;
+ private TrackedCombo loopItemsDropdown;
+ Button auto, balancing, reinforcing, other, inside, outside;
+ TrackedText loopComment, polarityLocationText;
+ Composite loopItems;
+ Group commentGroup, rotationGroup;
+ protected Resource resource;
+ public static final String AUTO = "$$AUTO$$";
+
+ @Override
+ protected void createAndAddControls(Composite body, IWorkbenchSite site,
+ ISessionContext context, WidgetSupport support) {
+ composite = new Composite(body, SWT.NONE);
+
+ loopItems = new Composite(composite, SWT.NONE);
+ loopItemsLabel = new Label(loopItems, SWT.SINGLE);
+ loopItemsLabel.setText("Loop Items:");
+ loopItemsDropdown = new TrackedCombo(loopItems, support, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);
+
+ commentGroup = new Group(composite, SWT.NONE);
+ commentGroup.setText("Comment");
+
+ auto = new Button(commentGroup, support, SWT.RADIO);
+ auto.setText("Auto");
+ auto.setSelectionFactory(new CommentRadioSelectionFactory(AUTO));
+ auto.addSelectionListener(new CommentSelectionListener(context, AUTO));
+
+ balancing = new Button(commentGroup, support, SWT.RADIO);
+ balancing.setText("B");
+ balancing.setSelectionFactory(new CommentRadioSelectionFactory("B"));
+ balancing.addSelectionListener(new CommentSelectionListener(context, "B"));
+
+ reinforcing = new Button(commentGroup, support, SWT.RADIO);
+ reinforcing.setText("R");
+ reinforcing.setSelectionFactory(new CommentRadioSelectionFactory("R"));
+ reinforcing.addSelectionListener(new CommentSelectionListener(context, "R"));
+
+ other = new Button(commentGroup, support, SWT.RADIO);
+ other.setText("other");
+ other.setSelectionFactory(new OtherCommentSelectionFactory(new String[] {null, "B", "R", AUTO}));
+ other.addSelectionListener(new CommentSelectionListener(context, ""));
+
+ loopComment = new TrackedText(commentGroup, support, SWT.BORDER);
+ loopComment.setTextFactory(new OtherCommentStringPropertyFactory());
+ loopComment.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.Loop_Comment));
+
+ rotationGroup = new Group(composite, SWT.NONE);
+ rotationGroup.setText("Direction of Rotation");
+
+ inside = new Button(rotationGroup, support, SWT.RADIO);
+ inside.setText("Clockwise");
+ inside.setSelectionFactory(new ClockwiseRotationRadioSelectionFactory(true));
+ inside.addSelectionListener(new ClockwiseRotationSelectionListener(context, true));
+
+ outside = new Button(rotationGroup, support, SWT.RADIO);
+ outside.setText("Counterclockwise");
+ outside.setSelectionFactory(new ClockwiseRotationRadioSelectionFactory(false));
+ outside.addSelectionListener(new ClockwiseRotationSelectionListener(context, false));
+
+ addListeners(context);
+ }
+
+ private void addListeners(ISessionContext context) {
+ // Item factory for loopItemsDropdown combo
+ loopItemsDropdown.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {
+
+ @Override
+ public Map<String, Object> perform(ReadGraph graph, final Resource input) throws DatabaseException {
+
+ LoopTab.this.resource = input;
+ Map<String, Object> map = new HashMap<String, Object>();
+ List<List<Resource>> loops = LoopUtils.getAllLoopsInDiagram(graph, input);
+ map.put("", null);
+ for (List<Resource> loop : loops) {
+ map.put(LoopUtils.cycleToString(graph, loop), loop);
+ }
+ return map;
+ }
+ });
+
+ // Initial selection to the combo
+ loopItemsDropdown.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {
+
+ @Override
+ public String perform(ReadGraph graph, final Resource input) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource itemListResource = graph.getPossibleObject(input, sr.Loop_Items);
+
+ // If the loop hasn't been defined, return empty.
+ if (itemListResource == null) {
+ return "";
+ }
+ List<Resource> itemList = ListUtils.toPossibleList(graph, itemListResource);
+ if (itemList == null) {
+ return "";
+ }
+
+ // See if the defined loop still exists.
+ List<List<Resource>> loops = LoopUtils.getAllLoopsInDiagram(graph, input);
+ Resource first = itemList.get(0);
+ for (List<Resource> loop : loops) {
+ // If the loops are of different size, continue.
+ if (loop.size() != itemList.size())
+ continue;
+
+ // If the first element of the sought loop is not found, continue.
+ int indexOfFirst = loop.indexOf(first);
+ if (indexOfFirst < 0) {
+ continue;
+ }
+
+ // Check if the loops are the same,
+ // even if they start at different Resources
+ boolean match = true;
+ int i = 1;// = indexOfFirst + 1;
+ do {
+ // Get the next Resource in the loop
+ Resource next = loop.get((i + indexOfFirst) % loop.size());
+ // If it is other than what should be, continue to the next loop.
+ if (!next.equalsResource(itemList.get(i))) {
+ match = false;
+ break;
+ }
+ } while (++i != itemList.size());
+ if (!match)
+ continue;
+
+ return LoopUtils.cycleToString(graph, loop);
+ }
+
+ // No match found, hence empty
+ return "";
+ }
+ });
+
+ // Modify listener for selecting loop items
+ loopItemsDropdown.addModifyListener(new ComboModifyListenerImpl<Resource>() {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void applyText(WriteGraph graph, final Resource input, String text) throws DatabaseException {
+ final Combo c = loopItemsDropdown.getWidget();
+ Display.getDefault().asyncExec(new Runnable() {
+ public void run() {
+ Object o = c.getData();
+ if (o != null && !(o instanceof HashMap<?, ?>))
+ return;
+
+ Object loopObject = ((HashMap<?, ?>)o).get(c.getText());
+ if (loopObject == null || !(loopObject instanceof List<?>))
+ return;
+
+ final List<Resource> loop = (List<Resource>)loopObject;
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource loopResource = graph.getPossibleObject(input, sr.Loop_Items);
+ // Delete the current list if it exists.
+ if (loopResource != null) {
+ List<Resource> removedList = ListUtils.toPossibleList(graph, loopResource);
+ for (Resource r : removedList)
+ ListUtils.removeElement(graph, loopResource, r);
+ graph.deny(loopResource);
+ }
+ // Create new list.
+ Resource newList = ListUtils.create(graph, loop);
+ graph.claim(input, sr.Loop_Items, newList);
+ }
+ });
+ }
+ });
+
+ }
+ });
+ }
+
+ @Override
+ protected void createControlLayoutVertical() {
+ GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(loopItems);
+ GridLayoutFactory.fillDefaults().numColumns(1).applyTo(loopItems);
+ GridDataFactory.fillDefaults().grab(false, false).applyTo(loopItemsLabel);
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(loopItemsDropdown.getWidget());
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(1).applyTo(composite);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(commentGroup);
+ GridLayoutFactory.fillDefaults().numColumns(5).applyTo(commentGroup);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(loopComment.getWidget());
+ GridDataFactory.fillDefaults().grab(false, false).applyTo(rotationGroup);
+ GridLayoutFactory.fillDefaults().applyTo(rotationGroup);
+ }
+
+ @Override
+ protected void createControlLayoutHorizontal(boolean wideScreen) {
+ GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(loopItems);
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(loopItems);
+ GridDataFactory.fillDefaults().grab(false, false).applyTo(loopItemsLabel);
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(loopItemsDropdown.getWidget());
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(commentGroup);
+ GridLayoutFactory.fillDefaults().numColumns(5).applyTo(commentGroup);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(loopComment.getWidget());
+ GridDataFactory.fillDefaults().grab(false, false).applyTo(rotationGroup);
+ GridLayoutFactory.fillDefaults().applyTo(rotationGroup);
+ }
+
+ class OtherCommentStringPropertyFactory extends ReadFactoryImpl<Resource, String> {
+
+ private final String propertyURI;
+
+ public OtherCommentStringPropertyFactory() {
+ this.propertyURI = SysdynResource.URIs.Loop_Comment;
+ }
+
+ @Override
+ public Object getIdentity(Object inputContents) {
+ return new Triple<Resource, String, Object>((Resource)inputContents, propertyURI, getClass());
+ }
+
+ @Override
+ public String perform(ReadGraph graph, Resource resource) throws DatabaseException {
+ String value = graph.getPossibleRelatedValue(resource, graph.getResource(propertyURI));;
+ if (value == null || AUTO.equals(value))
+ return "";
+ return value;
+ }
+ }
+
+ class ClockwiseRotationSelectionListener extends SelectionListenerImpl<Resource> {
+ private boolean clockwise;
+
+ public ClockwiseRotationSelectionListener(ISessionContext context, boolean clockwise) {
+ super(context);
+ this.clockwise = clockwise;
+ }
+
+ @Override
+ public void apply(WriteGraph graph, Resource component) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ Resource symbol = graph.getPossibleObject(component, mr.ComponentToElement);
+ if(symbol != null) {
+ graph.deny(symbol, sr.LoopSymbol_Clockwise);
+ graph.claimLiteral(symbol, sr.LoopSymbol_Clockwise, clockwise);
+ }
+ }
+
+ }
+
+ class ClockwiseRotationRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {
+ private boolean clockwise;
+
+ public ClockwiseRotationRadioSelectionFactory(boolean clockwise) {
+ this.clockwise = clockwise;
+ }
+
+ @Override
+ public Object getIdentity(Object inputContents) {
+ return new Triple<Object, Object, Class<?>>(inputContents, clockwise, getClass());
+ }
+
+ @Override
+ public Boolean perform(ReadGraph graph, Resource component) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ Resource symbol = graph.getPossibleObject(component, mr.ComponentToElement);
+ if(symbol != null) {
+ Boolean clockwise = graph.getPossibleRelatedValue(symbol, sr.LoopSymbol_Clockwise, Bindings.BOOLEAN);
+ return ObjectUtils.objectEquals(this.clockwise, clockwise);
+ }
+ return Boolean.TRUE;
+ }
+ }
+
+ class CommentSelectionListener extends SelectionListenerImpl<Resource> {
+ private String comment;
+
+ public CommentSelectionListener(ISessionContext context, String comment) {
+ super(context);
+ this.comment = comment;
+ }
+
+ @Override
+ public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ graph.deny(connectionElement, sr.Loop_Comment);
+ graph.claimLiteral(connectionElement, sr.Loop_Comment, comment.trim());
+ }
+
+ }
+
+ class CommentRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {
+ private String comment;
+
+ public CommentRadioSelectionFactory(String comment) {
+ this.comment = comment;
+ }
+
+ @Override
+ public Object getIdentity(Object inputContents) {
+ return new Triple<Object, Object, Class<?>>(inputContents, comment, getClass());
+ }
+
+ @Override
+ public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ String comment = graph.getPossibleRelatedValue(dependencyConnection, sr.Loop_Comment, Bindings.STRING);
+ if(comment == null && this.comment.equals(""))
+ return true;
+ return ObjectUtils.objectEquals(comment, this.comment);
+ }
+ }
+
+ class OtherCommentSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {
+
+ String[] limits;
+
+ public OtherCommentSelectionFactory(String[] limits) {
+ this.limits = limits;
+ }
+
+ @Override
+ public Object getIdentity(Object inputContents) {
+ return new Pair<Object, Class<?>>(inputContents, getClass());
+ }
+
+ @Override
+ public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ String comment = graph.getPossibleRelatedValue(dependencyConnection, sr.Loop_Comment, Bindings.STRING);
+ for(String s : limits) {
+ if(ObjectUtils.objectEquals(comment, s))
+ return false;
+ }
+ return true;
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties;\r
-\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-import org.eclipse.core.runtime.IAdaptable;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.resource.JFaceResources;\r
-import org.eclipse.jface.resource.LocalResourceManager;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.viewers.StructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.ScrolledComposite;\r
-import org.eclipse.swt.events.DisposeEvent;\r
-import org.eclipse.swt.events.DisposeListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Event;\r
-import org.eclipse.swt.widgets.Group;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Listener;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.eclipse.swt.widgets.TreeItem;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.BuiltinKeys;\r
-import org.simantics.browsing.ui.Column;\r
-import org.simantics.browsing.ui.Column.Align;\r
-import org.simantics.browsing.ui.NodeContext;\r
-import org.simantics.browsing.ui.common.ColumnKeys;\r
-import org.simantics.browsing.ui.common.NodeContextBuilder.MapNodeContext;\r
-import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
-import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedCombo;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;\r
-import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.procedure.adapter.DisposableListener;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.ChartUtils;\r
-import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
-import org.simantics.jfreechart.chart.properties.RangeComposite;\r
-import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.IntegerPropertyFactory;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.IntegerPropertyModifier;\r
-import org.simantics.sysdyn.ui.properties.widgets.sensitivity.DistributionPropertyWidget;\r
-import org.simantics.sysdyn.ui.properties.widgets.sensitivity.ParameterChildRule;\r
-import org.simantics.sysdyn.ui.properties.widgets.sensitivity.VariableNameModifier;\r
-import org.simantics.sysdyn.ui.validation.ParameterExistsValidator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.RunnableWithObject;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-import org.simantics.utils.ui.validators.IntegerValidator;\r
-\r
-/**\r
- * Tab for displaying sensitivity analysis experiment properties\r
- * \r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class SensitivityAnalysisExperimentTab extends AdjustableTab implements Widget {\r
-\r
- public SensitivityAnalysisExperimentTab(Object id) {\r
- super(id);\r
- }\r
-\r
- private GraphExplorerComposite explorer;\r
- private WidgetSupportImpl parameterSupport = new WidgetSupportImpl();\r
- private ScrolledComposite propertyContainer;\r
- private Composite parameterProperties;\r
- private Composite content;\r
- private Button remove;\r
- private Resource experiment;\r
- \r
- private boolean dirty = false;\r
- private boolean dirtyMethod = false;\r
- \r
- private DisposableListener<Collection<Resource>> contentListener;\r
- private Composite labelComposite;\r
- private Label labelName;\r
- private Label labelNumber;\r
- private Label labelMethod;\r
- private TrackedCombo methodSelector;\r
- private Label labelSeed;\r
- private TrackedText seed;\r
- private Tree tree;\r
- private Composite buttonComposite;\r
- private Group parameterPropertyGroup;\r
- private Label labelVariable;\r
- private TrackedText variable;\r
- private Label labelRange;\r
- private RangeComposite rangeComposite;\r
- private Label labelDistribution;\r
- private TrackedCombo distributionSelector;\r
- private DistributionPropertyWidget dpw;\r
- private TrackedText name;\r
- private TrackedText n;\r
- private Button addVariable;\r
-\r
- @Override\r
- public void createControls(Composite body, IWorkbenchSite site,\r
- final ISessionContext context, final WidgetSupport support) {\r
- support.register(this);\r
- super.createControls(body, site, context, support);\r
- }\r
-\r
- /**\r
- * Updates the content of propertyContainer \r
- * @param context\r
- */\r
- private void updateSelection(ISessionContext context) {\r
- ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
- IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
- parameterSupport.fireInput(context, selection);\r
-\r
- propertyContainer.setContent(content);\r
- Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- }\r
-\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- experiment = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- if(contentListener == null) {\r
- contentListener = new DisposableListener<Collection<Resource>>() {\r
-\r
- @Override\r
- public void execute(Collection<Resource> result) {\r
- if(remove != null && !remove.getWidget().isDisposed() && result != null) {\r
- remove.getWidget().getDisplay().asyncExec(new RunnableWithObject(result) {\r
- @Override\r
- public void run() {\r
- if(!remove.getWidget().isDisposed()) {\r
- @SuppressWarnings("unchecked")\r
- Collection<Resource> result = (Collection<Resource>) getObject();\r
- if(result.size() > 1)\r
- remove.getWidget().setEnabled(true);\r
- else\r
- remove.getWidget().setEnabled(false);\r
- }\r
- }\r
- });\r
-\r
- }\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
- };\r
-\r
- SimanticsUI.getSession().asyncRequest(new Read<Collection<Resource>> () {\r
-\r
- @SuppressWarnings("unchecked")\r
- @Override\r
- public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {\r
- return (Collection<Resource>) new ParameterChildRule().getChildren(graph, experiment);\r
- }\r
-\r
- }, contentListener);\r
- }\r
-\r
- }\r
-\r
-\r
- @Override\r
- protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
- final ISessionContext context, final WidgetSupport support) {\r
-\r
- composite = new RemoveFocusBeforeExperimentComposite(body, SWT.NONE);\r
- \r
- // Scrolled composite for displaying properties of a selection in explorer\r
- propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
- propertyContainer.setExpandHorizontal(true);\r
- propertyContainer.setExpandVertical(true);\r
- \r
- content = new Composite(propertyContainer, SWT.NONE);\r
-\r
- // Label\r
- labelComposite = new Composite(content, SWT.NONE);\r
- labelName = new Label(labelComposite, SWT.NONE);\r
- labelName.setText("Name");\r
-\r
- name = new TrackedText(labelComposite, support, SWT.BORDER);\r
- name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));\r
- name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));\r
- name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));\r
- name.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), name.getWidget())));\r
- \r
- labelNumber = new Label(labelComposite, SWT.NONE);\r
- labelNumber.setText("Number of runs");\r
- \r
- n = new TrackedText(labelComposite, support, SWT.BORDER);\r
- n.setTextFactory(new IntegerPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_numberOfValues));\r
- n.addModifyListener(new IntegerPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_numberOfValues));\r
- n.setInputValidator(new IntegerValidator());\r
- n.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), n.getWidget())));\r
- \r
- labelMethod = new Label(labelComposite, SWT.NONE);\r
- labelMethod.setText("Method");\r
- \r
- methodSelector = new TrackedCombo(labelComposite, support, SWT.DROP_DOWN);\r
- methodSelector.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
-\r
- @Override\r
- public Map<String, Object> perform(ReadGraph graph, Resource input) throws DatabaseException {\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- Map<String, Object> items = new HashMap<String, Object>();\r
-\r
- items.put("Halton", SR.HaltonSequenceGenerator);\r
- items.put("Random", SR.RandomGenerator);\r
- \r
- return items;\r
- }\r
-\r
- });\r
- methodSelector.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph, Resource parameter) throws DatabaseException {\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- Resource method = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_method);\r
- if(method == null)\r
- return null;\r
- \r
- if(graph.isInstanceOf(method, SR.RandomGenerator))\r
- return "Random";\r
- else if(graph.isInstanceOf(method, SR.HaltonSequenceGenerator))\r
- return "Halton";\r
- else\r
- return "";\r
-\r
- }\r
- });\r
- methodSelector.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
-\r
- @Override\r
- public void applyText(WriteGraph graph, Resource input, String text)\r
- throws DatabaseException {\r
- if(text == null || text.isEmpty())\r
- return;\r
-\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
-\r
- Resource type = SR.RandomGenerator;\r
-\r
- if("Halton".equals(text))\r
- type = SR.HaltonSequenceGenerator;\r
- \r
- graph.deny(input, SR.SensitivityAnalysisExperiment_method);\r
-\r
- GraphUtils.create2(graph, type,\r
- SR.SensitivityAnalysisExperiment_method_Inverse, input);\r
-\r
- dirtyMethod = true;\r
- }\r
- });\r
- methodSelector.addModifyListener(new TextModifyListener() {\r
-\r
- @Override\r
- public void modifyText(TrackedModifyEvent e) {\r
- if(dirtyMethod) {\r
- support.update();\r
- dirtyMethod = false;\r
- propertyContainer.setContent(content);\r
- Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- }\r
- }\r
- });\r
- \r
- labelSeed = new Label(labelComposite, SWT.NONE);\r
- labelSeed.setText("Seed");\r
- \r
- seed = new TrackedText(labelComposite, support, SWT.BORDER);\r
- seed.setTextFactory(new IntegerPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_randomSeed));\r
- seed.addModifyListener(new IntegerPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_randomSeed));\r
- seed.setInputValidator(new IntegerValidator());\r
- seed.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), seed.getWidget())));\r
-\r
- // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis\r
- explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter", "treeView").values(false, false, true), site, content, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
- \r
- explorer.setBrowseContexts(SysdynResource.URIs.SensitivityAnalysisExperiment_ParameterBrowseContext);\r
- explorer.setInputSource(new SingleSelectionInputSource(\r
- Resource.class));\r
- explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
- explorer.setColumns( new Column[] { new Column(ColumnKeys.SINGLE, Align.LEFT, 0, "", true) });\r
- explorer.finish();\r
- \r
- \r
- ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
- public void widgetSelected(SelectionEvent e) {\r
- updateSelection(context);\r
- }\r
- });\r
-\r
- /* Listener for displaying information of the first parameter during view initialization\r
- * The view does not have focus, so normal selection listener mechanisms do not work. \r
- * Need to do it the hard way. \r
- */ \r
- Listener listener = new Listener() {\r
-\r
- boolean flag = false;\r
- @Override\r
- public void handleEvent(Event event) {\r
- switch (event.type) {\r
- case SWT.Activate:\r
- case SWT.Show:\r
- case SWT.Paint:\r
- {\r
- if(!flag && ((Tree) event.widget).getItems().length > 0) {\r
- flag = true;\r
- TreeItem item = ((Tree) event.widget).getItems()[0];\r
- IAdaptable adaptable = (IAdaptable) item.getData();\r
- MapNodeContext nc = (MapNodeContext) adaptable.getAdapter(NodeContext.class);\r
- parameterSupport.fireInput(context, new StructuredSelection(nc.getConstant(BuiltinKeys.INPUT)));\r
- propertyContainer.setContent(content);\r
- Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- }\r
- }\r
- }\r
- }\r
- };\r
-\r
- tree = explorer.getExplorerControl();\r
- tree.addListener(SWT.Activate, listener);\r
- tree.addListener(SWT.Show, listener);\r
- tree.addListener(SWT.Paint,listener);\r
- /* End listener for displaying information for first parameter during view initialization*/\r
- \r
- explorer.addDisposeListener(new DisposeListener() {\r
- \r
- @Override\r
- public void widgetDisposed(DisposeEvent e) {\r
- if(contentListener != null)\r
- contentListener.dispose(); \r
- }\r
- });\r
- \r
- \r
- buttonComposite = new Composite(explorer, SWT.NONE);\r
- \r
- addVariable = new Button(buttonComposite, support, SWT.NONE);\r
- addVariable.setText("Add parameter");\r
- addVariable.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- \r
- Resource distribution = GraphUtils.create2(graph, sr.UniformDistribution,\r
- sr.UniformDistribution_minValue, 0.0,\r
- sr.UniformDistribution_maxValue, 10.0);\r
- \r
- Resource parameter = GraphUtils.create2(graph, sr.SensitivityAnalysisExperiment_Parameter,\r
- sr.SensitivityAnalysisExperiment_Parameter_propabilityDistribution, distribution,\r
- sr.SensitivityAnalysisExperiment_Parameter_variable, ChartUtils.emptyVariableName,\r
- L0.PartOf, input);\r
- \r
- Resource parameterList = graph.getPossibleObject(input, sr.SensitivityAnalysisExperiment_parameterList);\r
- ListUtils.insertBack(graph, parameterList, Collections.singleton(parameter));\r
- }\r
- });\r
-\r
- remove = new Button(buttonComposite, parameterSupport, SWT.NONE);\r
- remove.setText("Remove");\r
- remove.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
- if(input == null)\r
- return;\r
- \r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- \r
- Resource experiment = graph.getPossibleObject(input, L0.PartOf);\r
- Resource parameterList = graph.getPossibleObject(experiment, sr.SensitivityAnalysisExperiment_parameterList);\r
- \r
- if(ListUtils.toList(graph, parameterList).size() > 1)\r
- ListUtils.removeElement(graph, parameterList, input);\r
- \r
- }\r
- \r
- });\r
- propertyContainer.setContent(content);\r
- \r
- \r
- parameterPropertyGroup = new Group(content, SWT.NONE);\r
- \r
- parameterProperties = new Composite(parameterPropertyGroup, SWT.NONE);\r
-\r
- // Label\r
- labelVariable = new Label(parameterProperties, SWT.NONE);\r
- labelVariable.setText("Variable:");\r
-\r
- variable = new TrackedText(parameterProperties, parameterSupport, SWT.BORDER);\r
- variable.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));\r
- variable.addModifyListener(new VariableNameModifier(variable.getWidget(), parameterSupport, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_indexes));\r
- variable.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), variable.getWidget())));\r
- variable.setInputValidator(new ParameterExistsValidator(parameterSupport, variable));\r
- \r
- labelRange = new Label(parameterProperties, SWT.NONE);\r
- labelRange.setText("Range:");\r
- \r
- rangeComposite = new RangeComposite(parameterProperties, context, parameterSupport, SWT.NONE) {\r
- @Override\r
- protected Resource getIndexRelation(ReadGraph graph) {\r
- return SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_indexes;\r
- }\r
- };\r
- \r
-// TrackedText variable = new TrackedText(parameterProperties, parameterSupport, SWT.BORDER);\r
-// variable.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));\r
-// variable.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));\r
-// variable.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), variable.getWidget())));\r
-// GridDataFactory.fillDefaults().grab(true, false).applyTo(variable.getWidget());\r
-\r
- labelDistribution = new Label(parameterProperties, SWT.NONE);\r
- labelDistribution.setText("Distribution:");\r
-\r
- distributionSelector = new TrackedCombo(parameterProperties, parameterSupport, SWT.DROP_DOWN);\r
- distributionSelector.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {\r
-\r
- @Override\r
- public Map<String, Object> perform(ReadGraph graph, Resource input) throws DatabaseException {\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- Map<String, Object> items = new HashMap<String, Object>();\r
-\r
- items.put("Normal", SR.NormalDistribution);\r
- items.put("Uniform", SR.UniformDistribution);\r
- items.put("Interval", SR.Interval);\r
-\r
- return items;\r
- }\r
-\r
- });\r
-\r
- distributionSelector.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph, Resource parameter) throws DatabaseException {\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- Resource distribution = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);\r
- if(distribution == null)\r
- return null;\r
- \r
- if(graph.isInstanceOf(distribution, SR.UniformDistribution))\r
- return "Uniform";\r
- else if(graph.isInstanceOf(distribution, SR.NormalDistribution))\r
- return "Normal";\r
- else if(graph.isInstanceOf(distribution, SR.Interval))\r
- return "Interval";\r
- else\r
- return "";\r
-\r
- }\r
- });\r
-\r
- distributionSelector.addModifyListener(new ComboModifyListenerImpl<Resource>() {\r
-\r
- @Override\r
- public void applyText(WriteGraph graph, Resource input, String text)\r
- throws DatabaseException {\r
- if(text == null || text.isEmpty())\r
- return;\r
-\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
-\r
- Resource type = SR.UniformDistribution;\r
-\r
- if("Normal".equals(text))\r
- type = SR.NormalDistribution;\r
- else if("Interval".equals(text))\r
- type = SR.Interval; \r
-\r
- graph.deny(input, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);\r
-\r
- GraphUtils.create2(graph, type,\r
- SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse, input);\r
-\r
- dirty = true;\r
- }\r
- });\r
-\r
- distributionSelector.addModifyListener(new TextModifyListener() {\r
-\r
- @Override\r
- public void modifyText(TrackedModifyEvent e) {\r
- if(dirty) {\r
- parameterSupport.update();\r
- dirty = false;\r
- propertyContainer.setContent(content);\r
- Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- }\r
- }\r
- });\r
-\r
- dpw = new DistributionPropertyWidget(parameterProperties, context, parameterSupport, SWT.NONE);\r
- }\r
-\r
-\r
- @Override\r
- protected void createControlLayoutVertical() {\r
- \r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
- \r
- // Scrolled composite for displaying properties of a selection in explorer\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyContainer);\r
- GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
- \r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(content);\r
- GridLayoutFactory.fillDefaults().numColumns(1).applyTo(content);\r
-\r
- // Label\r
- GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(labelComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(labelComposite);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
- \r
- GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(n.getWidget());\r
- \r
- GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(seed.getWidget());\r
-\r
- GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
- \r
- GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
- \r
- Point tsize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(tsize);\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterPropertyGroup);\r
- GridLayoutFactory.fillDefaults().applyTo(parameterPropertyGroup);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterProperties);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parameterProperties);\r
-\r
- // Label\r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelVariable);\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(variable.getWidget());\r
- \r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelRange);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(rangeComposite);\r
- \r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelDistribution);\r
- \r
- GridDataFactory.fillDefaults().span(3, 1).grab(true, true).applyTo(dpw);\r
- GridLayoutFactory.fillDefaults().margins(6, 0).applyTo(dpw);\r
- }\r
- \r
- @Override\r
- protected void createControlLayoutHorizontal(boolean wideScreen) {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
- \r
- // Scrolled composite for displaying properties of a selection in explorer\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyContainer);\r
- GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
- \r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(content);\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(content);\r
-\r
- // Label\r
- GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(labelComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(8).applyTo(labelComposite);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());\r
- \r
- GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(n.getWidget());\r
- \r
- GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(seed.getWidget());\r
-\r
- GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
-\r
- GridDataFactory.fillDefaults().applyTo(buttonComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);\r
- \r
- Point tsize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(tsize);\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterPropertyGroup);\r
- GridLayoutFactory.fillDefaults().applyTo(parameterPropertyGroup);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterProperties);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parameterProperties);\r
-\r
- // Label\r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelVariable);\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(variable.getWidget());\r
- \r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelRange);\r
- \r
- GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(rangeComposite);\r
- \r
- GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelDistribution);\r
-\r
- GridDataFactory.fillDefaults().span(1, 1).grab(true, true).applyTo(dpw);\r
- GridLayoutFactory.fillDefaults().margins(6, 0).applyTo(dpw);\r
-\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011, 2014 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.sysdyn.ui.properties;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.resource.LocalResourceManager;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.events.DisposeEvent;
+import org.eclipse.swt.events.DisposeListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.BuiltinKeys;
+import org.simantics.browsing.ui.Column;
+import org.simantics.browsing.ui.Column.Align;
+import org.simantics.browsing.ui.NodeContext;
+import org.simantics.browsing.ui.common.ColumnKeys;
+import org.simantics.browsing.ui.common.NodeContextBuilder.MapNodeContext;
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;
+import org.simantics.browsing.ui.swt.widgets.Button;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;
+import org.simantics.browsing.ui.swt.widgets.TrackedCombo;
+import org.simantics.browsing.ui.swt.widgets.TrackedText;
+import org.simantics.browsing.ui.swt.widgets.impl.ComboModifyListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.TextModifyListener;
+import org.simantics.browsing.ui.swt.widgets.impl.TrackedModifyEvent;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.procedure.adapter.DisposableListener;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.ChartUtils;
+import org.simantics.jfreechart.chart.properties.AdjustableTab;
+import org.simantics.jfreechart.chart.properties.RangeComposite;
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.properties.widgets.factories.IntegerPropertyFactory;
+import org.simantics.sysdyn.ui.properties.widgets.factories.IntegerPropertyModifier;
+import org.simantics.sysdyn.ui.properties.widgets.sensitivity.DistributionPropertyWidget;
+import org.simantics.sysdyn.ui.properties.widgets.sensitivity.ParameterChildRule;
+import org.simantics.sysdyn.ui.properties.widgets.sensitivity.VariableNameModifier;
+import org.simantics.sysdyn.ui.validation.ParameterExistsValidator;
+import org.simantics.utils.RunnableWithObject;
+import org.simantics.utils.datastructures.ArrayMap;
+import org.simantics.utils.ui.AdaptionUtils;
+import org.simantics.utils.ui.validators.IntegerValidator;
+
+/**
+ * Tab for displaying sensitivity analysis experiment properties
+ *
+ * @author Tuomas Miettinen
+ *
+ */
+public class SensitivityAnalysisExperimentTab extends AdjustableTab implements Widget {
+
+ public SensitivityAnalysisExperimentTab(Object id) {
+ super(id);
+ }
+
+ private GraphExplorerComposite explorer;
+ private WidgetSupportImpl parameterSupport = new WidgetSupportImpl();
+ private ScrolledComposite propertyContainer;
+ private Composite parameterProperties;
+ private Composite content;
+ private Button remove;
+ private Resource experiment;
+
+ private boolean dirty = false;
+ private boolean dirtyMethod = false;
+
+ private DisposableListener<Collection<Resource>> contentListener;
+ private Composite labelComposite;
+ private Label labelName;
+ private Label labelNumber;
+ private Label labelMethod;
+ private TrackedCombo methodSelector;
+ private Label labelSeed;
+ private TrackedText seed;
+ private Tree tree;
+ private Composite buttonComposite;
+ private Group parameterPropertyGroup;
+ private Label labelVariable;
+ private TrackedText variable;
+ private Label labelRange;
+ private RangeComposite rangeComposite;
+ private Label labelDistribution;
+ private TrackedCombo distributionSelector;
+ private DistributionPropertyWidget dpw;
+ private TrackedText name;
+ private TrackedText n;
+ private Button addVariable;
+
+ @Override
+ public void createControls(Composite body, IWorkbenchSite site,
+ final ISessionContext context, final WidgetSupport support) {
+ support.register(this);
+ super.createControls(body, site, context, support);
+ }
+
+ /**
+ * Updates the content of propertyContainer
+ * @param context
+ */
+ private void updateSelection(ISessionContext context) {
+ ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);
+ IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();
+ parameterSupport.fireInput(context, selection);
+
+ propertyContainer.setContent(content);
+ Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ }
+
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ experiment = AdaptionUtils.adaptToSingle(input, Resource.class);
+ if(contentListener == null) {
+ contentListener = new DisposableListener<Collection<Resource>>() {
+
+ @Override
+ public void execute(Collection<Resource> result) {
+ if(remove != null && !remove.getWidget().isDisposed() && result != null) {
+ remove.getWidget().getDisplay().asyncExec(new RunnableWithObject(result) {
+ @Override
+ public void run() {
+ if(!remove.getWidget().isDisposed()) {
+ @SuppressWarnings("unchecked")
+ Collection<Resource> result = (Collection<Resource>) getObject();
+ if(result.size() > 1)
+ remove.getWidget().setEnabled(true);
+ else
+ remove.getWidget().setEnabled(false);
+ }
+ }
+ });
+
+ }
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+ };
+
+ Simantics.getSession().asyncRequest(new Read<Collection<Resource>> () {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {
+ return (Collection<Resource>) new ParameterChildRule().getChildren(graph, experiment);
+ }
+
+ }, contentListener);
+ }
+
+ }
+
+
+ @Override
+ protected void createAndAddControls(Composite body, IWorkbenchSite site,
+ final ISessionContext context, final WidgetSupport support) {
+
+ composite = new RemoveFocusBeforeExperimentComposite(body, SWT.NONE);
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);
+ propertyContainer.setExpandHorizontal(true);
+ propertyContainer.setExpandVertical(true);
+
+ content = new Composite(propertyContainer, SWT.NONE);
+
+ // Label
+ labelComposite = new Composite(content, SWT.NONE);
+ labelName = new Label(labelComposite, SWT.NONE);
+ labelName.setText("Name");
+
+ name = new TrackedText(labelComposite, support, SWT.BORDER);
+ name.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasLabel));
+ name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasLabel));
+ name.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasName));
+ name.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), name.getWidget())));
+
+ labelNumber = new Label(labelComposite, SWT.NONE);
+ labelNumber.setText("Number of runs");
+
+ n = new TrackedText(labelComposite, support, SWT.BORDER);
+ n.setTextFactory(new IntegerPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_numberOfValues));
+ n.addModifyListener(new IntegerPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_numberOfValues));
+ n.setInputValidator(new IntegerValidator());
+ n.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), n.getWidget())));
+
+ labelMethod = new Label(labelComposite, SWT.NONE);
+ labelMethod.setText("Method");
+
+ methodSelector = new TrackedCombo(labelComposite, support, SWT.DROP_DOWN);
+ methodSelector.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {
+
+ @Override
+ public Map<String, Object> perform(ReadGraph graph, Resource input) throws DatabaseException {
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ Map<String, Object> items = new HashMap<String, Object>();
+
+ items.put("Halton", SR.HaltonSequenceGenerator);
+ items.put("Random", SR.RandomGenerator);
+
+ return items;
+ }
+
+ });
+ methodSelector.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {
+
+ @Override
+ public String perform(ReadGraph graph, Resource parameter) throws DatabaseException {
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ Resource method = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_method);
+ if(method == null)
+ return null;
+
+ if(graph.isInstanceOf(method, SR.RandomGenerator))
+ return "Random";
+ else if(graph.isInstanceOf(method, SR.HaltonSequenceGenerator))
+ return "Halton";
+ else
+ return "";
+
+ }
+ });
+ methodSelector.addModifyListener(new ComboModifyListenerImpl<Resource>() {
+
+ @Override
+ public void applyText(WriteGraph graph, Resource input, String text)
+ throws DatabaseException {
+ if(text == null || text.isEmpty())
+ return;
+
+ SysdynResource SR = SysdynResource.getInstance(graph);
+
+ Resource type = SR.RandomGenerator;
+
+ if("Halton".equals(text))
+ type = SR.HaltonSequenceGenerator;
+
+ graph.deny(input, SR.SensitivityAnalysisExperiment_method);
+
+ GraphUtils.create2(graph, type,
+ SR.SensitivityAnalysisExperiment_method_Inverse, input);
+
+ dirtyMethod = true;
+ }
+ });
+ methodSelector.addModifyListener(new TextModifyListener() {
+
+ @Override
+ public void modifyText(TrackedModifyEvent e) {
+ if(dirtyMethod) {
+ support.update();
+ dirtyMethod = false;
+ propertyContainer.setContent(content);
+ Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ }
+ }
+ });
+
+ labelSeed = new Label(labelComposite, SWT.NONE);
+ labelSeed.setText("Seed");
+
+ seed = new TrackedText(labelComposite, support, SWT.BORDER);
+ seed.setTextFactory(new IntegerPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_randomSeed));
+ seed.addModifyListener(new IntegerPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_randomSeed));
+ seed.setInputValidator(new IntegerValidator());
+ seed.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), seed.getWidget())));
+
+ // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis
+ explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter", "treeView").values(false, false, true), site, content, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);
+
+ explorer.setBrowseContexts(SysdynResource.URIs.SensitivityAnalysisExperiment_ParameterBrowseContext);
+ explorer.setInputSource(new SingleSelectionInputSource(
+ Resource.class));
+ explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning
+ explorer.setColumns( new Column[] { new Column(ColumnKeys.SINGLE, Align.LEFT, 0, "", true) });
+ explorer.finish();
+
+
+ ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ updateSelection(context);
+ }
+ });
+
+ /* Listener for displaying information of the first parameter during view initialization
+ * The view does not have focus, so normal selection listener mechanisms do not work.
+ * Need to do it the hard way.
+ */
+ Listener listener = new Listener() {
+
+ boolean flag = false;
+ @Override
+ public void handleEvent(Event event) {
+ switch (event.type) {
+ case SWT.Activate:
+ case SWT.Show:
+ case SWT.Paint:
+ {
+ if(!flag && ((Tree) event.widget).getItems().length > 0) {
+ flag = true;
+ TreeItem item = ((Tree) event.widget).getItems()[0];
+ IAdaptable adaptable = (IAdaptable) item.getData();
+ MapNodeContext nc = (MapNodeContext) adaptable.getAdapter(NodeContext.class);
+ parameterSupport.fireInput(context, new StructuredSelection(nc.getConstant(BuiltinKeys.INPUT)));
+ propertyContainer.setContent(content);
+ Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ }
+ }
+ }
+ }
+ };
+
+ tree = explorer.getExplorerControl();
+ tree.addListener(SWT.Activate, listener);
+ tree.addListener(SWT.Show, listener);
+ tree.addListener(SWT.Paint,listener);
+ /* End listener for displaying information for first parameter during view initialization*/
+
+ explorer.addDisposeListener(new DisposeListener() {
+
+ @Override
+ public void widgetDisposed(DisposeEvent e) {
+ if(contentListener != null)
+ contentListener.dispose();
+ }
+ });
+
+
+ buttonComposite = new Composite(explorer, SWT.NONE);
+
+ addVariable = new Button(buttonComposite, support, SWT.NONE);
+ addVariable.setText("Add parameter");
+ addVariable.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ @Override
+ public void apply(WriteGraph graph, Resource input) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 L0 = Layer0.getInstance(graph);
+
+ Resource distribution = GraphUtils.create2(graph, sr.UniformDistribution,
+ sr.UniformDistribution_minValue, 0.0,
+ sr.UniformDistribution_maxValue, 10.0);
+
+ Resource parameter = GraphUtils.create2(graph, sr.SensitivityAnalysisExperiment_Parameter,
+ sr.SensitivityAnalysisExperiment_Parameter_propabilityDistribution, distribution,
+ sr.SensitivityAnalysisExperiment_Parameter_variable, ChartUtils.emptyVariableName,
+ L0.PartOf, input);
+
+ Resource parameterList = graph.getPossibleObject(input, sr.SensitivityAnalysisExperiment_parameterList);
+ ListUtils.insertBack(graph, parameterList, Collections.singleton(parameter));
+ }
+ });
+
+ remove = new Button(buttonComposite, parameterSupport, SWT.NONE);
+ remove.setText("Remove");
+ remove.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ @Override
+ public void apply(WriteGraph graph, Resource input) throws DatabaseException {
+ if(input == null)
+ return;
+
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 L0 = Layer0.getInstance(graph);
+
+ Resource experiment = graph.getPossibleObject(input, L0.PartOf);
+ Resource parameterList = graph.getPossibleObject(experiment, sr.SensitivityAnalysisExperiment_parameterList);
+
+ if(ListUtils.toList(graph, parameterList).size() > 1)
+ ListUtils.removeElement(graph, parameterList, input);
+
+ }
+
+ });
+ propertyContainer.setContent(content);
+
+
+ parameterPropertyGroup = new Group(content, SWT.NONE);
+
+ parameterProperties = new Composite(parameterPropertyGroup, SWT.NONE);
+
+ // Label
+ labelVariable = new Label(parameterProperties, SWT.NONE);
+ labelVariable.setText("Variable:");
+
+ variable = new TrackedText(parameterProperties, parameterSupport, SWT.BORDER);
+ variable.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));
+ variable.addModifyListener(new VariableNameModifier(variable.getWidget(), parameterSupport, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_indexes));
+ variable.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), variable.getWidget())));
+ variable.setInputValidator(new ParameterExistsValidator(parameterSupport, variable));
+
+ labelRange = new Label(parameterProperties, SWT.NONE);
+ labelRange.setText("Range:");
+
+ rangeComposite = new RangeComposite(parameterProperties, context, parameterSupport, SWT.NONE) {
+ @Override
+ protected Resource getIndexRelation(ReadGraph graph) {
+ return SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_indexes;
+ }
+ };
+
+// TrackedText variable = new TrackedText(parameterProperties, parameterSupport, SWT.BORDER);
+// variable.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));
+// variable.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.SensitivityAnalysisExperiment_Parameter_variable));
+// variable.setColorProvider(new SysdynBasicColorProvider(new LocalResourceManager(JFaceResources.getResources(), variable.getWidget())));
+// GridDataFactory.fillDefaults().grab(true, false).applyTo(variable.getWidget());
+
+ labelDistribution = new Label(parameterProperties, SWT.NONE);
+ labelDistribution.setText("Distribution:");
+
+ distributionSelector = new TrackedCombo(parameterProperties, parameterSupport, SWT.DROP_DOWN);
+ distributionSelector.setItemFactory(new ReadFactoryImpl<Resource, Map<String,Object>>() {
+
+ @Override
+ public Map<String, Object> perform(ReadGraph graph, Resource input) throws DatabaseException {
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ Map<String, Object> items = new HashMap<String, Object>();
+
+ items.put("Normal", SR.NormalDistribution);
+ items.put("Uniform", SR.UniformDistribution);
+ items.put("Interval", SR.Interval);
+
+ return items;
+ }
+
+ });
+
+ distributionSelector.setSelectionFactory(new ReadFactoryImpl<Resource, String>() {
+
+ @Override
+ public String perform(ReadGraph graph, Resource parameter) throws DatabaseException {
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ Resource distribution = graph.getPossibleObject(parameter, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);
+ if(distribution == null)
+ return null;
+
+ if(graph.isInstanceOf(distribution, SR.UniformDistribution))
+ return "Uniform";
+ else if(graph.isInstanceOf(distribution, SR.NormalDistribution))
+ return "Normal";
+ else if(graph.isInstanceOf(distribution, SR.Interval))
+ return "Interval";
+ else
+ return "";
+
+ }
+ });
+
+ distributionSelector.addModifyListener(new ComboModifyListenerImpl<Resource>() {
+
+ @Override
+ public void applyText(WriteGraph graph, Resource input, String text)
+ throws DatabaseException {
+ if(text == null || text.isEmpty())
+ return;
+
+ SysdynResource SR = SysdynResource.getInstance(graph);
+
+ Resource type = SR.UniformDistribution;
+
+ if("Normal".equals(text))
+ type = SR.NormalDistribution;
+ else if("Interval".equals(text))
+ type = SR.Interval;
+
+ graph.deny(input, SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution);
+
+ GraphUtils.create2(graph, type,
+ SR.SensitivityAnalysisExperiment_Parameter_propabilityDistribution_Inverse, input);
+
+ dirty = true;
+ }
+ });
+
+ distributionSelector.addModifyListener(new TextModifyListener() {
+
+ @Override
+ public void modifyText(TrackedModifyEvent e) {
+ if(dirty) {
+ parameterSupport.update();
+ dirty = false;
+ propertyContainer.setContent(content);
+ Point size = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ }
+ }
+ });
+
+ dpw = new DistributionPropertyWidget(parameterProperties, context, parameterSupport, SWT.NONE);
+ }
+
+
+ @Override
+ protected void createControlLayoutVertical() {
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyContainer);
+ GridLayoutFactory.fillDefaults().applyTo(propertyContainer);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(content);
+ GridLayoutFactory.fillDefaults().numColumns(1).applyTo(content);
+
+ // Label
+ GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(labelComposite);
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(labelComposite);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());
+
+ GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(n.getWidget());
+
+ GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(seed.getWidget());
+
+ GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).grab(false, true).applyTo(explorer);
+
+ GridDataFactory.fillDefaults().applyTo(buttonComposite);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);
+
+ Point tsize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(tsize);
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterPropertyGroup);
+ GridLayoutFactory.fillDefaults().applyTo(parameterPropertyGroup);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterProperties);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parameterProperties);
+
+ // Label
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelVariable);
+
+ GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(variable.getWidget());
+
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelRange);
+
+ GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(rangeComposite);
+
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelDistribution);
+
+ GridDataFactory.fillDefaults().span(3, 1).grab(true, true).applyTo(dpw);
+ GridLayoutFactory.fillDefaults().margins(6, 0).applyTo(dpw);
+ }
+
+ @Override
+ protected void createControlLayoutHorizontal(boolean wideScreen) {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(propertyContainer);
+ GridLayoutFactory.fillDefaults().applyTo(propertyContainer);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(content);
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(content);
+
+ // Label
+ GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(labelComposite);
+ GridLayoutFactory.fillDefaults().numColumns(8).applyTo(labelComposite);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(name.getWidget());
+
+ GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(n.getWidget());
+
+ GridDataFactory.fillDefaults().hint(50, SWT.DEFAULT).applyTo(seed.getWidget());
+
+ GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);
+
+ GridDataFactory.fillDefaults().applyTo(buttonComposite);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite);
+
+ Point tsize = content.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(tsize);
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterPropertyGroup);
+ GridLayoutFactory.fillDefaults().applyTo(parameterPropertyGroup);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(parameterProperties);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parameterProperties);
+
+ // Label
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelVariable);
+
+ GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(variable.getWidget());
+
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelRange);
+
+ GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(rangeComposite);
+
+ GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).applyTo(labelDistribution);
+
+ GridDataFactory.fillDefaults().span(1, 1).grab(true, true).applyTo(dpw);
+ GridLayoutFactory.fillDefaults().margins(6, 0).applyTo(dpw);
+
+ }
+
+}
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
import org.simantics.browsing.ui.NodeContext;
import org.simantics.browsing.ui.common.AdaptableHintContext;
import org.simantics.browsing.ui.swt.SingleSelectionInputSource;
import org.simantics.layer0.Layer0;
import org.simantics.sysdyn.SysdynResource;
import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;
-import org.simantics.ui.SimanticsUI;
import org.simantics.utils.datastructures.ArrayMap;
import org.simantics.utils.ui.AdaptionUtils;
IAdaptable a = (IAdaptable)o;
final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);
if(node != null) {
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
@Override
public void perform(WriteGraph graph) throws DatabaseException {
IAdaptable a = (IAdaptable)o;
final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);
if(node != null) {
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
@Override
public void perform(WriteGraph graph) throws DatabaseException {
-/*******************************************************************************\r
- * Copyright (c) 2010, 2011, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties;\r
-\r
-import java.awt.Color;\r
-import java.awt.Font;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.resource.FontDescriptor;\r
-import org.eclipse.jface.resource.JFaceResources;\r
-import org.eclipse.jface.resource.LocalResourceManager;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.SWTException;\r
-import org.eclipse.swt.graphics.FontData;\r
-import org.eclipse.swt.graphics.RGB;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Display;\r
-import org.eclipse.swt.widgets.Group;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
-import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.diagram.G2DUtils;\r
-import org.simantics.diagram.stubs.G2DResource;\r
-import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.properties.widgets.CustomFontDialog;\r
-import org.simantics.sysdyn.ui.properties.widgets.ValveOrientationGroup;\r
-import org.simantics.sysdyn.ui.properties.widgets.ValveTextLocationGroup;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-import org.simantics.utils.datastructures.Triple;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-import org.simantics.utils.ui.validators.DoubleValidator;\r
-\r
-/**\r
- * Information tab for additional information of variables. \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class VariableInformationTab extends AdjustableTab implements Widget {\r
- \r
- public VariableInformationTab(Object id) {\r
- super(id);\r
- }\r
-\r
- private Composite orientationComposite;\r
- private WidgetSupport support;\r
- private Resource component;\r
- private org.simantics.browsing.ui.swt.widgets.Label sample;\r
- private LocalResourceManager resourceManager;\r
-\r
- @Override\r
- public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
- this.support = support;\r
- support.register(this);\r
- \r
- // Create a ResourceManager to dispose images when the widget is disposed.\r
- this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), body);\r
- \r
- super.createControls(body, site, context, support);\r
- }\r
-\r
- private Read<Pair<Font, Color>> fontAndColorRead;\r
- private Group informationGroup;\r
- private TrackedText information;\r
- private Group rangeGroup;\r
- private Label label;\r
- private TrackedText rangeStart;\r
- private TrackedText rangeEnd;\r
- private TrackedText rangeStep;\r
- private Composite fontComposite;\r
- private Button b;\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- component = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- // is the displayed variable a valve?\r
- Boolean isValve = false;\r
- try {\r
- isValve = context.getSession().syncRequest(new Read<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- return graph.isInstanceOf(component, sr.Valve);\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- // if it is a valve, display the orientation information\r
- if(isValve) {\r
- ValveOrientationGroup vog = new ValveOrientationGroup(orientationComposite, context, support, SWT.NONE);\r
- vog.setInput(context, input);\r
- ValveTextLocationGroup vtlg = new ValveTextLocationGroup(orientationComposite, context, support, SWT.NONE);\r
- vtlg.setInput(context, input);\r
- orientationComposite.getParent().layout();\r
- }\r
-\r
- // Read font and color information for sample text\r
- if(fontAndColorRead == null) {\r
- fontAndColorRead = new Read<Pair<Font, Color>>() {\r
-\r
- @Override\r
- public Pair<Font, Color> perform(ReadGraph graph) throws DatabaseException {\r
- Font font = null;\r
- Color color = null;\r
- if(component != null) {\r
- Resource element = graph.getPossibleObject(component, ModelingResources.getInstance(graph).ComponentToElement);\r
- if(element != null) {\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- Resource fontResource = graph.getPossibleObject(element, g2d.HasFont);\r
- if(fontResource != null)\r
- font = G2DUtils.getFont(graph, fontResource);\r
- Resource colorResource = graph.getPossibleObject(element, g2d.HasColor);\r
- if(colorResource != null)\r
- color = G2DUtils.getColor(graph, colorResource);\r
- }\r
- }\r
- return new Pair<Font, Color>(font, color);\r
- }\r
- };\r
-\r
- SimanticsUI.getSession().asyncRequest(fontAndColorRead, new Listener<Pair<Font, Color>>() {\r
-\r
- @Override\r
- public void execute(final Pair<Font, Color> result) {\r
- final Display device;\r
- try {\r
- device = sample.getWidget().getDisplay();\r
- } catch (SWTException e) {\r
- // Widget is disposed, the GUI probably did'n function as fast as the user commanded.\r
- // Thus do nothing.\r
- return;\r
- }\r
- \r
- device.asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- try {\r
- if(sample.getWidget().isDisposed())\r
- return;\r
- } catch (SWTException e) {\r
- // Widget is disposed, the GUI probably did'n function as fast as the user commanded.\r
- // Thus do nothing.\r
- return;\r
- }\r
- if(result.first != null) {\r
- FontData fd = toSwtFontData(result.first);\r
- sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(fd)));\r
- }\r
- if(result.second != null) {\r
- RGB rgb = new RGB(result.second.getRed(), result.second.getGreen(), \r
- result.second.getBlue());\r
- sample.setForeground(resourceManager.createColor(rgb));\r
- }\r
- try {\r
- sample.getWidget().getParent().getParent().layout();\r
- } catch (SWTException e) {\r
-\r
- }\r
- }\r
- });\r
-\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return sample == null || sample.getWidget().isDisposed();\r
- }\r
-\r
- });\r
- }\r
- }\r
-\r
- /**\r
- * Create SWT FontData based on AWT Font\r
- * @param font AWT Font\r
- * @return SWT FontData based on AWT Font\r
- */\r
- private static FontData toSwtFontData(Font font) {\r
- FontData fontData = new FontData();\r
- fontData.setName(font.getFamily());\r
- fontData.setStyle(font.getStyle());\r
- fontData.setHeight(font.getSize());\r
- return fontData;\r
- }\r
-\r
- @Override\r
- protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
- ISessionContext context, WidgetSupport _support) {\r
-\r
- composite = new Composite(body, SWT.NONE);\r
-\r
- informationGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);\r
- informationGroup.setText("Information");\r
-\r
- // Textual format documentation\r
- information = new TrackedText(informationGroup, support, SWT.MULTI | SWT.BORDER);\r
- information.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasDescription));\r
- information.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasDescription));\r
-\r
- // Orientation information for valves\r
- orientationComposite = new Composite(composite, SWT.NONE);\r
-\r
- // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts\r
- rangeGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);\r
- rangeGroup.setText("Range");\r
-\r
- label = new Label(rangeGroup, SWT.NONE);\r
- label.setText("Start");\r
-\r
- rangeStart = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);\r
- rangeStart.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeStart));\r
- rangeStart.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeStart));\r
- rangeStart.setInputValidator(new DoubleValidator());\r
-\r
- label = new Label(rangeGroup, SWT.NONE);\r
- label.setText("End");\r
-\r
-\r
- rangeEnd = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);\r
- rangeEnd.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeEnd));\r
- rangeEnd.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeEnd));\r
- rangeEnd.setInputValidator(new DoubleValidator());\r
-\r
- label = new Label(rangeGroup, SWT.NONE);\r
- label.setText("Step");\r
-\r
- rangeStep = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);\r
- rangeStep.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeStep));\r
- rangeStep.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeStep));\r
- rangeStep.setInputValidator(new DoubleValidator());\r
-\r
- \r
- // Font options. FIXME: very bad appearance right now\r
- \r
- fontComposite = new Composite(composite, SWT.NONE);\r
- b = new Button(fontComposite, support, SWT.PUSH);\r
- b.setText("Choose Font");\r
-\r
- // Sample text with selected font\r
- sample = new org.simantics.browsing.ui.swt.widgets.Label(fontComposite, support, SWT.NONE);\r
- sample.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName, "Sample"));\r
-\r
- b.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- Font f;\r
- Color color;\r
- Object input;\r
-\r
- @Override\r
- public void beforeApply() {\r
-\r
- Triple<Font, Color, String> result = null;\r
-\r
- try {\r
- result = SimanticsUI.getSession().syncRequest(new Read<Triple<Font, Color, String>>(){\r
-\r
- @Override\r
- public Triple<Font, Color, String> perform(ReadGraph graph) throws DatabaseException {\r
- Resource component = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
- String name = NameUtils.getSafeName(graph, component);\r
-\r
- Resource element = graph.getPossibleObject(component, ModelingResources.getInstance(graph).ComponentToElement);\r
- if(element != null) {\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- Resource fontResource = graph.getPossibleObject(element, g2d.HasFont);\r
- Resource colorResource = graph.getPossibleObject(element, g2d.HasColor);\r
-\r
- Font font = null;\r
- if(fontResource != null)\r
- font = G2DUtils.getFont(graph, fontResource);\r
- Color color = null;\r
- if(colorResource != null)\r
- color = G2DUtils.getColor(graph, colorResource);\r
-\r
- return new Triple<Font, Color, String>(font, color, name);\r
- }\r
-\r
- return null;\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- }\r
-\r
-\r
- CustomFontDialog dialog = new CustomFontDialog(composite.getShell(), (result != null ? result.third : null));\r
-\r
- if(result != null) {\r
- if(result.first != null) {\r
- dialog.setAWTFont(result.first);\r
- f = result.first;\r
- }\r
- if(result.second != null) {\r
- dialog.setColor(result.second);\r
- color = result.second;\r
- }\r
- }\r
-\r
- dialog.open();\r
- if(dialog.getAWTFont() != null)\r
- f = dialog.getAWTFont();\r
- if(dialog.getAWTColor() != null) {\r
- color = dialog.getAWTColor();\r
- }\r
-\r
- FontData fd = dialog.getSWTFontData();\r
- if(fd != null)\r
- sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(fd)));\r
- RGB rgb = dialog.getRGB(); \r
- if(rgb != null)\r
- sample.setForeground(resourceManager.createColor(rgb));\r
- fontComposite.layout();\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource input) throws DatabaseException {\r
- graph.markUndoPoint();\r
- Resource element = graph.getPossibleObject(input, ModelingResources.getInstance(graph).ComponentToElement);\r
- if(element != null) {\r
- G2DResource g2d = G2DResource.getInstance(graph);\r
- graph.deny(element, g2d.HasFont);\r
- StringBuilder sb = new StringBuilder();\r
- if(f != null) {\r
- graph.claim(element, g2d.HasFont, G2DUtils.createFont(graph, f));\r
- sb.append(" font to " + f.getName());\r
- }\r
- graph.deny(element, g2d.HasColor);\r
- if(color != null) {\r
- graph.claim(element, g2d.HasColor, G2DUtils.createColor(graph, color));\r
- sb.append(" color to " + color.getRGB());\r
- }\r
- sb.insert(0, "Modified");\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- }\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object parameter) {\r
- super.setInput(context, parameter);\r
- input = parameter;\r
- }\r
-\r
- });\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutVertical() {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(informationGroup);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(informationGroup);\r
-\r
- // Textual format documentation\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());\r
-\r
- // Orientation information for valves\r
- GridDataFactory.fillDefaults().span(1, 2).applyTo(orientationComposite);\r
- GridLayoutFactory.fillDefaults().margins(3,3).applyTo(orientationComposite);\r
-\r
- // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts\r
- GridDataFactory.fillDefaults().applyTo(rangeGroup);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(rangeGroup);\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStart.getWidget());\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeEnd.getWidget());\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStep.getWidget());\r
-\r
- GridDataFactory.fillDefaults().applyTo(fontComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(1).applyTo(fontComposite);\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutHorizontal(boolean wideScreen) {\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(informationGroup);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(informationGroup);\r
-\r
- // Textual format documentation\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());\r
-\r
- // Orientation information for valves\r
- GridDataFactory.fillDefaults().span(1, 2).applyTo(orientationComposite);\r
- GridLayoutFactory.fillDefaults().margins(3,3).applyTo(orientationComposite);\r
-\r
- // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts\r
- GridDataFactory.fillDefaults().applyTo(rangeGroup);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(6).applyTo(rangeGroup);\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStart.getWidget());\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeEnd.getWidget());\r
-\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStep.getWidget());\r
-\r
- GridDataFactory.fillDefaults().applyTo(fontComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(fontComposite);\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2011, 2014 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.sysdyn.ui.properties;
+
+import java.awt.Color;
+import java.awt.Font;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.resource.FontDescriptor;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.resource.LocalResourceManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.SWTException;
+import org.eclipse.swt.graphics.FontData;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.Button;
+import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;
+import org.simantics.browsing.ui.swt.widgets.StringPropertyModifier;
+import org.simantics.browsing.ui.swt.widgets.TrackedText;
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.diagram.G2DUtils;
+import org.simantics.diagram.stubs.G2DResource;
+import org.simantics.jfreechart.chart.properties.AdjustableTab;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.properties.widgets.CustomFontDialog;
+import org.simantics.sysdyn.ui.properties.widgets.ValveOrientationGroup;
+import org.simantics.sysdyn.ui.properties.widgets.ValveTextLocationGroup;
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;
+import org.simantics.utils.datastructures.Pair;
+import org.simantics.utils.datastructures.Triple;
+import org.simantics.utils.ui.AdaptionUtils;
+import org.simantics.utils.ui.ISelectionUtils;
+import org.simantics.utils.ui.validators.DoubleValidator;
+
+/**
+ * Information tab for additional information of variables.
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class VariableInformationTab extends AdjustableTab implements Widget {
+
+ public VariableInformationTab(Object id) {
+ super(id);
+ }
+
+ private Composite orientationComposite;
+ private WidgetSupport support;
+ private Resource component;
+ private org.simantics.browsing.ui.swt.widgets.Label sample;
+ private LocalResourceManager resourceManager;
+
+ @Override
+ public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {
+ this.support = support;
+ support.register(this);
+
+ // Create a ResourceManager to dispose images when the widget is disposed.
+ this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), body);
+
+ super.createControls(body, site, context, support);
+ }
+
+ private Read<Pair<Font, Color>> fontAndColorRead;
+ private Group informationGroup;
+ private TrackedText information;
+ private Group rangeGroup;
+ private Label label;
+ private TrackedText rangeStart;
+ private TrackedText rangeEnd;
+ private TrackedText rangeStep;
+ private Composite fontComposite;
+ private Button b;
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ component = AdaptionUtils.adaptToSingle(input, Resource.class);
+ // is the displayed variable a valve?
+ Boolean isValve = false;
+ try {
+ isValve = context.getSession().syncRequest(new Read<Boolean>() {
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ return graph.isInstanceOf(component, sr.Valve);
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ // if it is a valve, display the orientation information
+ if(isValve) {
+ ValveOrientationGroup vog = new ValveOrientationGroup(orientationComposite, context, support, SWT.NONE);
+ vog.setInput(context, input);
+ ValveTextLocationGroup vtlg = new ValveTextLocationGroup(orientationComposite, context, support, SWT.NONE);
+ vtlg.setInput(context, input);
+ orientationComposite.getParent().layout();
+ }
+
+ // Read font and color information for sample text
+ if(fontAndColorRead == null) {
+ fontAndColorRead = new Read<Pair<Font, Color>>() {
+
+ @Override
+ public Pair<Font, Color> perform(ReadGraph graph) throws DatabaseException {
+ Font font = null;
+ Color color = null;
+ if(component != null) {
+ Resource element = graph.getPossibleObject(component, ModelingResources.getInstance(graph).ComponentToElement);
+ if(element != null) {
+ G2DResource g2d = G2DResource.getInstance(graph);
+ Resource fontResource = graph.getPossibleObject(element, g2d.HasFont);
+ if(fontResource != null)
+ font = G2DUtils.getFont(graph, fontResource);
+ Resource colorResource = graph.getPossibleObject(element, g2d.HasColor);
+ if(colorResource != null)
+ color = G2DUtils.getColor(graph, colorResource);
+ }
+ }
+ return new Pair<Font, Color>(font, color);
+ }
+ };
+
+ Simantics.getSession().asyncRequest(fontAndColorRead, new Listener<Pair<Font, Color>>() {
+
+ @Override
+ public void execute(final Pair<Font, Color> result) {
+ final Display device;
+ try {
+ device = sample.getWidget().getDisplay();
+ } catch (SWTException e) {
+ // Widget is disposed, the GUI probably did'n function as fast as the user commanded.
+ // Thus do nothing.
+ return;
+ }
+
+ device.asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ if(sample.getWidget().isDisposed())
+ return;
+ } catch (SWTException e) {
+ // Widget is disposed, the GUI probably did'n function as fast as the user commanded.
+ // Thus do nothing.
+ return;
+ }
+ if(result.first != null) {
+ FontData fd = toSwtFontData(result.first);
+ sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(fd)));
+ }
+ if(result.second != null) {
+ RGB rgb = new RGB(result.second.getRed(), result.second.getGreen(),
+ result.second.getBlue());
+ sample.setForeground(resourceManager.createColor(rgb));
+ }
+ try {
+ sample.getWidget().getParent().getParent().layout();
+ } catch (SWTException e) {
+
+ }
+ }
+ });
+
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return sample == null || sample.getWidget().isDisposed();
+ }
+
+ });
+ }
+ }
+
+ /**
+ * Create SWT FontData based on AWT Font
+ * @param font AWT Font
+ * @return SWT FontData based on AWT Font
+ */
+ private static FontData toSwtFontData(Font font) {
+ FontData fontData = new FontData();
+ fontData.setName(font.getFamily());
+ fontData.setStyle(font.getStyle());
+ fontData.setHeight(font.getSize());
+ return fontData;
+ }
+
+ @Override
+ protected void createAndAddControls(Composite body, IWorkbenchSite site,
+ ISessionContext context, WidgetSupport _support) {
+
+ composite = new Composite(body, SWT.NONE);
+
+ informationGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
+ informationGroup.setText("Information");
+
+ // Textual format documentation
+ information = new TrackedText(informationGroup, support, SWT.MULTI | SWT.BORDER);
+ information.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasDescription));
+ information.addModifyListener(new StringPropertyModifier(context, Layer0.URIs.HasDescription));
+
+ // Orientation information for valves
+ orientationComposite = new Composite(composite, SWT.NONE);
+
+ // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts
+ rangeGroup = new Group(composite, SWT.SHADOW_ETCHED_IN);
+ rangeGroup.setText("Range");
+
+ label = new Label(rangeGroup, SWT.NONE);
+ label.setText("Start");
+
+ rangeStart = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);
+ rangeStart.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeStart));
+ rangeStart.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeStart));
+ rangeStart.setInputValidator(new DoubleValidator());
+
+ label = new Label(rangeGroup, SWT.NONE);
+ label.setText("End");
+
+
+ rangeEnd = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);
+ rangeEnd.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeEnd));
+ rangeEnd.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeEnd));
+ rangeEnd.setInputValidator(new DoubleValidator());
+
+ label = new Label(rangeGroup, SWT.NONE);
+ label.setText("Step");
+
+ rangeStep = new TrackedText(rangeGroup, support, SWT.RIGHT | SWT.BORDER);
+ rangeStep.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.HasRangeStep));
+ rangeStep.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.HasRangeStep));
+ rangeStep.setInputValidator(new DoubleValidator());
+
+
+ // Font options. FIXME: very bad appearance right now
+
+ fontComposite = new Composite(composite, SWT.NONE);
+ b = new Button(fontComposite, support, SWT.PUSH);
+ b.setText("Choose Font");
+
+ // Sample text with selected font
+ sample = new org.simantics.browsing.ui.swt.widgets.Label(fontComposite, support, SWT.NONE);
+ sample.setTextFactory(new StringPropertyFactory(Layer0.URIs.HasName, "Sample"));
+
+ b.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ Font f;
+ Color color;
+ Object input;
+
+ @Override
+ public void beforeApply() {
+
+ Triple<Font, Color, String> result = null;
+
+ try {
+ result = Simantics.getSession().syncRequest(new Read<Triple<Font, Color, String>>(){
+
+ @Override
+ public Triple<Font, Color, String> perform(ReadGraph graph) throws DatabaseException {
+ Resource component = ISelectionUtils.filterSingleSelection(input, Resource.class);
+ String name = NameUtils.getSafeName(graph, component);
+
+ Resource element = graph.getPossibleObject(component, ModelingResources.getInstance(graph).ComponentToElement);
+ if(element != null) {
+ G2DResource g2d = G2DResource.getInstance(graph);
+ Resource fontResource = graph.getPossibleObject(element, g2d.HasFont);
+ Resource colorResource = graph.getPossibleObject(element, g2d.HasColor);
+
+ Font font = null;
+ if(fontResource != null)
+ font = G2DUtils.getFont(graph, fontResource);
+ Color color = null;
+ if(colorResource != null)
+ color = G2DUtils.getColor(graph, colorResource);
+
+ return new Triple<Font, Color, String>(font, color, name);
+ }
+
+ return null;
+ }
+
+ });
+ } catch (DatabaseException e) {
+ }
+
+
+ CustomFontDialog dialog = new CustomFontDialog(composite.getShell(), (result != null ? result.third : null));
+
+ if(result != null) {
+ if(result.first != null) {
+ dialog.setAWTFont(result.first);
+ f = result.first;
+ }
+ if(result.second != null) {
+ dialog.setColor(result.second);
+ color = result.second;
+ }
+ }
+
+ dialog.open();
+ if(dialog.getAWTFont() != null)
+ f = dialog.getAWTFont();
+ if(dialog.getAWTColor() != null) {
+ color = dialog.getAWTColor();
+ }
+
+ FontData fd = dialog.getSWTFontData();
+ if(fd != null)
+ sample.setFont(resourceManager.createFont(FontDescriptor.createFrom(fd)));
+ RGB rgb = dialog.getRGB();
+ if(rgb != null)
+ sample.setForeground(resourceManager.createColor(rgb));
+ fontComposite.layout();
+ }
+
+ @Override
+ public void apply(WriteGraph graph, Resource input) throws DatabaseException {
+ graph.markUndoPoint();
+ Resource element = graph.getPossibleObject(input, ModelingResources.getInstance(graph).ComponentToElement);
+ if(element != null) {
+ G2DResource g2d = G2DResource.getInstance(graph);
+ graph.deny(element, g2d.HasFont);
+ StringBuilder sb = new StringBuilder();
+ if(f != null) {
+ graph.claim(element, g2d.HasFont, G2DUtils.createFont(graph, f));
+ sb.append(" font to " + f.getName());
+ }
+ graph.deny(element, g2d.HasColor);
+ if(color != null) {
+ graph.claim(element, g2d.HasColor, G2DUtils.createColor(graph, color));
+ sb.append(" color to " + color.getRGB());
+ }
+ sb.insert(0, "Modified");
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+ }
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object parameter) {
+ super.setInput(context, parameter);
+ input = parameter;
+ }
+
+ });
+ }
+
+ @Override
+ protected void createControlLayoutVertical() {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(informationGroup);
+ GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(informationGroup);
+
+ // Textual format documentation
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());
+
+ // Orientation information for valves
+ GridDataFactory.fillDefaults().span(1, 2).applyTo(orientationComposite);
+ GridLayoutFactory.fillDefaults().margins(3,3).applyTo(orientationComposite);
+
+ // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts
+ GridDataFactory.fillDefaults().applyTo(rangeGroup);
+ GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(rangeGroup);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStart.getWidget());
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeEnd.getWidget());
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStep.getWidget());
+
+ GridDataFactory.fillDefaults().applyTo(fontComposite);
+ GridLayoutFactory.fillDefaults().numColumns(1).applyTo(fontComposite);
+ }
+
+ @Override
+ protected void createControlLayoutHorizontal(boolean wideScreen) {
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(informationGroup);
+ GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(informationGroup);
+
+ // Textual format documentation
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(information.getWidget());
+
+ // Orientation information for valves
+ GridDataFactory.fillDefaults().span(1, 2).applyTo(orientationComposite);
+ GridLayoutFactory.fillDefaults().margins(3,3).applyTo(orientationComposite);
+
+ // Range of a variable (e.g. from 0 to 10). Does not affect simulation, but the infor can be used for example in charts
+ GridDataFactory.fillDefaults().applyTo(rangeGroup);
+ GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(6).applyTo(rangeGroup);
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStart.getWidget());
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeEnd.getWidget());
+
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(rangeStep.getWidget());
+
+ GridDataFactory.fillDefaults().applyTo(fontComposite);
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(fontComposite);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets;\r
-\r
-import java.awt.event.MouseEvent;\r
-import java.awt.geom.Point2D;\r
-import java.io.StringReader;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.Iterator;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.FocusEvent;\r
-import org.eclipse.swt.events.FocusListener;\r
-import org.eclipse.swt.events.KeyEvent;\r
-import org.eclipse.swt.events.KeyListener;\r
-import org.eclipse.swt.events.MouseListener;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Event;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.eclipse.swt.widgets.TableItem;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.tableParser.ParseException;\r
-import org.simantics.sysdyn.tableParser.TableParser;\r
-import org.simantics.sysdyn.tableParser.Token;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupInputOutputTable;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupInputOutputTable.InputOutput;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-\r
-public class ChartTableWidget implements Widget {\r
-\r
- Text input, output;\r
- Button add;\r
- LookupInputOutputTable table;\r
- Resource expression;\r
-\r
- public ChartTableWidget(Composite parent, WidgetSupport support, int style) {\r
- support.register(this);\r
- Composite valueTableComposite = new Composite(parent, SWT.NONE);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(valueTableComposite);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(valueTableComposite);\r
-\r
- table = new LookupInputOutputTable(valueTableComposite, SWT.NONE);\r
- GridDataFactory.fillDefaults().span(3, 1).grab(false, true).applyTo(table);\r
- table.getTableViewer().getTable().addMouseListener(new MouseListener() {\r
-\r
- @Override\r
- public void mouseUp(org.eclipse.swt.events.MouseEvent e) {\r
- if(e.button == MouseEvent.BUTTON3) {\r
- Table t = (Table)e.widget;\r
- TableItem item = (TableItem)t.getItem(new org.eclipse.swt.graphics.Point(e.x, e.y));\r
- table.removeItem(t.indexOf(item));\r
- tableModified();\r
- }\r
- }\r
- @Override\r
- public void mouseDown(org.eclipse.swt.events.MouseEvent e) { }\r
- @Override\r
- public void mouseDoubleClick(org.eclipse.swt.events.MouseEvent e) { }\r
- });\r
-\r
- input = new Text(valueTableComposite, SWT.BORDER | SWT.RIGHT);\r
- input.setText("");\r
- output = new Text(valueTableComposite, SWT.BORDER | SWT.RIGHT);\r
- output.setText("");\r
-\r
- add = new Button(valueTableComposite, SWT.None);\r
- add.setText("Add");\r
- add.addSelectionListener(new SelectionListener() {\r
-\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- try {\r
- Double in = Double.parseDouble(input.getText());\r
- Double out = Double.parseDouble(output.getText());\r
- table.addLocation(new Point2D.Double(in, out));\r
- tableModified();\r
- } catch (NumberFormatException e1) {\r
- }\r
- input.setText("");\r
- output.setText("");\r
- }\r
-\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {}\r
- });\r
-\r
- FocusListener flistener = new FocusListener() {\r
- @Override\r
- public void focusGained(FocusEvent e) {\r
- Text text = (Text)e.widget;\r
- text.setSelection(0, text.getCharCount());\r
- }\r
- @Override\r
- public void focusLost(FocusEvent e) { }\r
- };\r
-\r
-\r
- KeyListener listener = new KeyListener() {\r
-\r
- @Override\r
- public void keyPressed(KeyEvent e) {\r
- if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {\r
- try {\r
- Double in = Double.parseDouble(input.getText());\r
- Double out = Double.parseDouble(output.getText());\r
- table.addLocation(new Point2D.Double(in, out));\r
- tableModified();\r
- } catch (NumberFormatException e1) {\r
- if(input.getText().isEmpty() && output.getText().isEmpty()) {\r
- add.forceFocus();\r
- return;\r
- }\r
- }\r
- input.setText("");\r
- output.setText("");\r
- input.setFocus();\r
- } \r
- }\r
-\r
- @Override\r
- public void keyReleased(KeyEvent e) { }\r
-\r
- };\r
-\r
- input.addFocusListener(flistener);\r
- input.addKeyListener(listener);\r
- output.addFocusListener(flistener);\r
- output.addKeyListener(listener);\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
-\r
- expression = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
-\r
-\r
- try {\r
- SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(!graph.isInstanceOf(expression, sr.WithLookupExpression))\r
- return null;\r
- return graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);\r
- }\r
- }, new Listener<String>() {\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(String lookup) {\r
- if(lookup == null) return;\r
- TableParser parser = new TableParser(new StringReader(""));\r
- parser.ReInit(new StringReader(lookup));\r
- table.clearTable();\r
- try {\r
- parser.table();\r
- ArrayList<Token> xTokens = parser.getXTokens();\r
- ArrayList<Token> yTokens = parser.getYTokens();\r
- for(int i = 0; i < xTokens.size(); i++) {\r
- table.addLocation(new Point2D.Double(\r
- Double.parseDouble(xTokens.get(i).image), \r
- Double.parseDouble(yTokens.get(i).image)));\r
- }\r
- } catch (ParseException e1) {\r
- }\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return table.isDisposed();\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- table.addListener(SWT.Modify, new org.eclipse.swt.widgets.Listener() {\r
-\r
- @Override\r
- public void handleEvent(Event event) {\r
- tableModified();\r
- }\r
- });\r
- }\r
- \r
- \r
- @SuppressWarnings("unchecked")\r
- private void tableModified() {\r
- StringBuilder b = new StringBuilder();\r
- b.append("{");\r
- ArrayList<InputOutput> inputOutputList = (ArrayList<InputOutput>)table.getTableViewer().getInput();\r
- Collections.sort(inputOutputList, table.new InputOutputComparator());\r
- Iterator<InputOutput> iterator = inputOutputList.iterator();\r
- while(iterator.hasNext()){\r
- InputOutput io = iterator.next();\r
- b.append("{" + io.getInput(String.class) + "," + io.getOutput(String.class) + "}");\r
- if(iterator.hasNext())\r
- b.append(",");\r
- }\r
- b.append("}");\r
- final String table = b.toString();\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table);\r
- }\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets;
+
+import java.awt.event.MouseEvent;
+import java.awt.geom.Point2D;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.events.KeyEvent;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.swt.widgets.Text;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.tableParser.ParseException;
+import org.simantics.sysdyn.tableParser.TableParser;
+import org.simantics.sysdyn.tableParser.Token;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupInputOutputTable;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupInputOutputTable.InputOutput;
+import org.simantics.utils.ui.ISelectionUtils;
+
+public class ChartTableWidget implements Widget {
+
+ Text input, output;
+ Button add;
+ LookupInputOutputTable table;
+ Resource expression;
+
+ public ChartTableWidget(Composite parent, WidgetSupport support, int style) {
+ support.register(this);
+ Composite valueTableComposite = new Composite(parent, SWT.NONE);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(valueTableComposite);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(valueTableComposite);
+
+ table = new LookupInputOutputTable(valueTableComposite, SWT.NONE);
+ GridDataFactory.fillDefaults().span(3, 1).grab(false, true).applyTo(table);
+ table.getTableViewer().getTable().addMouseListener(new MouseListener() {
+
+ @Override
+ public void mouseUp(org.eclipse.swt.events.MouseEvent e) {
+ if(e.button == MouseEvent.BUTTON3) {
+ Table t = (Table)e.widget;
+ TableItem item = (TableItem)t.getItem(new org.eclipse.swt.graphics.Point(e.x, e.y));
+ table.removeItem(t.indexOf(item));
+ tableModified();
+ }
+ }
+ @Override
+ public void mouseDown(org.eclipse.swt.events.MouseEvent e) { }
+ @Override
+ public void mouseDoubleClick(org.eclipse.swt.events.MouseEvent e) { }
+ });
+
+ input = new Text(valueTableComposite, SWT.BORDER | SWT.RIGHT);
+ input.setText("");
+ output = new Text(valueTableComposite, SWT.BORDER | SWT.RIGHT);
+ output.setText("");
+
+ add = new Button(valueTableComposite, SWT.None);
+ add.setText("Add");
+ add.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ try {
+ Double in = Double.parseDouble(input.getText());
+ Double out = Double.parseDouble(output.getText());
+ table.addLocation(new Point2D.Double(in, out));
+ tableModified();
+ } catch (NumberFormatException e1) {
+ }
+ input.setText("");
+ output.setText("");
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {}
+ });
+
+ FocusListener flistener = new FocusListener() {
+ @Override
+ public void focusGained(FocusEvent e) {
+ Text text = (Text)e.widget;
+ text.setSelection(0, text.getCharCount());
+ }
+ @Override
+ public void focusLost(FocusEvent e) { }
+ };
+
+
+ KeyListener listener = new KeyListener() {
+
+ @Override
+ public void keyPressed(KeyEvent e) {
+ if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {
+ try {
+ Double in = Double.parseDouble(input.getText());
+ Double out = Double.parseDouble(output.getText());
+ table.addLocation(new Point2D.Double(in, out));
+ tableModified();
+ } catch (NumberFormatException e1) {
+ if(input.getText().isEmpty() && output.getText().isEmpty()) {
+ add.forceFocus();
+ return;
+ }
+ }
+ input.setText("");
+ output.setText("");
+ input.setFocus();
+ }
+ }
+
+ @Override
+ public void keyReleased(KeyEvent e) { }
+
+ };
+
+ input.addFocusListener(flistener);
+ input.addKeyListener(listener);
+ output.addFocusListener(flistener);
+ output.addKeyListener(listener);
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+
+ expression = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);
+
+
+ try {
+ Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(!graph.isInstanceOf(expression, sr.WithLookupExpression))
+ return null;
+ return graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);
+ }
+ }, new Listener<String>() {
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public void execute(String lookup) {
+ if(lookup == null) return;
+ TableParser parser = new TableParser(new StringReader(""));
+ parser.ReInit(new StringReader(lookup));
+ table.clearTable();
+ try {
+ parser.table();
+ ArrayList<Token> xTokens = parser.getXTokens();
+ ArrayList<Token> yTokens = parser.getYTokens();
+ for(int i = 0; i < xTokens.size(); i++) {
+ table.addLocation(new Point2D.Double(
+ Double.parseDouble(xTokens.get(i).image),
+ Double.parseDouble(yTokens.get(i).image)));
+ }
+ } catch (ParseException e1) {
+ }
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return table.isDisposed();
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ table.addListener(SWT.Modify, new org.eclipse.swt.widgets.Listener() {
+
+ @Override
+ public void handleEvent(Event event) {
+ tableModified();
+ }
+ });
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private void tableModified() {
+ StringBuilder b = new StringBuilder();
+ b.append("{");
+ ArrayList<InputOutput> inputOutputList = (ArrayList<InputOutput>)table.getTableViewer().getInput();
+ Collections.sort(inputOutputList, table.new InputOutputComparator());
+ Iterator<InputOutput> iterator = inputOutputList.iterator();
+ while(iterator.hasNext()){
+ InputOutput io = iterator.next();
+ b.append("{" + io.getInput(String.class) + "," + io.getOutput(String.class) + "}");
+ if(iterator.hasNext())
+ b.append(",");
+ }
+ b.append("}");
+ final String table = b.toString();
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table);
+ }
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets;\r
-\r
-import java.awt.BasicStroke;\r
-import java.awt.Color;\r
-import java.awt.GridLayout;\r
-import java.awt.geom.Ellipse2D;\r
-import java.io.StringReader;\r
-import java.util.ArrayList;\r
-import java.util.Iterator;\r
-\r
-import javax.swing.JComponent;\r
-import javax.swing.JPanel;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.jfree.chart.ChartFactory;\r
-import org.jfree.chart.JFreeChart;\r
-import org.jfree.chart.axis.ValueAxis;\r
-import org.jfree.chart.plot.PlotOrientation;\r
-import org.jfree.chart.plot.XYPlot;\r
-import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\r
-import org.jfree.data.general.SeriesChangeEvent;\r
-import org.jfree.data.general.SeriesChangeListener;\r
-import org.jfree.data.xy.XYDataItem;\r
-import org.jfree.data.xy.XYDataset;\r
-import org.jfree.data.xy.XYSeries;\r
-import org.jfree.data.xy.XYSeriesCollection;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.tableParser.ParseException;\r
-import org.simantics.sysdyn.tableParser.TableParser;\r
-import org.simantics.sysdyn.tableParser.Token;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupChartPanel;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-import org.simantics.utils.ui.SWTAWTComponent;\r
-\r
-public class ChartWidget implements Widget {\r
-\r
- JFreeChart chart;\r
- LookupChartPanel chartPanel;\r
- SWTAWTComponent swtawtcomponent;\r
-\r
- public ChartWidget(Composite parent, WidgetSupport support, int style) {\r
- support.register(this);\r
- chartPanel = new LookupChartPanel(createChart());\r
- chartPanel.setMouseZoomable(true, false);\r
- chartPanel.setDomainZoomable(false);\r
- chartPanel.setRangeZoomable(false);\r
-\r
- swtawtcomponent = new SWTAWTComponent(parent, SWT.BORDER) {\r
- @Override\r
- protected JComponent createSwingComponent() {\r
- JPanel panel = new JPanel();\r
- panel.setLayout(new GridLayout(1, 1));\r
- panel.add(chartPanel);\r
- panel.doLayout();\r
- return panel;\r
- }\r
- };\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(swtawtcomponent);\r
- swtawtcomponent.populate();\r
-\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
-\r
- final Resource expression = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
-\r
- class Auxiliary {\r
- Double minX, minY, maxX, maxY;\r
- String table;\r
- }\r
-\r
- try {\r
- SimanticsUI.getSession().syncRequest(new Read<Auxiliary>() {\r
-\r
- @Override\r
- public Auxiliary perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(!graph.isInstanceOf(expression, sr.WithLookupExpression))\r
- return null;\r
- Auxiliary auxiliary = new Auxiliary();\r
- auxiliary.minX = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_minX);\r
- auxiliary.maxX = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_maxX);\r
- auxiliary.minY = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_minY);\r
- auxiliary.maxY = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_maxY);\r
- auxiliary.table = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);\r
- return auxiliary;\r
- }\r
- }, new Listener<Auxiliary>() {\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(Auxiliary result) {\r
- if(result == null) return;\r
- XYDataset dataset = createDataset(result.table);\r
- chartPanel.resetChart(dataset);\r
- chartPanel.addSeriesChangeListener(new _SeriesChangeListener(expression));\r
- \r
- XYPlot plot = (XYPlot) chart.getPlot();\r
- ValueAxis rangeAxis = plot.getRangeAxis();\r
- rangeAxis.setAutoRange(false);\r
- if(result.minY == null) result.minY = rangeAxis.getLowerBound();\r
- if(result.maxY == null) result.maxY = rangeAxis.getUpperBound();\r
- rangeAxis.setRange(result.minY, result.maxY);\r
- ValueAxis domainAxis = plot.getDomainAxis();\r
- domainAxis.setAutoRange(false);\r
- if(result.minX == null) result.minX = domainAxis.getLowerBound();\r
- if(result.maxX == null) result.maxX = domainAxis.getUpperBound();\r
- domainAxis.setRange(result.minX, result.maxX);\r
-\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return swtawtcomponent.isDisposed();\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- private JFreeChart createChart() {\r
- XYDataset dataset = createDataset(null);\r
- chart = ChartFactory.createXYLineChart(null, null, null,\r
- dataset, PlotOrientation.VERTICAL, false, true, false);\r
- XYPlot plot = (XYPlot) chart.getPlot();\r
- XYLineAndShapeRenderer renderer\r
- = (XYLineAndShapeRenderer) plot.getRenderer();\r
- renderer.setBaseShapesVisible(true);\r
- renderer.setDrawOutlines(true);\r
- renderer.setUseFillPaint(true);\r
- renderer.setBaseFillPaint(Color.white);\r
- renderer.setSeriesStroke(0, new BasicStroke(3.0f));\r
- renderer.setSeriesOutlineStroke(0, new BasicStroke(2.0f));\r
- renderer.setSeriesShape(0, new Ellipse2D.Double(-5.0, -5.0, 10.0, 10.0));\r
- return chart;\r
- }\r
-\r
- public XYDataset createDataset(String table) {\r
- XYSeries series = new XYSeries("Series");\r
- \r
- if(table != null) {\r
- TableParser parser = new TableParser(new StringReader(""));\r
- parser.ReInit(new StringReader(table));\r
- try {\r
- parser.table();\r
- ArrayList<Token> xTokens = parser.getXTokens();\r
- ArrayList<Token> yTokens = parser.getYTokens();\r
- for(int i = 0; i < xTokens.size(); i++) {\r
- series.add(\r
- Double.parseDouble(xTokens.get(i).image), \r
- Double.parseDouble(yTokens.get(i).image));\r
- }\r
- } catch (ParseException e1) {\r
- }\r
- }\r
- \r
- XYSeriesCollection dataset = new XYSeriesCollection();\r
- dataset.addSeries(series);\r
- return dataset;\r
- }\r
-\r
- public LookupChartPanel getChartPanel() {\r
- return this.chartPanel;\r
- }\r
-\r
- public JFreeChart getChart() {\r
- return this.chart;\r
- }\r
-\r
- private class _SeriesChangeListener implements SeriesChangeListener {\r
-\r
- Resource expression;\r
- \r
- public _SeriesChangeListener(Resource expression) {\r
- this.expression = expression;\r
- }\r
- @Override\r
- public void seriesChanged(SeriesChangeEvent event) {\r
- if(chartPanel.isDragging()) return;\r
-\r
- StringBuilder b = new StringBuilder();\r
- b.append("{");\r
- XYSeriesCollection collection = (XYSeriesCollection) ((XYPlot)chart.getPlot()).getDataset();\r
- XYSeries series = collection.getSeries(0);\r
- if(series.isEmpty())\r
- return;\r
- Iterator<?> iterator = series.getItems().iterator();\r
- while(iterator.hasNext()){\r
- XYDataItem item = (XYDataItem)iterator.next();\r
- b.append("{" + item.getX() + "," + item.getY() + "}");\r
- if(iterator.hasNext())\r
- b.append(",");\r
- }\r
- b.append("}");\r
- final String table = b.toString();\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table);\r
- }\r
- });\r
-\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.GridLayout;
+import java.awt.geom.Ellipse2D;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import javax.swing.JComponent;
+import javax.swing.JPanel;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.jfree.chart.ChartFactory;
+import org.jfree.chart.JFreeChart;
+import org.jfree.chart.axis.ValueAxis;
+import org.jfree.chart.plot.PlotOrientation;
+import org.jfree.chart.plot.XYPlot;
+import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
+import org.jfree.data.general.SeriesChangeEvent;
+import org.jfree.data.general.SeriesChangeListener;
+import org.jfree.data.xy.XYDataItem;
+import org.jfree.data.xy.XYDataset;
+import org.jfree.data.xy.XYSeries;
+import org.jfree.data.xy.XYSeriesCollection;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.tableParser.ParseException;
+import org.simantics.sysdyn.tableParser.TableParser;
+import org.simantics.sysdyn.tableParser.Token;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupChartPanel;
+import org.simantics.utils.ui.ISelectionUtils;
+import org.simantics.utils.ui.SWTAWTComponent;
+
+public class ChartWidget implements Widget {
+
+ JFreeChart chart;
+ LookupChartPanel chartPanel;
+ SWTAWTComponent swtawtcomponent;
+
+ public ChartWidget(Composite parent, WidgetSupport support, int style) {
+ support.register(this);
+ chartPanel = new LookupChartPanel(createChart());
+ chartPanel.setMouseZoomable(true, false);
+ chartPanel.setDomainZoomable(false);
+ chartPanel.setRangeZoomable(false);
+
+ swtawtcomponent = new SWTAWTComponent(parent, SWT.BORDER) {
+ @Override
+ protected JComponent createSwingComponent() {
+ JPanel panel = new JPanel();
+ panel.setLayout(new GridLayout(1, 1));
+ panel.add(chartPanel);
+ panel.doLayout();
+ return panel;
+ }
+ };
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(swtawtcomponent);
+ swtawtcomponent.populate();
+
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+
+ final Resource expression = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);
+
+ class Auxiliary {
+ Double minX, minY, maxX, maxY;
+ String table;
+ }
+
+ try {
+ Simantics.getSession().syncRequest(new Read<Auxiliary>() {
+
+ @Override
+ public Auxiliary perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(!graph.isInstanceOf(expression, sr.WithLookupExpression))
+ return null;
+ Auxiliary auxiliary = new Auxiliary();
+ auxiliary.minX = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_minX);
+ auxiliary.maxX = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_maxX);
+ auxiliary.minY = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_minY);
+ auxiliary.maxY = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_maxY);
+ auxiliary.table = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);
+ return auxiliary;
+ }
+ }, new Listener<Auxiliary>() {
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public void execute(Auxiliary result) {
+ if(result == null) return;
+ XYDataset dataset = createDataset(result.table);
+ chartPanel.resetChart(dataset);
+ chartPanel.addSeriesChangeListener(new _SeriesChangeListener(expression));
+
+ XYPlot plot = (XYPlot) chart.getPlot();
+ ValueAxis rangeAxis = plot.getRangeAxis();
+ rangeAxis.setAutoRange(false);
+ if(result.minY == null) result.minY = rangeAxis.getLowerBound();
+ if(result.maxY == null) result.maxY = rangeAxis.getUpperBound();
+ rangeAxis.setRange(result.minY, result.maxY);
+ ValueAxis domainAxis = plot.getDomainAxis();
+ domainAxis.setAutoRange(false);
+ if(result.minX == null) result.minX = domainAxis.getLowerBound();
+ if(result.maxX == null) result.maxX = domainAxis.getUpperBound();
+ domainAxis.setRange(result.minX, result.maxX);
+
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return swtawtcomponent.isDisposed();
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private JFreeChart createChart() {
+ XYDataset dataset = createDataset(null);
+ chart = ChartFactory.createXYLineChart(null, null, null,
+ dataset, PlotOrientation.VERTICAL, false, true, false);
+ XYPlot plot = (XYPlot) chart.getPlot();
+ XYLineAndShapeRenderer renderer
+ = (XYLineAndShapeRenderer) plot.getRenderer();
+ renderer.setBaseShapesVisible(true);
+ renderer.setDrawOutlines(true);
+ renderer.setUseFillPaint(true);
+ renderer.setBaseFillPaint(Color.white);
+ renderer.setSeriesStroke(0, new BasicStroke(3.0f));
+ renderer.setSeriesOutlineStroke(0, new BasicStroke(2.0f));
+ renderer.setSeriesShape(0, new Ellipse2D.Double(-5.0, -5.0, 10.0, 10.0));
+ return chart;
+ }
+
+ public XYDataset createDataset(String table) {
+ XYSeries series = new XYSeries("Series");
+
+ if(table != null) {
+ TableParser parser = new TableParser(new StringReader(""));
+ parser.ReInit(new StringReader(table));
+ try {
+ parser.table();
+ ArrayList<Token> xTokens = parser.getXTokens();
+ ArrayList<Token> yTokens = parser.getYTokens();
+ for(int i = 0; i < xTokens.size(); i++) {
+ series.add(
+ Double.parseDouble(xTokens.get(i).image),
+ Double.parseDouble(yTokens.get(i).image));
+ }
+ } catch (ParseException e1) {
+ }
+ }
+
+ XYSeriesCollection dataset = new XYSeriesCollection();
+ dataset.addSeries(series);
+ return dataset;
+ }
+
+ public LookupChartPanel getChartPanel() {
+ return this.chartPanel;
+ }
+
+ public JFreeChart getChart() {
+ return this.chart;
+ }
+
+ private class _SeriesChangeListener implements SeriesChangeListener {
+
+ Resource expression;
+
+ public _SeriesChangeListener(Resource expression) {
+ this.expression = expression;
+ }
+ @Override
+ public void seriesChanged(SeriesChangeEvent event) {
+ if(chartPanel.isDragging()) return;
+
+ StringBuilder b = new StringBuilder();
+ b.append("{");
+ XYSeriesCollection collection = (XYSeriesCollection) ((XYPlot)chart.getPlot()).getDataset();
+ XYSeries series = collection.getSeries(0);
+ if(series.isEmpty())
+ return;
+ Iterator<?> iterator = series.getItems().iterator();
+ while(iterator.hasNext()){
+ XYDataItem item = (XYDataItem)iterator.next();
+ b.append("{" + item.getX() + "," + item.getY() + "}");
+ if(iterator.hasNext())
+ b.append(",");
+ }
+ b.append("}");
+ final String table = b.toString();
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table);
+ }
+ });
+
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Expression type representations\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ExpressionTypes {\r
-\r
- public static enum ExpressionType {Auxiliary, Parameter, Constant, Lookup, WithLookup, Stock, Delay, Empty};\r
-\r
- public static ExpressionType[] auxiliaryExpressions = new ExpressionType[] {\r
- ExpressionType.Auxiliary, \r
- ExpressionType.Parameter, \r
- ExpressionType.Constant, \r
- ExpressionType.Delay,\r
- // ExpressionType.Lookup, \r
- ExpressionType.WithLookup};\r
-\r
- public static ExpressionType[] valveExpressions = new ExpressionType[] {\r
- ExpressionType.Auxiliary, \r
- ExpressionType.Parameter, \r
- ExpressionType.Constant, \r
- ExpressionType.Delay,\r
- ExpressionType.WithLookup};\r
-\r
- public static ExpressionType[] stockExpressions = new ExpressionType[] {\r
- ExpressionType.Stock};\r
-\r
- public static ExpressionType getExpressionType(final Resource expression) {\r
- try {\r
- return SimanticsUI.getSession().syncRequest(new Read<ExpressionType>() {\r
-\r
- @Override\r
- public ExpressionType perform(ReadGraph graph) throws DatabaseException {\r
- return getExpressionType(graph, expression);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- return null;\r
- }\r
-\r
- }\r
- \r
- public static ExpressionType getExpressionType(ReadGraph graph, final Resource expression) throws DatabaseException {\r
- ExpressionType et = null;\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(graph.isInstanceOf(expression, sr.NormalExpression)) {\r
- et = ExpressionType.Auxiliary;\r
- } else if (graph.isInstanceOf(expression, sr.StockExpression)) {\r
- et = ExpressionType.Stock;\r
- } else if (graph.isInstanceOf(expression, sr.ParameterExpression)) {\r
- et = ExpressionType.Parameter;\r
- } else if (graph.isInstanceOf(expression, sr.ConstantExpression)) {\r
- et = ExpressionType.Constant;\r
- } else if (graph.isInstanceOf(expression, sr.DelayExpression)) {\r
- et = ExpressionType.Delay;\r
- } else if (graph.isInstanceOf(expression, sr.LookupExpression)) {\r
- et = ExpressionType.Lookup;\r
- } else if (graph.isInstanceOf(expression, sr.WithLookupExpression)) {\r
- et = ExpressionType.WithLookup;\r
- } else {\r
- et = ExpressionType.Empty;\r
- }\r
- return et;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets;
+
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * Expression type representations
+ * @author Teemu Lempinen
+ *
+ */
+public class ExpressionTypes {
+
+ public static enum ExpressionType {Auxiliary, Parameter, Constant, Lookup, WithLookup, Stock, Delay, Empty};
+
+ public static ExpressionType[] auxiliaryExpressions = new ExpressionType[] {
+ ExpressionType.Auxiliary,
+ ExpressionType.Parameter,
+ ExpressionType.Constant,
+ ExpressionType.Delay,
+ // ExpressionType.Lookup,
+ ExpressionType.WithLookup};
+
+ public static ExpressionType[] valveExpressions = new ExpressionType[] {
+ ExpressionType.Auxiliary,
+ ExpressionType.Parameter,
+ ExpressionType.Constant,
+ ExpressionType.Delay,
+ ExpressionType.WithLookup};
+
+ public static ExpressionType[] stockExpressions = new ExpressionType[] {
+ ExpressionType.Stock};
+
+ public static ExpressionType getExpressionType(final Resource expression) {
+ try {
+ return Simantics.getSession().syncRequest(new Read<ExpressionType>() {
+
+ @Override
+ public ExpressionType perform(ReadGraph graph) throws DatabaseException {
+ return getExpressionType(graph, expression);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ return null;
+ }
+
+ }
+
+ public static ExpressionType getExpressionType(ReadGraph graph, final Resource expression) throws DatabaseException {
+ ExpressionType et = null;
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(graph.isInstanceOf(expression, sr.NormalExpression)) {
+ et = ExpressionType.Auxiliary;
+ } else if (graph.isInstanceOf(expression, sr.StockExpression)) {
+ et = ExpressionType.Stock;
+ } else if (graph.isInstanceOf(expression, sr.ParameterExpression)) {
+ et = ExpressionType.Parameter;
+ } else if (graph.isInstanceOf(expression, sr.ConstantExpression)) {
+ et = ExpressionType.Constant;
+ } else if (graph.isInstanceOf(expression, sr.DelayExpression)) {
+ et = ExpressionType.Delay;
+ } else if (graph.isInstanceOf(expression, sr.LookupExpression)) {
+ et = ExpressionType.Lookup;
+ } else if (graph.isInstanceOf(expression, sr.WithLookupExpression)) {
+ et = ExpressionType.WithLookup;
+ } else {
+ et = ExpressionType.Empty;
+ }
+ return et;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets;\r
-\r
-import java.awt.event.ActionEvent;\r
-import java.awt.event.ActionListener;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
-import javax.swing.Timer;\r
-\r
-import org.eclipse.jface.resource.JFaceResources;\r
-import org.eclipse.jface.resource.LocalResourceManager;\r
-import org.eclipse.swt.custom.VerifyKeyListener;\r
-import org.eclipse.swt.events.FocusListener;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes.ExpressionType;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.AuxiliaryExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ConstantExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.DelayExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.EmptyExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionComposite;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.IExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ParameterExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.StockExpression;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.WithLookupExpression;\r
-import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-/**\r
- * Widget for displaying an expression. Widget creates the IExpression for displaying\r
- * properties for each expression type and adds validation, saving and other services\r
- * to the active IExpression.\r
- * \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ExpressionWidget implements Widget {\r
-\r
- private ExpressionWidgetInput input;\r
- private Resource expr;\r
- private Variable variable;\r
- private Composite parent;\r
- private Map<String, Object> data;\r
- private IExpression expression;\r
- private ModifyListener modifyListener;\r
- private FocusListener focusListener;\r
- private Table variableTable;\r
- private VerifyKeyListener verifyKeyListener;\r
- private Timer validationTimer;\r
- private static int VALIDATION_DELAY_TIME = 500;\r
- private final LocalResourceManager resourceManager;\r
- \r
- /**\r
- * Create a new expression widget\r
- * @param parent\r
- * @param support\r
- * @param style\r
- */\r
- public ExpressionWidget(Composite parent, WidgetSupport support, int style) {\r
- support.register(this);\r
- this.parent = parent;\r
- if (parent instanceof ExpressionComposite) {\r
- ExpressionComposite expressionComposite = (ExpressionComposite)parent;\r
- expressionComposite.setExpressionWidget(this);\r
- }\r
- this.data = new HashMap<String, Object>();\r
- \r
- // Create a ResourceManager to dispose images when the widget is disposed.\r
- this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), this.parent);\r
- \r
- /*\r
- * Create a validation timer for expression fields. Validation timer\r
- * validates the field as the modeler is typing an expression \r
- */\r
- validationTimer = new Timer(VALIDATION_DELAY_TIME, new ActionListener() {\r
-\r
- @Override\r
- public void actionPerformed(ActionEvent e) {\r
- if(variableTable == null || variableTable.isDisposed())\r
- return;\r
- variableTable.getDisplay().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- validateFields();\r
- }\r
- });\r
- }\r
- });\r
- validationTimer.setRepeats(false);\r
- }\r
- \r
- @Override\r
- public void setInput(ISessionContext context, Object input) { \r
- // Update IExpression based on the newly selected expression\r
- ExpressionWidgetInput i = AdaptionUtils.adaptToSingle(input, ExpressionWidgetInput.class);\r
- this.input = i;\r
- expr = i.expression;\r
- variable = i.variable;\r
- ExpressionType et = ExpressionTypes.getExpressionType(expr);\r
- displayExpression(et.toString(), true);\r
- }\r
-\r
- /**\r
- * Displays IExpression corresponding to expressionType.\r
- * @param expressionType Expression type\r
- * @param original Is the displayed expression for a newly selected expression (true) or did the\r
- * expression change its type (false) \r
- */\r
- public void displayExpression(String expressionType, boolean original) {\r
- if(expressionType == null || parent.isDisposed()) {\r
- return;\r
- }\r
-\r
- // Get up-to-date data to data-map\r
- if(this.expression != null) expression.updateData(data);\r
- \r
- // Create the new expression\r
- ExpressionType et = ExpressionType.valueOf(expressionType);\r
- IExpression exp = null;\r
- switch (et) {\r
- case Auxiliary: \r
- exp = new AuxiliaryExpression(input); break;\r
- case Parameter: \r
- exp = new ParameterExpression(input); break;\r
- case Constant: \r
- exp = new ConstantExpression(input); break;\r
- case Lookup: \r
- exp = new LookupExpression(); break;\r
- case WithLookup: \r
- exp = new WithLookupExpression(input); break;\r
- case Stock: \r
- exp = new StockExpression(input); break;\r
- case Delay: \r
- exp = new DelayExpression(input); break;\r
- default: \r
- exp = new EmptyExpression();\r
- }\r
-\r
- if (exp != null) {\r
- // If expression was created, remove the old one\r
- for(Control c : parent.getChildren()) {\r
- c.dispose();\r
- } \r
-\r
- // If a completely new expression was selected, read data\r
- if(original) \r
- exp.readData(expr, data);\r
-\r
- // Create the visual representation of the expression type\r
- exp.createExpressionFields(parent, data, variableTable);\r
- \r
- // Add listeners\r
- if(modifyListener != null)\r
- exp.addModifyListener(modifyListener);\r
- if(focusListener != null)\r
- exp.addFocusListener(focusListener);\r
- if(verifyKeyListener != null)\r
- exp.addVerifyKeyListener(verifyKeyListener);\r
- this.expression = exp;\r
- this.parent.layout();\r
- validateFieldsTimed();\r
-\r
- save();\r
- } \r
- }\r
-\r
- /**\r
- * Get current IExpression\r
- * @return current IExpression\r
- */\r
- public IExpression getExpression() {\r
- return expression;\r
- }\r
-\r
- /**\r
- * Set the variable table that contains information about variables that are connected \r
- * to this expression\r
- * @param table\r
- */\r
- public void setVariableTable(Table table) {\r
- this.variableTable = table;\r
- }\r
-\r
- /**\r
- * Set timed field validation with default delay time\r
- */\r
- public void validateFieldsTimed() { \r
- validateFieldsTimed(VALIDATION_DELAY_TIME);\r
- }\r
- \r
- /**\r
- * Set timed field validation\r
- * @param delay Delay time for validation\r
- */\r
- public void validateFieldsTimed(int delay) {\r
- validationTimer.setDelay(delay);\r
- if(!validationTimer.isRunning())\r
- validationTimer.start();\r
- else\r
- validationTimer.restart();\r
- }\r
- \r
- /**\r
- * Validates expression fields in current IExpression\r
- */\r
- public void validateFields() {\r
- if(this.variableTable == null) return;\r
- \r
- try {\r
- // Find the variable for this experession\r
- Resource variable = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- return graph.getPossibleObject(expr, l0.PartOf);\r
- }\r
- });\r
- // Validate the variable\r
- if(variable != null)\r
- ExpressionUtils.validateExpressionFields(variable, expression, variableTable, resourceManager);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- }\r
-\r
- public void addModifyListener(ModifyListener listener) {\r
- this.modifyListener = listener;\r
- }\r
-\r
- public void addVerifyKeyListener(VerifyKeyListener listener) {\r
- this.verifyKeyListener = listener;\r
- }\r
- \r
- public void addFocusListener(FocusListener listener) {\r
- this.focusListener = listener;\r
- }\r
-\r
- public void save() {\r
- if(this.expression != null)\r
- this.expression.save(expr, data);\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.swing.Timer;
+
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.resource.LocalResourceManager;
+import org.eclipse.swt.custom.VerifyKeyListener;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Table;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.ui.properties.widgets.ExpressionTypes.ExpressionType;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.AuxiliaryExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ConstantExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.DelayExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.EmptyExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionComposite;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionWidgetInput;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.IExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.LookupExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ParameterExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.StockExpression;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.WithLookupExpression;
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;
+import org.simantics.utils.ui.AdaptionUtils;
+
+/**
+ * Widget for displaying an expression. Widget creates the IExpression for displaying
+ * properties for each expression type and adds validation, saving and other services
+ * to the active IExpression.
+ *
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class ExpressionWidget implements Widget {
+
+ private ExpressionWidgetInput input;
+ private Resource expr;
+ private Variable variable;
+ private Composite parent;
+ private Map<String, Object> data;
+ private IExpression expression;
+ private ModifyListener modifyListener;
+ private FocusListener focusListener;
+ private Table variableTable;
+ private VerifyKeyListener verifyKeyListener;
+ private Timer validationTimer;
+ private static int VALIDATION_DELAY_TIME = 500;
+ private final LocalResourceManager resourceManager;
+
+ /**
+ * Create a new expression widget
+ * @param parent
+ * @param support
+ * @param style
+ */
+ public ExpressionWidget(Composite parent, WidgetSupport support, int style) {
+ support.register(this);
+ this.parent = parent;
+ if (parent instanceof ExpressionComposite) {
+ ExpressionComposite expressionComposite = (ExpressionComposite)parent;
+ expressionComposite.setExpressionWidget(this);
+ }
+ this.data = new HashMap<String, Object>();
+
+ // Create a ResourceManager to dispose images when the widget is disposed.
+ this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), this.parent);
+
+ /*
+ * Create a validation timer for expression fields. Validation timer
+ * validates the field as the modeler is typing an expression
+ */
+ validationTimer = new Timer(VALIDATION_DELAY_TIME, new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if(variableTable == null || variableTable.isDisposed())
+ return;
+ variableTable.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ validateFields();
+ }
+ });
+ }
+ });
+ validationTimer.setRepeats(false);
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ // Update IExpression based on the newly selected expression
+ ExpressionWidgetInput i = AdaptionUtils.adaptToSingle(input, ExpressionWidgetInput.class);
+ this.input = i;
+ expr = i.expression;
+ variable = i.variable;
+ ExpressionType et = ExpressionTypes.getExpressionType(expr);
+ displayExpression(et.toString(), true);
+ }
+
+ /**
+ * Displays IExpression corresponding to expressionType.
+ * @param expressionType Expression type
+ * @param original Is the displayed expression for a newly selected expression (true) or did the
+ * expression change its type (false)
+ */
+ public void displayExpression(String expressionType, boolean original) {
+ if(expressionType == null || parent.isDisposed()) {
+ return;
+ }
+
+ // Get up-to-date data to data-map
+ if(this.expression != null) expression.updateData(data);
+
+ // Create the new expression
+ ExpressionType et = ExpressionType.valueOf(expressionType);
+ IExpression exp = null;
+ switch (et) {
+ case Auxiliary:
+ exp = new AuxiliaryExpression(input); break;
+ case Parameter:
+ exp = new ParameterExpression(input); break;
+ case Constant:
+ exp = new ConstantExpression(input); break;
+ case Lookup:
+ exp = new LookupExpression(); break;
+ case WithLookup:
+ exp = new WithLookupExpression(input); break;
+ case Stock:
+ exp = new StockExpression(input); break;
+ case Delay:
+ exp = new DelayExpression(input); break;
+ default:
+ exp = new EmptyExpression();
+ }
+
+ if (exp != null) {
+ // If expression was created, remove the old one
+ for(Control c : parent.getChildren()) {
+ c.dispose();
+ }
+
+ // If a completely new expression was selected, read data
+ if(original)
+ exp.readData(expr, data);
+
+ // Create the visual representation of the expression type
+ exp.createExpressionFields(parent, data, variableTable);
+
+ // Add listeners
+ if(modifyListener != null)
+ exp.addModifyListener(modifyListener);
+ if(focusListener != null)
+ exp.addFocusListener(focusListener);
+ if(verifyKeyListener != null)
+ exp.addVerifyKeyListener(verifyKeyListener);
+ this.expression = exp;
+ this.parent.layout();
+ validateFieldsTimed();
+
+ save();
+ }
+ }
+
+ /**
+ * Get current IExpression
+ * @return current IExpression
+ */
+ public IExpression getExpression() {
+ return expression;
+ }
+
+ /**
+ * Set the variable table that contains information about variables that are connected
+ * to this expression
+ * @param table
+ */
+ public void setVariableTable(Table table) {
+ this.variableTable = table;
+ }
+
+ /**
+ * Set timed field validation with default delay time
+ */
+ public void validateFieldsTimed() {
+ validateFieldsTimed(VALIDATION_DELAY_TIME);
+ }
+
+ /**
+ * Set timed field validation
+ * @param delay Delay time for validation
+ */
+ public void validateFieldsTimed(int delay) {
+ validationTimer.setDelay(delay);
+ if(!validationTimer.isRunning())
+ validationTimer.start();
+ else
+ validationTimer.restart();
+ }
+
+ /**
+ * Validates expression fields in current IExpression
+ */
+ public void validateFields() {
+ if(this.variableTable == null) return;
+
+ try {
+ // Find the variable for this experession
+ Resource variable = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ return graph.getPossibleObject(expr, l0.PartOf);
+ }
+ });
+ // Validate the variable
+ if(variable != null)
+ ExpressionUtils.validateExpressionFields(variable, expression, variableTable, resourceManager);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public void addModifyListener(ModifyListener listener) {
+ this.modifyListener = listener;
+ }
+
+ public void addVerifyKeyListener(VerifyKeyListener listener) {
+ this.verifyKeyListener = listener;
+ }
+
+ public void addFocusListener(FocusListener listener) {
+ this.focusListener = listener;
+ }
+
+ public void save() {
+ if(this.expression != null)
+ this.expression.save(expr, data);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets;\r
-\r
-import java.text.Collator;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.HashSet;\r
-import java.util.Locale;\r
-import java.util.concurrent.CopyOnWriteArrayList;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.jface.resource.JFaceResources;\r
-import org.eclipse.jface.resource.LocalResourceManager;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.FocusListener;\r
-import org.eclipse.swt.events.MouseListener;\r
-import org.eclipse.swt.graphics.Image;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.TabFolder;\r
-import org.eclipse.swt.widgets.TabItem;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.eclipse.swt.widgets.TableItem;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.AsyncReadGraph;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.request.PossibleModel;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.AsyncListener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.modelica.ModelicaWriter;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.validation.ValidationUtils;\r
-import org.simantics.sysdyn.utils.Function;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-\r
-public class ShortcutTabWidget implements Widget {\r
-\r
- TabFolder tabFolder;\r
- TabItem variables;\r
- TabItem functions;\r
- Table variableTable;\r
- Table functionTable;\r
- Composite composite;\r
- TableItem item2;\r
- \r
- CopyOnWriteArrayList<Runnable> dependencyListeners =\r
- new CopyOnWriteArrayList<Runnable>();\r
- \r
- private final LocalResourceManager resourceManager;\r
-\r
- public ShortcutTabWidget(Composite parent, WidgetSupport support, int style) {\r
- if(support!=null)\r
- support.register(this);\r
-\r
- composite = new Composite(parent, style);\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);\r
- \r
- tabFolder = new TabFolder (composite, SWT.NONE);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(tabFolder);\r
- GridLayoutFactory.fillDefaults().applyTo(tabFolder);\r
- variables = new TabItem(tabFolder, SWT.NULL);\r
- variables.setText("Variables");\r
- variableTable = new Table (tabFolder, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.NO_FOCUS | SWT.HIDE_SELECTION);\r
- \r
- variables.setControl(variableTable);\r
-\r
- functions = new TabItem(tabFolder, SWT.NULL);\r
- functions.setText("Functions"); \r
-\r
- functionTable = new Table (tabFolder, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.NO_FOCUS | SWT.HIDE_SELECTION);\r
- \r
- // Create a ResourceManager to dispose images when the widget is disposed.\r
- this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), functionTable);\r
- \r
- functions.setControl(functionTable);\r
- \r
- // Add the functions only after we know which variable is connected to this widget.\r
- }\r
-\r
- public Composite getWidget() {\r
- return composite;\r
- }\r
- \r
- private void addFunctions(Resource model) {\r
- TableItem item;\r
- \r
- ArrayList<Function> functionList = Function.getUserDefinedFunctions(model);\r
- functionList.addAll(Function.getSharedFunctions(model)); \r
- functionList.addAll(Function.getAllBuiltInFunctions()); \r
- \r
- Collections.sort(functionList);\r
- \r
- for(Function function : functionList){\r
- item = new TableItem(functionTable, SWT.NONE);\r
- item.setText(function.getName() + "()");\r
- String parameterList = Function.inputListToString(function.getInputList());\r
- item.setData(function.getName() + "(" + parameterList + ")");\r
- item.setImage(getImage(this.resourceManager, function));\r
- }\r
- \r
- }\r
- \r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- if(input instanceof IStructuredSelection) {\r
- final Resource variable = ISelectionUtils.filterSingleSelection(input, Resource.class);\r
- if(variable != null) {\r
- \r
- // Fill the function table\r
- try { \r
- Resource model = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return graph.syncRequest(new PossibleModel(variable));\r
- }\r
- });\r
- addFunctions(model);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- // Fill the variable table\r
- SimanticsUI.getSession().asyncRequest(new Read<HashSet<String>>() {\r
-\r
- @Override\r
- public HashSet<String> perform(ReadGraph graph)\r
- throws DatabaseException {\r
- return ValidationUtils.getDependencies(graph, variable);\r
- }\r
- }, new AsyncListener<HashSet<String>>() {\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph,\r
- HashSet<String> result) {\r
- \r
- final HashSet<String> dependencies = result;\r
- variableTable.getDisplay().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- if(variableTable.isDisposed()) return;\r
- \r
- TableItem[] items = variableTable.getItems();\r
- \r
- // Remove deleted dependencies and create the list of current dependencies (itemStrings)\r
- ArrayList<String> itemStrings = new ArrayList<String>();\r
- for(TableItem i : items) {\r
- String text = i.getText();\r
- if(dependencies.contains(text))\r
- itemStrings.add(text);\r
- else\r
- variableTable.remove(variableTable.indexOf(i));\r
- }\r
- \r
- // Add all new dependencies\r
- TableItem item;\r
- for(String d : dependencies) {\r
- if(!itemStrings.contains(d)) {\r
- item = new TableItem(variableTable, SWT.NONE);\r
- item.setText(d);\r
- item.setData(d);\r
- }\r
- }\r
- \r
- sort();\r
- \r
- String selfName = getName();\r
-\r
- // Time and self are not added if selfName (we have an error or a stock).\r
- if (selfName != null)\r
- {\r
- item = new TableItem(variableTable, SWT.NONE);\r
- item.setText(selfName);\r
- item.setData(selfName);\r
- \r
- item = new TableItem(variableTable, SWT.NONE);\r
- item.setText(ModelicaWriter.VAR_TIME);\r
- item.setData(ModelicaWriter.VAR_TIME);\r
- \r
- item = new TableItem(variableTable, SWT.NONE);\r
- item.setText(ModelicaWriter.VAR_START);\r
- item.setData(ModelicaWriter.VAR_START);\r
- \r
- item = new TableItem(variableTable, SWT.NONE);\r
- item.setText(ModelicaWriter.VAR_STOP);\r
- item.setData(ModelicaWriter.VAR_STOP);\r
- \r
- item = new TableItem(variableTable, SWT.NONE);\r
- item.setText(ModelicaWriter.VAR_STEP);\r
- item.setData(ModelicaWriter.VAR_STEP);\r
- }\r
- \r
- synchronized(dependencyListeners) {\r
- for(Runnable listener : dependencyListeners)\r
- listener.run();\r
- } \r
- }\r
- });\r
- }\r
- \r
- /**\r
- * Sort items to alphabetical order.\r
- */\r
- private void sort() {\r
- TableItem[] connectedVariables = variableTable.getItems();\r
- Collator collator = Collator.getInstance(Locale.getDefault());\r
- for (int i = 1; i < connectedVariables.length; i++) {\r
- String value1 = connectedVariables[i].getText(0);\r
- for (int j = 0; j < i; j++) {\r
- String value2 = connectedVariables[j].getText(0);\r
- if (collator.compare(value1, value2) < 0) {\r
- String value = connectedVariables[i].getText(0);\r
- connectedVariables[i].dispose();\r
- TableItem item2 = new TableItem(variableTable, SWT.NONE, j);\r
- item2.setText(value);\r
- item2.setData(value);\r
- connectedVariables = variableTable.getItems();\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * Get the name of the respective variable.\r
- */\r
- private String getName() {\r
- String selfName = null;\r
- try {\r
- selfName = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
- @Override\r
- public String perform(ReadGraph graph)\r
- throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Object selfName = graph.getPossibleRelatedValue(variable, l0.HasName);\r
- if (selfName instanceof String) {\r
- return (String)selfName;\r
- }\r
- return null;\r
- }\r
- });\r
- }\r
- catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return selfName;\r
- }\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph,\r
- Throwable throwable) {\r
- throwable.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return variableTable.isDisposed();\r
- }\r
- });\r
- }\r
- }\r
- }\r
-\r
-\r
- \r
- public void addFocusListener(FocusListener listener) {\r
- this.functionTable.addFocusListener(listener);\r
- this.variableTable.addFocusListener(listener);\r
- }\r
- \r
- public void addMouseListener(MouseListener listener) {\r
- this.functionTable.addMouseListener(listener);\r
- this.variableTable.addMouseListener(listener);\r
- }\r
- \r
- public void addDependencyListener(Runnable listener) {\r
- synchronized(dependencyListeners) {\r
- dependencyListeners.add(listener);\r
- }\r
- }\r
-\r
- public void removeDependencyListener(Runnable listener) {\r
- synchronized(dependencyListeners) {\r
- dependencyListeners.remove(listener);\r
- }\r
- }\r
- \r
- public Table getVariableTable() {\r
- return variableTable;\r
- }\r
-\r
- /**\r
- * Get the icon image for each type of Modelica function.\r
- * @param rm LocalResourceManager for which the image is created.\r
- * @param function Modelica function\r
- * @return Image to be shown e.g. in assistive text feed and ShortcutTab\r
- */\r
- public static Image getImage(LocalResourceManager rm, Function function) {\r
- switch (function.getType()) {\r
- case USER_DEFINED:\r
- return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/function.png")));\r
- case SHARED:\r
- return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/functionLink.png")));\r
- case VENSIM:\r
- return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/vensimFunction.png")));\r
- case SYSDYN:\r
- return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/sysdynFunction.png")));\r
- case MODELICA:\r
- return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/modelicaFunction.png")));\r
- case MODELICA_ARRAY:\r
- return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/modelicaArrayFunction.png")));\r
- default:\r
- return null;\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets;
+
+import java.text.Collator;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.resource.LocalResourceManager;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.TabFolder;
+import org.eclipse.swt.widgets.TabItem;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.request.PossibleModel;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.AsyncListener;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.modelica.ModelicaWriter;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.validation.ValidationUtils;
+import org.simantics.sysdyn.utils.Function;
+import org.simantics.utils.ui.ISelectionUtils;
+
+public class ShortcutTabWidget implements Widget {
+
+ TabFolder tabFolder;
+ TabItem variables;
+ TabItem functions;
+ Table variableTable;
+ Table functionTable;
+ Composite composite;
+ TableItem item2;
+
+ CopyOnWriteArrayList<Runnable> dependencyListeners =
+ new CopyOnWriteArrayList<Runnable>();
+
+ private final LocalResourceManager resourceManager;
+
+ public ShortcutTabWidget(Composite parent, WidgetSupport support, int style) {
+ if(support!=null)
+ support.register(this);
+
+ composite = new Composite(parent, style);
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(composite);
+
+ tabFolder = new TabFolder (composite, SWT.NONE);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(tabFolder);
+ GridLayoutFactory.fillDefaults().applyTo(tabFolder);
+ variables = new TabItem(tabFolder, SWT.NULL);
+ variables.setText("Variables");
+ variableTable = new Table (tabFolder, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.NO_FOCUS | SWT.HIDE_SELECTION);
+
+ variables.setControl(variableTable);
+
+ functions = new TabItem(tabFolder, SWT.NULL);
+ functions.setText("Functions");
+
+ functionTable = new Table (tabFolder, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.NO_FOCUS | SWT.HIDE_SELECTION);
+
+ // Create a ResourceManager to dispose images when the widget is disposed.
+ this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), functionTable);
+
+ functions.setControl(functionTable);
+
+ // Add the functions only after we know which variable is connected to this widget.
+ }
+
+ public Composite getWidget() {
+ return composite;
+ }
+
+ private void addFunctions(Resource model) {
+ TableItem item;
+
+ ArrayList<Function> functionList = Function.getUserDefinedFunctions(model);
+ functionList.addAll(Function.getSharedFunctions(model));
+ functionList.addAll(Function.getAllBuiltInFunctions());
+
+ Collections.sort(functionList);
+
+ for(Function function : functionList){
+ item = new TableItem(functionTable, SWT.NONE);
+ item.setText(function.getName() + "()");
+ String parameterList = Function.inputListToString(function.getInputList());
+ item.setData(function.getName() + "(" + parameterList + ")");
+ item.setImage(getImage(this.resourceManager, function));
+ }
+
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ if(input instanceof IStructuredSelection) {
+ final Resource variable = ISelectionUtils.filterSingleSelection(input, Resource.class);
+ if(variable != null) {
+
+ // Fill the function table
+ try {
+ Resource model = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return graph.syncRequest(new PossibleModel(variable));
+ }
+ });
+ addFunctions(model);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ // Fill the variable table
+ Simantics.getSession().asyncRequest(new Read<HashSet<String>>() {
+
+ @Override
+ public HashSet<String> perform(ReadGraph graph)
+ throws DatabaseException {
+ return ValidationUtils.getDependencies(graph, variable);
+ }
+ }, new AsyncListener<HashSet<String>>() {
+
+ @Override
+ public void execute(AsyncReadGraph graph,
+ HashSet<String> result) {
+
+ final HashSet<String> dependencies = result;
+ variableTable.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if(variableTable.isDisposed()) return;
+
+ TableItem[] items = variableTable.getItems();
+
+ // Remove deleted dependencies and create the list of current dependencies (itemStrings)
+ ArrayList<String> itemStrings = new ArrayList<String>();
+ for(TableItem i : items) {
+ String text = i.getText();
+ if(dependencies.contains(text))
+ itemStrings.add(text);
+ else
+ variableTable.remove(variableTable.indexOf(i));
+ }
+
+ // Add all new dependencies
+ TableItem item;
+ for(String d : dependencies) {
+ if(!itemStrings.contains(d)) {
+ item = new TableItem(variableTable, SWT.NONE);
+ item.setText(d);
+ item.setData(d);
+ }
+ }
+
+ sort();
+
+ String selfName = getName();
+
+ // Time and self are not added if selfName (we have an error or a stock).
+ if (selfName != null)
+ {
+ item = new TableItem(variableTable, SWT.NONE);
+ item.setText(selfName);
+ item.setData(selfName);
+
+ item = new TableItem(variableTable, SWT.NONE);
+ item.setText(ModelicaWriter.VAR_TIME);
+ item.setData(ModelicaWriter.VAR_TIME);
+
+ item = new TableItem(variableTable, SWT.NONE);
+ item.setText(ModelicaWriter.VAR_START);
+ item.setData(ModelicaWriter.VAR_START);
+
+ item = new TableItem(variableTable, SWT.NONE);
+ item.setText(ModelicaWriter.VAR_STOP);
+ item.setData(ModelicaWriter.VAR_STOP);
+
+ item = new TableItem(variableTable, SWT.NONE);
+ item.setText(ModelicaWriter.VAR_STEP);
+ item.setData(ModelicaWriter.VAR_STEP);
+ }
+
+ synchronized(dependencyListeners) {
+ for(Runnable listener : dependencyListeners)
+ listener.run();
+ }
+ }
+ });
+ }
+
+ /**
+ * Sort items to alphabetical order.
+ */
+ private void sort() {
+ TableItem[] connectedVariables = variableTable.getItems();
+ Collator collator = Collator.getInstance(Locale.getDefault());
+ for (int i = 1; i < connectedVariables.length; i++) {
+ String value1 = connectedVariables[i].getText(0);
+ for (int j = 0; j < i; j++) {
+ String value2 = connectedVariables[j].getText(0);
+ if (collator.compare(value1, value2) < 0) {
+ String value = connectedVariables[i].getText(0);
+ connectedVariables[i].dispose();
+ TableItem item2 = new TableItem(variableTable, SWT.NONE, j);
+ item2.setText(value);
+ item2.setData(value);
+ connectedVariables = variableTable.getItems();
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Get the name of the respective variable.
+ */
+ private String getName() {
+ String selfName = null;
+ try {
+ selfName = Simantics.getSession().syncRequest(new Read<String>() {
+ @Override
+ public String perform(ReadGraph graph)
+ throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ Object selfName = graph.getPossibleRelatedValue(variable, l0.HasName);
+ if (selfName instanceof String) {
+ return (String)selfName;
+ }
+ return null;
+ }
+ });
+ }
+ catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return selfName;
+ }
+
+ @Override
+ public void exception(AsyncReadGraph graph,
+ Throwable throwable) {
+ throwable.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return variableTable.isDisposed();
+ }
+ });
+ }
+ }
+ }
+
+
+
+ public void addFocusListener(FocusListener listener) {
+ this.functionTable.addFocusListener(listener);
+ this.variableTable.addFocusListener(listener);
+ }
+
+ public void addMouseListener(MouseListener listener) {
+ this.functionTable.addMouseListener(listener);
+ this.variableTable.addMouseListener(listener);
+ }
+
+ public void addDependencyListener(Runnable listener) {
+ synchronized(dependencyListeners) {
+ dependencyListeners.add(listener);
+ }
+ }
+
+ public void removeDependencyListener(Runnable listener) {
+ synchronized(dependencyListeners) {
+ dependencyListeners.remove(listener);
+ }
+ }
+
+ public Table getVariableTable() {
+ return variableTable;
+ }
+
+ /**
+ * Get the icon image for each type of Modelica function.
+ * @param rm LocalResourceManager for which the image is created.
+ * @param function Modelica function
+ * @return Image to be shown e.g. in assistive text feed and ShortcutTab
+ */
+ public static Image getImage(LocalResourceManager rm, Function function) {
+ switch (function.getType()) {
+ case USER_DEFINED:
+ return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/function.png")));
+ case SHARED:
+ return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/functionLink.png")));
+ case VENSIM:
+ return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/vensimFunction.png")));
+ case SYSDYN:
+ return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/sysdynFunction.png")));
+ case MODELICA:
+ return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/modelicaFunction.png")));
+ case MODELICA_ARRAY:
+ return rm.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/modelicaArrayFunction.png")));
+ default:
+ return null;
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.arrays;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;\r
-import org.simantics.browsing.ui.common.modifiers.Enumeration;\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class RedeclarationNode extends AbstractNode<Resource> implements IModifiableNode {\r
-\r
- private Resource module;\r
- \r
- public RedeclarationNode(ReadGraph graph, final Resource module, Resource enumeration) {\r
- super(enumeration);\r
- this.module = module;\r
- }\r
- \r
- /**\r
- * \r
- * @param graph\r
- * @return\r
- */\r
- public Resource getReplacingEnumeration(ReadGraph graph) {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource result = null;\r
- try {\r
- Resource redeclaration = getRedeclaration(graph);\r
- if(redeclaration != null) {\r
- result = graph.getSingleObject(redeclaration, sr.Redeclaration_replacingEnumeration);\r
- }\r
- } catch(DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- return result;\r
- }\r
- \r
-\r
- public Resource getModule() {\r
- return module;\r
- }\r
-\r
- public void setModule(Resource module) {\r
- this.module = module;\r
- }\r
-\r
- public Resource getRedeclaration(ReadGraph graph) {\r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for(Resource redeclaration : graph.syncRequest(new ObjectsWithType(module, sr.Module_redeclaration, sr.Redeclaration))) {\r
- Resource replacedEnumeration = graph.getPossibleObject(redeclaration, sr.Redeclaration_replacedEnumeration);\r
- if(replacedEnumeration != null && replacedEnumeration.equals(getReplacedEnumeration())) {\r
- return redeclaration;\r
- }\r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return null;\r
- }\r
-\r
- public void setRedeclaration(WriteGraph graph, Resource redeclaration) {\r
- try {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource oldRedeclaration = getRedeclaration(graph);\r
- if(oldRedeclaration != null || redeclaration == null) {\r
- graph.deny(module, sr.Module_redeclaration, oldRedeclaration);\r
- }\r
- \r
- if(redeclaration != null)\r
- graph.claim(module, sr.Module_redeclaration, redeclaration);\r
- \r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- public Resource getReplacedEnumeration() {\r
- return this.data;\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- \r
- if(!ColumnKeys.REPLACED_WITH.equals(columnId))\r
- return null;\r
- \r
- ComboBoxModifier<Resource> cbm = null;\r
- \r
- try {\r
- cbm = SimanticsUI.getSession().syncRequest(new Read<ComboBoxModifier<Resource>>() {\r
- \r
- @Override\r
- public ComboBoxModifier<Resource> perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- ArrayList<EnumeratedValue<Resource>> values = new ArrayList<EnumeratedValue<Resource>>();\r
- \r
- \r
- Resource configuration = graph.getSingleObject(module, l0.PartOf);\r
- \r
- for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
- String name = NameUtils.getSafeName(graph, enumeration);\r
- values.add(new EnumeratedValue<Resource>(name, enumeration)); \r
- }\r
-\r
- if(values.size() == 0)\r
- return null;\r
- \r
- values.add(0, new EnumeratedValue<Resource>("", null));\r
- Enumeration<Resource> enumeration = new Enumeration<Resource>(values); \r
- \r
- ComboBoxModifier<Resource> cbm = new ComboBoxModifier<Resource>(graph.getSession(), enumeration, getReplacingEnumeration(graph)) {\r
- \r
- @Override\r
- protected void modifyWithObject(WriteGraph graph, Resource oldEnumObject,\r
- Resource enumObject) throws DatabaseException {\r
- \r
- if(enumObject == null) {\r
- setRedeclaration(graph, null);\r
- } else if(!enumObject.equals(oldEnumObject)) {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource redeclaration = GraphUtils.create2(graph, \r
- sr.Redeclaration, \r
- sr.Redeclaration_replacedEnumeration, getReplacedEnumeration(),\r
- sr.Redeclaration_replacingEnumeration, enumObject);\r
- setRedeclaration(graph, redeclaration);\r
- }\r
- \r
- }\r
- };\r
- \r
- return cbm;\r
- \r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
-\r
- return cbm;\r
- }\r
- \r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.properties.widgets.arrays;
+
+import java.util.ArrayList;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.modifiers.EnumeratedValue;
+import org.simantics.browsing.ui.common.modifiers.Enumeration;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;
+
+public class RedeclarationNode extends AbstractNode<Resource> implements IModifiableNode {
+
+ private Resource module;
+
+ public RedeclarationNode(ReadGraph graph, final Resource module, Resource enumeration) {
+ super(enumeration);
+ this.module = module;
+ }
+
+ /**
+ *
+ * @param graph
+ * @return
+ */
+ public Resource getReplacingEnumeration(ReadGraph graph) {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource result = null;
+ try {
+ Resource redeclaration = getRedeclaration(graph);
+ if(redeclaration != null) {
+ result = graph.getSingleObject(redeclaration, sr.Redeclaration_replacingEnumeration);
+ }
+ } catch(DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ return result;
+ }
+
+
+ public Resource getModule() {
+ return module;
+ }
+
+ public void setModule(Resource module) {
+ this.module = module;
+ }
+
+ public Resource getRedeclaration(ReadGraph graph) {
+ try {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for(Resource redeclaration : graph.syncRequest(new ObjectsWithType(module, sr.Module_redeclaration, sr.Redeclaration))) {
+ Resource replacedEnumeration = graph.getPossibleObject(redeclaration, sr.Redeclaration_replacedEnumeration);
+ if(replacedEnumeration != null && replacedEnumeration.equals(getReplacedEnumeration())) {
+ return redeclaration;
+ }
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ public void setRedeclaration(WriteGraph graph, Resource redeclaration) {
+ try {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource oldRedeclaration = getRedeclaration(graph);
+ if(oldRedeclaration != null || redeclaration == null) {
+ graph.deny(module, sr.Module_redeclaration, oldRedeclaration);
+ }
+
+ if(redeclaration != null)
+ graph.claim(module, sr.Module_redeclaration, redeclaration);
+
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public Resource getReplacedEnumeration() {
+ return this.data;
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+
+ if(!ColumnKeys.REPLACED_WITH.equals(columnId))
+ return null;
+
+ ComboBoxModifier<Resource> cbm = null;
+
+ try {
+ cbm = Simantics.getSession().syncRequest(new Read<ComboBoxModifier<Resource>>() {
+
+ @Override
+ public ComboBoxModifier<Resource> perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ ArrayList<EnumeratedValue<Resource>> values = new ArrayList<EnumeratedValue<Resource>>();
+
+
+ Resource configuration = graph.getSingleObject(module, l0.PartOf);
+
+ for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {
+ String name = NameUtils.getSafeName(graph, enumeration);
+ values.add(new EnumeratedValue<Resource>(name, enumeration));
+ }
+
+ if(values.size() == 0)
+ return null;
+
+ values.add(0, new EnumeratedValue<Resource>("", null));
+ Enumeration<Resource> enumeration = new Enumeration<Resource>(values);
+
+ ComboBoxModifier<Resource> cbm = new ComboBoxModifier<Resource>(graph.getSession(), enumeration, getReplacingEnumeration(graph)) {
+
+ @Override
+ protected void modifyWithObject(WriteGraph graph, Resource oldEnumObject,
+ Resource enumObject) throws DatabaseException {
+
+ if(enumObject == null) {
+ setRedeclaration(graph, null);
+ } else if(!enumObject.equals(oldEnumObject)) {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource redeclaration = GraphUtils.create2(graph,
+ sr.Redeclaration,
+ sr.Redeclaration_replacedEnumeration, getReplacedEnumeration(),
+ sr.Redeclaration_replacingEnumeration, enumObject);
+ setRedeclaration(graph, redeclaration);
+ }
+
+ }
+ };
+
+ return cbm;
+
+ }
+ });
+ } catch (DatabaseException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return cbm;
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class AuxiliaryExpression extends BasicExpression {\r
-\r
- public AuxiliaryExpression(ExpressionWidgetInput input) {\r
- super(input);\r
- try {\r
- this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return SysdynResource.getInstance(graph).NormalExpression;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- @Override\r
- public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
- // Create the single field\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
- String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
-\r
- Label l = new Label(parent, SWT.NONE);\r
- l.setText("=");\r
-\r
- expression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
- expression.setExpression(equation);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets.expressions;
+
+import java.util.Map;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.SysdynResource;
+
+public class AuxiliaryExpression extends BasicExpression {
+
+ public AuxiliaryExpression(ExpressionWidgetInput input) {
+ super(input);
+ try {
+ this.expressionType = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return SysdynResource.getInstance(graph).NormalExpression;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {
+ // Create the single field
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);
+ String equation = data.get("equation") != null ? (String)data.get("equation") : "";
+
+ Label l = new Label(parent, SWT.NONE);
+ l.setText("=");
+
+ expression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);
+ expression.setExpression(equation);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
-\r
-import java.util.Arrays;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.text.BadLocationException;\r
-import org.eclipse.jface.text.IDocument;\r
-import org.eclipse.jface.text.IUndoManager;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.VerifyKeyListener;\r
-import org.eclipse.swt.events.FocusListener;\r
-import org.eclipse.swt.events.KeyListener;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.CommentMetadata;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.db.service.VirtualGraphSupport;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Basic expression that is used with parameter, auxiliary and constant\r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class BasicExpression implements IExpression {\r
-\r
- protected ExpressionField expression;\r
- protected Resource expressionType;\r
- protected ExpressionWidgetInput input;\r
- \r
- public BasicExpression(ExpressionWidgetInput input) {\r
- this.input = input;\r
- }\r
- \r
- @Override\r
- public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
- // Create the single field\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
- String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
-\r
- Label l = new Label(parent, SWT.NONE);\r
- l.setText("=");\r
-\r
- expression = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
- expression.setExpression(equation);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
-\r
- }\r
-\r
- @Override\r
- public void focus() {\r
- this.expression.focus();\r
-\r
- }\r
-\r
- @Override\r
- public List<ExpressionField> getExpressionFields() {\r
- return Arrays.asList(this.expression);\r
- }\r
-\r
- @Override\r
- public void readData(final Resource expression, Map<String, Object> data) {\r
- String equation = null;\r
- if (expression != null && data.get("equation") == null) {\r
- try {\r
- equation = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if (expression != null) {\r
- String equation = graph.getPossibleRelatedValue(expression, sr.Expression_equation);\r
- if(equation != null)\r
- return equation;\r
- }\r
- \r
- return "";\r
- \r
- }\r
-\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- data.put("equation", equation);\r
- }\r
- }\r
-\r
- @Override\r
- public void replaceSelection(String var) {\r
- if(expression != null) {\r
- IDocument doc = expression.getDocument();\r
- try {\r
- Point selection = expression.getSelection();\r
- doc.replace(selection.x, selection.y, var);\r
- expression.setSelection(selection.x + var.length());\r
- } catch (BadLocationException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- }\r
-\r
- @Override\r
- public void save(final Resource expression, Map<String, Object> data) {\r
- final String currentText = this.expression.getExpression();\r
- final String oldEquation = (String)data.get("equation");\r
-\r
- if(oldEquation == null || \r
- (currentText != null && expressionType != null)) {\r
- data.put("equation", currentText);\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph g)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
-\r
- // If nothing has changed, do nothing\r
- if (oldEquation != null \r
- && expression != null \r
- && g.isInstanceOf(expression, expressionType) \r
- && currentText.equals(oldEquation)) {\r
- return;\r
- }\r
- \r
- // Force change to parameter, if the equation is a parameter\r
- if(ExpressionUtils.isParameter(currentText)) {\r
- if(!expressionType.equals(sr.ConstantExpression))\r
- expressionType = sr.ParameterExpression;\r
- } else {\r
- expressionType = sr.NormalExpression;\r
- }\r
- \r
- g.markUndoPoint();\r
- CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
- g.addMetadata(cm.add("Set equation"));\r
-\r
- // If the current expression type is different than the target expression type, create a new expression\r
- if(!g.isInstanceOf(expression, expressionType)) {\r
-\r
- final Resource newExpression = GraphUtils.create2(g, expressionType, \r
- sr.Expression_equation, currentText);\r
- String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);\r
- if(arrayRange != null)\r
- g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);\r
- \r
- final Resource variable = g.getPossibleObject(expression, l0.PartOf);\r
- if(variable == null)\r
- return;\r
- Resource ownerList = g.getPossibleObject(variable, sr.Variable_expressionList);\r
- if(ownerList == null)\r
- return;\r
- \r
- ListUtils.replace(g, ownerList, expression, newExpression);\r
- \r
- g.deny(expression, l0.PartOf);\r
- \r
- g.claim(newExpression, l0.PartOf, variable);\r
- \r
- \r
- VirtualGraphSupport support = g.getService(VirtualGraphSupport.class);\r
- g.syncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(variable != null) {\r
- if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
- graph.deny(variable, sr.IndependentVariable_activeExpression);\r
- graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);\r
- }\r
- }\r
- }\r
- );\r
- } else {\r
- // Claim value for the expression\r
- g.claimLiteral(expression, sr.Expression_equation, currentText);\r
- }\r
- }\r
-\r
- });\r
- }\r
- }\r
-\r
- @Override\r
- public void updateData(Map<String, Object> data) {\r
- if(this.expression != null && this.expression.getExpression() != null)\r
- data.put("equation", this.expression.getExpression());\r
- }\r
-\r
- @Override\r
- public void addKeyListener(KeyListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
-\r
- }\r
-\r
- @Override\r
- public void addModifyListener(ModifyListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
-\r
- }\r
-\r
- @Override\r
- public void addFocusListener(FocusListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
- }\r
-\r
- @Override\r
- public void addVerifyKeyListener(VerifyKeyListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
- }\r
-\r
- @Override\r
- public IUndoManager getUndoManager() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.properties.widgets.expressions;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IUndoManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.VerifyKeyListener;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.simantics.Simantics;
+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.CommentMetadata;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.db.service.VirtualGraphSupport;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;
+
+/**
+ * Basic expression that is used with parameter, auxiliary and constant
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class BasicExpression implements IExpression {
+
+ protected ExpressionField expression;
+ protected Resource expressionType;
+ protected ExpressionWidgetInput input;
+
+ public BasicExpression(ExpressionWidgetInput input) {
+ this.input = input;
+ }
+
+ @Override
+ public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {
+ // Create the single field
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);
+ String equation = data.get("equation") != null ? (String)data.get("equation") : "";
+
+ Label l = new Label(parent, SWT.NONE);
+ l.setText("=");
+
+ expression = new ExpressionField(parent, SWT.BORDER, null, false, input);
+ expression.setExpression(equation);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);
+
+ }
+
+ @Override
+ public void focus() {
+ this.expression.focus();
+
+ }
+
+ @Override
+ public List<ExpressionField> getExpressionFields() {
+ return Arrays.asList(this.expression);
+ }
+
+ @Override
+ public void readData(final Resource expression, Map<String, Object> data) {
+ String equation = null;
+ if (expression != null && data.get("equation") == null) {
+ try {
+ equation = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if (expression != null) {
+ String equation = graph.getPossibleRelatedValue(expression, sr.Expression_equation);
+ if(equation != null)
+ return equation;
+ }
+
+ return "";
+
+ }
+
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ data.put("equation", equation);
+ }
+ }
+
+ @Override
+ public void replaceSelection(String var) {
+ if(expression != null) {
+ IDocument doc = expression.getDocument();
+ try {
+ Point selection = expression.getSelection();
+ doc.replace(selection.x, selection.y, var);
+ expression.setSelection(selection.x + var.length());
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void save(final Resource expression, Map<String, Object> data) {
+ final String currentText = this.expression.getExpression();
+ final String oldEquation = (String)data.get("equation");
+
+ if(oldEquation == null ||
+ (currentText != null && expressionType != null)) {
+ data.put("equation", currentText);
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph g)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+
+ // If nothing has changed, do nothing
+ if (oldEquation != null
+ && expression != null
+ && g.isInstanceOf(expression, expressionType)
+ && currentText.equals(oldEquation)) {
+ return;
+ }
+
+ // Force change to parameter, if the equation is a parameter
+ if(ExpressionUtils.isParameter(currentText)) {
+ if(!expressionType.equals(sr.ConstantExpression))
+ expressionType = sr.ParameterExpression;
+ } else {
+ expressionType = sr.NormalExpression;
+ }
+
+ g.markUndoPoint();
+ CommentMetadata cm = g.getMetadata(CommentMetadata.class);
+ g.addMetadata(cm.add("Set equation"));
+
+ // If the current expression type is different than the target expression type, create a new expression
+ if(!g.isInstanceOf(expression, expressionType)) {
+
+ final Resource newExpression = GraphUtils.create2(g, expressionType,
+ sr.Expression_equation, currentText);
+ String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);
+ if(arrayRange != null)
+ g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);
+
+ final Resource variable = g.getPossibleObject(expression, l0.PartOf);
+ if(variable == null)
+ return;
+ Resource ownerList = g.getPossibleObject(variable, sr.Variable_expressionList);
+ if(ownerList == null)
+ return;
+
+ ListUtils.replace(g, ownerList, expression, newExpression);
+
+ g.deny(expression, l0.PartOf);
+
+ g.claim(newExpression, l0.PartOf, variable);
+
+
+ VirtualGraphSupport support = g.getService(VirtualGraphSupport.class);
+ g.syncRequest(new WriteRequest(support.getWorkspacePersistent("expressions")) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(variable != null) {
+ if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))
+ graph.deny(variable, sr.IndependentVariable_activeExpression);
+ graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);
+ }
+ }
+ }
+ );
+ } else {
+ // Claim value for the expression
+ g.claimLiteral(expression, sr.Expression_equation, currentText);
+ }
+ }
+
+ });
+ }
+ }
+
+ @Override
+ public void updateData(Map<String, Object> data) {
+ if(this.expression != null && this.expression.getExpression() != null)
+ data.put("equation", this.expression.getExpression());
+ }
+
+ @Override
+ public void addKeyListener(KeyListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addKeyListener(listener);
+
+ }
+
+ @Override
+ public void addModifyListener(ModifyListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addModifyListener(listener);
+
+ }
+
+ @Override
+ public void addFocusListener(FocusListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addFocusListener(listener);
+ }
+
+ @Override
+ public void addVerifyKeyListener(VerifyKeyListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);
+ }
+
+ @Override
+ public IUndoManager getUndoManager() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.Comparator;\r
-\r
-import org.eclipse.jface.resource.ImageDescriptor;\r
-import org.eclipse.jface.resource.JFaceResources;\r
-import org.eclipse.jface.resource.LocalResourceManager;\r
-import org.eclipse.jface.text.ITextViewer;\r
-import org.eclipse.jface.text.contentassist.CompletionProposal;\r
-import org.eclipse.jface.text.contentassist.ICompletionProposal;\r
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;\r
-import org.eclipse.jface.text.contentassist.IContextInformation;\r
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;\r
-import org.eclipse.swt.graphics.Image;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.eclipse.swt.widgets.TableItem;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget;\r
-import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
-import org.simantics.sysdyn.utils.Function;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-\r
-/**\r
- * IContentAssistProcessor to determine which options (the functions and \r
- * variables available) are shown for ContentAssistant; this assist of\r
- * text field allows long variable names to be selected from a popup menu.\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class CompletionProcessor implements IContentAssistProcessor {\r
- \r
- private final Table allowedVariables;\r
- private ArrayList<Function> functions;\r
- private ArrayList<String> variables = null;\r
- private ArrayList<String> timeAndSelfVariables = null;\r
- private final ExpressionWidgetInput input;\r
- \r
- private LocalResourceManager resourceManager;\r
- \r
- private static final char[] ALLOWED_CHARACTERS = {\r
- 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','å','ä','ö',\r
- 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Å','Ä','Ö',\r
- '1','2','3','4','5','6','7','8','9','0','.','(',')'};\r
- \r
- private static final String ALLOWED_CONNECTED_CHARACTERS_REG_EXP = "[\\Q({[:;,<=>+-*/^\\E]";\r
- \r
- private static final ArrayList<String> ALLOW_ALL_COMPLETIONS_LIST = new ArrayList<String>();\r
- static {\r
- ALLOW_ALL_COMPLETIONS_LIST.add("");\r
- }\r
- \r
- public CompletionProcessor(Table allowedVariables, boolean allowFunctions, ExpressionWidgetInput input) {\r
- this.allowedVariables = allowedVariables;\r
- this.input = input;\r
- this.functions = new ArrayList<Function>();\r
- \r
- if (allowFunctions) {\r
- if (input != null && CompletionProcessor.this.input.variable != null) {\r
- // Get the respective model\r
- Resource model = null;\r
- try {\r
- model = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return Variables.getModel(graph, CompletionProcessor.this.input.variable);\r
- }\r
- });\r
- \r
- //User defined functions\r
- functions.addAll(Function.getUserDefinedFunctions(model));\r
- // Shared functions\r
- functions.addAll(Function.getSharedFunctions(model));\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- // Collect built in functions and sort all functions.\r
- functions.addAll(Function.getAllBuiltInFunctions());\r
- Collections.sort(functions);\r
- }\r
- }\r
- \r
- /**\r
- * Collect and sort all variables.\r
- */\r
- private void findVariables() {\r
- if (variables == null) {\r
- variables = new ArrayList<String>();\r
- timeAndSelfVariables = new ArrayList<String>();\r
- if(allowedVariables != null && !allowedVariables.isDisposed()) {\r
- TableItem[] connectedVariables = allowedVariables.getItems();\r
- for(TableItem ti : connectedVariables) {\r
- // The status of the variable is determined using the color of its table item :(\r
- if (ExpressionUtils.variableTimeAndSelfColor(resourceManager).equals(ti.getForeground())) {\r
- this.timeAndSelfVariables.add(ti.getText());\r
- } else {\r
- this.variables.add(ti.getText());\r
- }\r
- \r
- }\r
- }\r
- Collections.sort(variables);\r
- Collections.sort(timeAndSelfVariables);\r
- }\r
- }\r
- \r
- /**\r
- * Create CompletionProposals of the variables and add them to array. Do not allow duplicates.\r
- * @param array result array of CompletionProposals\r
- * @param token current token\r
- * @param offset an offset within the document for which completions should be computed\r
- */\r
- private void addVariables(ArrayList<ICompletionProposal> array, String token, int offset) {\r
- Image imageVariable = resourceManager.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/variable.png")));\r
- Image imageVariableGray = resourceManager.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/variableGray.png")));\r
- \r
- for (String variable : variables) {\r
- if ((token.length() == 0 || variable.toUpperCase().startsWith(token.toUpperCase()))\r
- && !listContainsVariable(array, variable)) {\r
- array.add(new CompletionProposal(variable, \r
- offset - token.length(),\r
- token.length(), \r
- variable.length(), \r
- imageVariable, \r
- variable, \r
- null, \r
- null));\r
- } \r
- }\r
- for (String variable : timeAndSelfVariables) {\r
- if ((token.length() == 0 || variable.toUpperCase().startsWith(token.toUpperCase()))\r
- && !listContainsVariable(array, variable)) {\r
- array.add(new CompletionProposal(variable, \r
- offset - token.length(),\r
- token.length(), \r
- variable.length(), \r
- imageVariableGray, \r
- variable, \r
- null, \r
- null));\r
- } \r
- }\r
- }\r
- \r
- private boolean listContainsVariable(ArrayList<ICompletionProposal> array,\r
- String variable) {\r
- for (ICompletionProposal proposal : array) {\r
- if (proposal.getDisplayString().equals(variable))\r
- return true;\r
- }\r
- return false;\r
- }\r
-\r
- /**\r
- * Create CompletionProposals of the functions and add them to array.\r
- * @param array result array of CompletionProposals\r
- * @param token current token\r
- * @param offset an offset within the document for which completions should be computed\r
- */\r
- private void addFunctions(ArrayList<ICompletionProposal> array, String token, int offset) {\r
- // Parameters don't have functions\r
- if (functions == null)\r
- return;\r
- \r
- // Create CompletionProposals out of Functions\r
- for (Function function : functions) {\r
- if (token.length() == 0 || function.getName().toUpperCase().startsWith(token.toUpperCase())) {\r
- Image image = ShortcutTabWidget.getImage(resourceManager, function);\r
- String parameterList = Function.inputListToString(function.getInputList());\r
- array.add(new CompletionProposal(\r
- function.getName() + "(" + parameterList + ")", \r
- offset - token.length(),\r
- token.length(), \r
- function.getName().length() + 1,\r
- image, \r
- function.getName() + "(" + parameterList + ")", \r
- null, \r
- function.getDescriptionHTML()));\r
- } \r
- }\r
- }\r
- \r
- /**\r
- * Collect all matching proposals. Duplicates are removed; the one with the longest token stays.\r
- * @param possibleLabelBeginnings sets of whitespace delimited tokens (as Strings)\r
- * @param offset an offset within the document for which completions should be computed\r
- * @return Array of matching proposals\r
- */\r
- private ICompletionProposal[] collectProposals(ArrayList<String> possibleLabelBeginnings, int offset) {\r
- ArrayList<ICompletionProposal> resultArray = new ArrayList<ICompletionProposal>();\r
- \r
- // Find variables and functions and create CompletionProposals out of them.\r
- findVariables();\r
- \r
- // Sort the list based on the length of the tokens (descending) to get "" to end.\r
- Collections.sort(possibleLabelBeginnings, new Comparator<String>(){\r
- @Override\r
- public int compare(String o1, String o2) {\r
- if (o1.length() > o2.length()) {\r
- return -1;\r
- } else if (o1.length() < o2.length()) {\r
- return 1;\r
- }\r
- return 0;\r
- }\r
- });\r
- \r
- for (String possibleLabelBeginning : possibleLabelBeginnings) {\r
- addVariables(resultArray, possibleLabelBeginning, offset);\r
- }\r
- \r
- // No support for whitespace in function names; get shortest beginning\r
- addFunctions(resultArray, possibleLabelBeginnings.get(possibleLabelBeginnings.size() - 1), offset);\r
-\r
- ICompletionProposal[] result = new ICompletionProposal[resultArray.size()];\r
- for (int i = 0; i < result.length; ++i) {\r
- result[i] = resultArray.get(i);\r
- }\r
- return result;\r
- }\r
- \r
- @Override\r
- public ICompletionProposal[] computeCompletionProposals(\r
- ITextViewer viewer, int offset) {\r
- String equation = viewer.getDocument().get();\r
- Control control = viewer.getTextWidget();\r
- this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), control);\r
- \r
- if (equation.length() == 0 || offset == 0) {\r
- return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);\r
- }\r
- \r
- equation = equation.substring(0, offset);\r
- \r
- // Split the equation on '+', '-', etc. characters\r
- String stringsBetweenConnectedCharacters[] = equation.split(ALLOWED_CONNECTED_CHARACTERS_REG_EXP);\r
- if (stringsBetweenConnectedCharacters.length == 0) {\r
- return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);\r
- }\r
- String stringAfterLastConnectedCharacter = stringsBetweenConnectedCharacters[stringsBetweenConnectedCharacters.length - 1];\r
- String stringAfterWhitespaceAfterLastConnectedCharacter = removeLeadingWhitespace(stringAfterLastConnectedCharacter);\r
- \r
- // Split into tokens on whitespace characters, include also the trailing empty strings\r
- String[] tokens = stringAfterWhitespaceAfterLastConnectedCharacter.split("[\\s]", -42);\r
- \r
- // Only whitespace after the last connection character\r
- if (allTokensAreEmpty(tokens))\r
- return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);\r
- \r
- return collectProposals(getPossibleLabelBeginnings(tokens), offset);\r
- }\r
-\r
- /**\r
- * Collect all possible strings (with each whitespace replaced by a space character)\r
- * which may be a beginning of a variable. \r
- * Create the beginnings by adding whitespace between. E.g.:\r
- * {"multi", "part", "variab"}\r
- * -> { "multi part variab",\r
- * "part variab",\r
- * "variab" }\r
- * @param tokens list of tokens\r
- * @return all possible label beginnings\r
- */\r
- private ArrayList<String> getPossibleLabelBeginnings(String[] tokens) {\r
- ArrayList<String> possibleLabelBeginnings = new ArrayList<String>();\r
- for (int i = 0; i < tokens.length; ++i) {\r
- String token = new String();\r
- for (int j = i; j < tokens.length; ++j) {\r
- token += " " + tokens[j];\r
- }\r
- // Remove the excess space character from the beginning\r
- token = token.substring(1);\r
- \r
- possibleLabelBeginnings.add(token);\r
- }\r
- return possibleLabelBeginnings;\r
- }\r
-\r
- /**\r
- * Remove leading whitespace\r
- * @param input\r
- * @return\r
- */\r
- private String removeLeadingWhitespace(String input) {\r
- for (int i = 0; i < input.length(); ++i) {\r
- if (!Character.isWhitespace(input.charAt(i))) {\r
- return input.substring(i);\r
- }\r
- }\r
- return "";\r
- }\r
-\r
- private boolean allTokensAreEmpty(String[] tokens) {\r
- for (String token : tokens)\r
- if (!token.equals(""))\r
- return false;\r
- return true;\r
- }\r
-\r
- @Override\r
- public IContextInformation[] computeContextInformation(\r
- ITextViewer viewer, int offset) {\r
- return null;\r
- }\r
-\r
- @Override\r
- public char[] getCompletionProposalAutoActivationCharacters() {\r
- return ALLOWED_CHARACTERS;\r
- }\r
-\r
- @Override\r
- public char[] getContextInformationAutoActivationCharacters() {\r
- return null;\r
- }\r
-\r
- @Override\r
- public String getErrorMessage() {\r
- return "Error in CompletionProcessor";\r
- }\r
-\r
- @Override\r
- public IContextInformationValidator getContextInformationValidator() {\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2014 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.sysdyn.ui.properties.widgets.expressions;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.resource.LocalResourceManager;
+import org.eclipse.jface.text.ITextViewer;
+import org.eclipse.jface.text.contentassist.CompletionProposal;
+import org.eclipse.jface.text.contentassist.ICompletionProposal;
+import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
+import org.eclipse.jface.text.contentassist.IContextInformation;
+import org.eclipse.jface.text.contentassist.IContextInformationValidator;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.properties.widgets.ShortcutTabWidget;
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;
+import org.simantics.sysdyn.utils.Function;
+
+
+/**
+ * IContentAssistProcessor to determine which options (the functions and
+ * variables available) are shown for ContentAssistant; this assist of
+ * text field allows long variable names to be selected from a popup menu.
+ * @author Tuomas Miettinen
+ *
+ */
+public class CompletionProcessor implements IContentAssistProcessor {
+
+ private final Table allowedVariables;
+ private ArrayList<Function> functions;
+ private ArrayList<String> variables = null;
+ private ArrayList<String> timeAndSelfVariables = null;
+ private final ExpressionWidgetInput input;
+
+ private LocalResourceManager resourceManager;
+
+ private static final char[] ALLOWED_CHARACTERS = {
+ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','å','ä','ö',
+ 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Å','Ä','Ö',
+ '1','2','3','4','5','6','7','8','9','0','.','(',')'};
+
+ private static final String ALLOWED_CONNECTED_CHARACTERS_REG_EXP = "[\\Q({[:;,<=>+-*/^\\E]";
+
+ private static final ArrayList<String> ALLOW_ALL_COMPLETIONS_LIST = new ArrayList<String>();
+ static {
+ ALLOW_ALL_COMPLETIONS_LIST.add("");
+ }
+
+ public CompletionProcessor(Table allowedVariables, boolean allowFunctions, ExpressionWidgetInput input) {
+ this.allowedVariables = allowedVariables;
+ this.input = input;
+ this.functions = new ArrayList<Function>();
+
+ if (allowFunctions) {
+ if (input != null && CompletionProcessor.this.input.variable != null) {
+ // Get the respective model
+ Resource model = null;
+ try {
+ model = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return Variables.getModel(graph, CompletionProcessor.this.input.variable);
+ }
+ });
+
+ //User defined functions
+ functions.addAll(Function.getUserDefinedFunctions(model));
+ // Shared functions
+ functions.addAll(Function.getSharedFunctions(model));
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // Collect built in functions and sort all functions.
+ functions.addAll(Function.getAllBuiltInFunctions());
+ Collections.sort(functions);
+ }
+ }
+
+ /**
+ * Collect and sort all variables.
+ */
+ private void findVariables() {
+ if (variables == null) {
+ variables = new ArrayList<String>();
+ timeAndSelfVariables = new ArrayList<String>();
+ if(allowedVariables != null && !allowedVariables.isDisposed()) {
+ TableItem[] connectedVariables = allowedVariables.getItems();
+ for(TableItem ti : connectedVariables) {
+ // The status of the variable is determined using the color of its table item :(
+ if (ExpressionUtils.variableTimeAndSelfColor(resourceManager).equals(ti.getForeground())) {
+ this.timeAndSelfVariables.add(ti.getText());
+ } else {
+ this.variables.add(ti.getText());
+ }
+
+ }
+ }
+ Collections.sort(variables);
+ Collections.sort(timeAndSelfVariables);
+ }
+ }
+
+ /**
+ * Create CompletionProposals of the variables and add them to array. Do not allow duplicates.
+ * @param array result array of CompletionProposals
+ * @param token current token
+ * @param offset an offset within the document for which completions should be computed
+ */
+ private void addVariables(ArrayList<ICompletionProposal> array, String token, int offset) {
+ Image imageVariable = resourceManager.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/variable.png")));
+ Image imageVariableGray = resourceManager.createImage(ImageDescriptor.createFromURL(Activator.getDefault().getBundle().getResource("icons/variableGray.png")));
+
+ for (String variable : variables) {
+ if ((token.length() == 0 || variable.toUpperCase().startsWith(token.toUpperCase()))
+ && !listContainsVariable(array, variable)) {
+ array.add(new CompletionProposal(variable,
+ offset - token.length(),
+ token.length(),
+ variable.length(),
+ imageVariable,
+ variable,
+ null,
+ null));
+ }
+ }
+ for (String variable : timeAndSelfVariables) {
+ if ((token.length() == 0 || variable.toUpperCase().startsWith(token.toUpperCase()))
+ && !listContainsVariable(array, variable)) {
+ array.add(new CompletionProposal(variable,
+ offset - token.length(),
+ token.length(),
+ variable.length(),
+ imageVariableGray,
+ variable,
+ null,
+ null));
+ }
+ }
+ }
+
+ private boolean listContainsVariable(ArrayList<ICompletionProposal> array,
+ String variable) {
+ for (ICompletionProposal proposal : array) {
+ if (proposal.getDisplayString().equals(variable))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Create CompletionProposals of the functions and add them to array.
+ * @param array result array of CompletionProposals
+ * @param token current token
+ * @param offset an offset within the document for which completions should be computed
+ */
+ private void addFunctions(ArrayList<ICompletionProposal> array, String token, int offset) {
+ // Parameters don't have functions
+ if (functions == null)
+ return;
+
+ // Create CompletionProposals out of Functions
+ for (Function function : functions) {
+ if (token.length() == 0 || function.getName().toUpperCase().startsWith(token.toUpperCase())) {
+ Image image = ShortcutTabWidget.getImage(resourceManager, function);
+ String parameterList = Function.inputListToString(function.getInputList());
+ array.add(new CompletionProposal(
+ function.getName() + "(" + parameterList + ")",
+ offset - token.length(),
+ token.length(),
+ function.getName().length() + 1,
+ image,
+ function.getName() + "(" + parameterList + ")",
+ null,
+ function.getDescriptionHTML()));
+ }
+ }
+ }
+
+ /**
+ * Collect all matching proposals. Duplicates are removed; the one with the longest token stays.
+ * @param possibleLabelBeginnings sets of whitespace delimited tokens (as Strings)
+ * @param offset an offset within the document for which completions should be computed
+ * @return Array of matching proposals
+ */
+ private ICompletionProposal[] collectProposals(ArrayList<String> possibleLabelBeginnings, int offset) {
+ ArrayList<ICompletionProposal> resultArray = new ArrayList<ICompletionProposal>();
+
+ // Find variables and functions and create CompletionProposals out of them.
+ findVariables();
+
+ // Sort the list based on the length of the tokens (descending) to get "" to end.
+ Collections.sort(possibleLabelBeginnings, new Comparator<String>(){
+ @Override
+ public int compare(String o1, String o2) {
+ if (o1.length() > o2.length()) {
+ return -1;
+ } else if (o1.length() < o2.length()) {
+ return 1;
+ }
+ return 0;
+ }
+ });
+
+ for (String possibleLabelBeginning : possibleLabelBeginnings) {
+ addVariables(resultArray, possibleLabelBeginning, offset);
+ }
+
+ // No support for whitespace in function names; get shortest beginning
+ addFunctions(resultArray, possibleLabelBeginnings.get(possibleLabelBeginnings.size() - 1), offset);
+
+ ICompletionProposal[] result = new ICompletionProposal[resultArray.size()];
+ for (int i = 0; i < result.length; ++i) {
+ result[i] = resultArray.get(i);
+ }
+ return result;
+ }
+
+ @Override
+ public ICompletionProposal[] computeCompletionProposals(
+ ITextViewer viewer, int offset) {
+ String equation = viewer.getDocument().get();
+ Control control = viewer.getTextWidget();
+ this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), control);
+
+ if (equation.length() == 0 || offset == 0) {
+ return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);
+ }
+
+ equation = equation.substring(0, offset);
+
+ // Split the equation on '+', '-', etc. characters
+ String stringsBetweenConnectedCharacters[] = equation.split(ALLOWED_CONNECTED_CHARACTERS_REG_EXP);
+ if (stringsBetweenConnectedCharacters.length == 0) {
+ return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);
+ }
+ String stringAfterLastConnectedCharacter = stringsBetweenConnectedCharacters[stringsBetweenConnectedCharacters.length - 1];
+ String stringAfterWhitespaceAfterLastConnectedCharacter = removeLeadingWhitespace(stringAfterLastConnectedCharacter);
+
+ // Split into tokens on whitespace characters, include also the trailing empty strings
+ String[] tokens = stringAfterWhitespaceAfterLastConnectedCharacter.split("[\\s]", -42);
+
+ // Only whitespace after the last connection character
+ if (allTokensAreEmpty(tokens))
+ return collectProposals(ALLOW_ALL_COMPLETIONS_LIST, offset);
+
+ return collectProposals(getPossibleLabelBeginnings(tokens), offset);
+ }
+
+ /**
+ * Collect all possible strings (with each whitespace replaced by a space character)
+ * which may be a beginning of a variable.
+ * Create the beginnings by adding whitespace between. E.g.:
+ * {"multi", "part", "variab"}
+ * -> { "multi part variab",
+ * "part variab",
+ * "variab" }
+ * @param tokens list of tokens
+ * @return all possible label beginnings
+ */
+ private ArrayList<String> getPossibleLabelBeginnings(String[] tokens) {
+ ArrayList<String> possibleLabelBeginnings = new ArrayList<String>();
+ for (int i = 0; i < tokens.length; ++i) {
+ String token = new String();
+ for (int j = i; j < tokens.length; ++j) {
+ token += " " + tokens[j];
+ }
+ // Remove the excess space character from the beginning
+ token = token.substring(1);
+
+ possibleLabelBeginnings.add(token);
+ }
+ return possibleLabelBeginnings;
+ }
+
+ /**
+ * Remove leading whitespace
+ * @param input
+ * @return
+ */
+ private String removeLeadingWhitespace(String input) {
+ for (int i = 0; i < input.length(); ++i) {
+ if (!Character.isWhitespace(input.charAt(i))) {
+ return input.substring(i);
+ }
+ }
+ return "";
+ }
+
+ private boolean allTokensAreEmpty(String[] tokens) {
+ for (String token : tokens)
+ if (!token.equals(""))
+ return false;
+ return true;
+ }
+
+ @Override
+ public IContextInformation[] computeContextInformation(
+ ITextViewer viewer, int offset) {
+ return null;
+ }
+
+ @Override
+ public char[] getCompletionProposalAutoActivationCharacters() {
+ return ALLOWED_CHARACTERS;
+ }
+
+ @Override
+ public char[] getContextInformationAutoActivationCharacters() {
+ return null;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ return "Error in CompletionProcessor";
+ }
+
+ @Override
+ public IContextInformationValidator getContextInformationValidator() {
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ConstantExpression extends BasicExpression {\r
-\r
- public ConstantExpression(ExpressionWidgetInput input) {\r
- super(input);\r
- try {\r
- this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return SysdynResource.getInstance(graph).ConstantExpression;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- @Override\r
- public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
- // Create the single field\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
- String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
-\r
- Label l = new Label(parent, SWT.NONE);\r
- l.setText("=");\r
- //System.out.println("ConstantExpression");\r
- expression = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
- expression.setExpression(equation);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
-\r
- }\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets.expressions;
+
+import java.util.Map;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.SysdynResource;
+
+public class ConstantExpression extends BasicExpression {
+
+ public ConstantExpression(ExpressionWidgetInput input) {
+ super(input);
+ try {
+ this.expressionType = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return SysdynResource.getInstance(graph).ConstantExpression;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {
+ // Create the single field
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);
+ String equation = data.get("equation") != null ? (String)data.get("equation") : "";
+
+ Label l = new Label(parent, SWT.NONE);
+ l.setText("=");
+ //System.out.println("ConstantExpression");
+ expression = new ExpressionField(parent, SWT.BORDER, null, false, input);
+ expression.setExpression(equation);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);
+
+ }
}
\ No newline at end of file
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
-\r
-import java.util.Arrays;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.text.BadLocationException;\r
-import org.eclipse.jface.text.IDocument;\r
-import org.eclipse.jface.text.IUndoManager;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.VerifyKeyListener;\r
-import org.eclipse.swt.events.FocusAdapter;\r
-import org.eclipse.swt.events.FocusEvent;\r
-import org.eclipse.swt.events.FocusListener;\r
-import org.eclipse.swt.events.KeyListener;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Combo;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Spinner;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.VirtualGraph;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.CommentMetadata;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * IExpression for displaying fields of DelayExpression\r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class DelayExpression implements IExpression {\r
-\r
- private ExpressionField equation, delayTime, initialValue;\r
- private ExpressionField lastSelectedText;\r
- private Spinner order;\r
- private final ExpressionWidgetInput input;\r
- private Resource expression;\r
- private Combo delayTypeCombo;\r
-\r
- /**\r
- * Creates a new DelayExpression\r
- * @param expression\r
- */\r
- public DelayExpression(ExpressionWidgetInput input) {\r
- this.input = input;\r
- this.expression = input.expression;\r
- }\r
-\r
- /**\r
- * Displays the fields for delayExpression\r
- */\r
- @Override\r
- public void createExpressionFields(Composite parent, final Map<String, Object> data, Table allowedVariables) {\r
- // Get possible existing data\r
- GridLayoutFactory.fillDefaults().numColumns(5).applyTo(parent);\r
- String eq = data.get("equation") != null ? (String)data.get("equation") : "";\r
- String dt = data.get("delayTime") != null ? (String)data.get("delayTime") : "";\r
- String iv = data.get("initialValue") != null ? (String)data.get("initialValue") : "";\r
- int o = data.get("order") != null ? (Integer)data.get("order") : 3;\r
-\r
- Label l = new Label(parent, SWT.NONE);\r
- l.setText("Expression");\r
-\r
- // Equation that is delayed\r
- equation = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
- equation.setExpression(eq);\r
- GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(equation);\r
- equation.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
-\r
- @Override\r
- public void focusLost(FocusEvent e) {\r
- lastSelectedText = equation;\r
- }\r
- });\r
-\r
- l = new Label(parent, SWT.NONE);\r
- l.setText("Delay time");\r
-\r
- // How much the equation is delayed\r
- delayTime = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
- delayTime.setExpression(dt);\r
- GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(delayTime);\r
-\r
- delayTime.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
-\r
- @Override\r
- public void focusLost(FocusEvent e) {\r
- lastSelectedText = delayTime;\r
- }\r
- });\r
-\r
- l = new Label(parent, SWT.NONE);\r
- l.setText("Initial value");\r
-\r
- // What is the initial value of the delay (empty == same as equation)\r
- initialValue = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);\r
- initialValue.setExpression(iv);\r
- GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(initialValue);\r
-\r
- initialValue.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
-\r
- @Override\r
- public void focusLost(FocusEvent e) {\r
- lastSelectedText = initialValue;\r
- }\r
- });\r
-\r
-\r
- l = new Label(parent, SWT.NONE);\r
- l.setText("Order");\r
-\r
- // The order of the delay (default == 3)\r
- order = new Spinner(parent, SWT.BORDER);\r
- order.setMinimum(1);\r
- order.setSelection(o);\r
- order.addSelectionListener(new SelectionAdapter() {\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- save(expression, data);\r
- }\r
- });\r
- GridDataFactory.fillDefaults().grab(false, false).applyTo(order);\r
- \r
- l = new Label(parent, SWT.NONE);\r
- l.setText("Delay type");\r
- GridDataFactory.fillDefaults().grab(true, false).align(SWT.END, SWT.CENTER).applyTo(l);\r
- \r
- // The type of the delay (material / information delay)\r
- delayTypeCombo = new Combo(parent, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);\r
- delayTypeCombo.add("Material");\r
- delayTypeCombo.add("Information");\r
- GridDataFactory.fillDefaults().applyTo(delayTypeCombo);\r
- \r
- // Initial selection to the combo\r
- try {\r
- boolean isInformationDelay = SimanticsUI.getSession().syncRequest(new Read<Boolean>(){\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- return graph.hasStatement(expression, sr.DelayExpression_isInformationDelay, expression);\r
- }\r
- });\r
- delayTypeCombo.select(isInformationDelay ? 1 : 0);\r
- } catch (DatabaseException e1) {\r
- delayTypeCombo.select(0);\r
- e1.printStackTrace();\r
- }\r
- \r
- // Modify listener for selecting the delay type\r
- delayTypeCombo.addModifyListener(new ModifyListener() {\r
-\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- save(expression, data);\r
- }\r
- });\r
- \r
- lastSelectedText = equation;\r
- }\r
-\r
- @Override\r
- public void focus() {\r
- lastSelectedText.setFocus();\r
- }\r
-\r
- @Override\r
- public List<ExpressionField> getExpressionFields() {\r
- return Arrays.asList(equation, delayTime, initialValue);\r
- }\r
-\r
- @Override\r
- public void readData(final Resource expression, Map<String, Object> data) {\r
- class Auxiliary {\r
- String equation, delayTime, initialValue;\r
- Integer order;\r
- Boolean isInformationDelay;\r
- }\r
-\r
- Auxiliary results = null;\r
-\r
- try {\r
- results = SimanticsUI.getSession().syncRequest(new Read<Auxiliary>() {\r
-\r
- @Override\r
- public Auxiliary perform(ReadGraph graph) throws DatabaseException {\r
- Auxiliary results = new Auxiliary();\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if (expression != null && graph.isInstanceOf(expression, sr.DelayExpression)) {\r
- results.equation = graph.getPossibleRelatedValue(expression, sr.DelayExpression_expression);\r
- results.delayTime = graph.getPossibleRelatedValue(expression, sr.DelayExpression_delayTime);\r
- results.initialValue = graph.getPossibleRelatedValue(expression, sr.DelayExpression_initialValue);\r
- results.order = graph.getPossibleRelatedValue(expression, sr.DelayExpression_order);\r
- results.isInformationDelay = graph.hasStatement(expression, sr.DelayExpression_isInformationDelay, expression);\r
- } else {\r
- results.equation = "";\r
- results.delayTime = "";\r
- results.order = 1;\r
- results.isInformationDelay = false;\r
- }\r
- return results;\r
- }\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- if(results.equation != null)\r
- data.put("equation", results.equation);\r
- if(results.delayTime != null)\r
- data.put("delayTime", results.delayTime);\r
- if(results.initialValue != null)\r
- data.put("initialValue", results.initialValue);\r
- if(results.order != null)\r
- data.put("order", results.order);\r
- if(results.isInformationDelay != null)\r
- data.put("isInformationDelay", results.isInformationDelay);\r
- }\r
-\r
- @Override\r
- public void replaceSelection(String var) {\r
- if(lastSelectedText != null) {\r
- IDocument doc = lastSelectedText.getDocument();\r
- try {\r
- Point selection = lastSelectedText.getSelection();\r
- doc.replace(selection.x, selection.y, var);\r
- lastSelectedText.setSelection(selection.x + var.length());\r
- } catch (BadLocationException e) {\r
- e.printStackTrace();\r
- }\r
- } \r
- }\r
-\r
- @Override\r
- public void save(Resource expr, Map<String, Object> data) {\r
- this.expression = expr;\r
- final String currentEquation = this.equation.getExpression();\r
- final String currentDelayTime = this.delayTime.getExpression();\r
- final String currentInitialValue = this.initialValue.getExpression();\r
- final Integer currentOrder = this.order.getSelection();\r
- final Boolean currentIsInformationDelay = (this.delayTypeCombo.getSelectionIndex() == 1);\r
-\r
- String oldEquation = (String)data.get("equation");\r
- String oldDelayTime = (String)data.get("delayTime");\r
- String oldInitialValue = (String)data.get("initialValue");\r
- Integer oldOrder = (Integer)data.get("order");\r
- Boolean oldIsInformationDelay = (Boolean)data.get("isInformationDelay");\r
-\r
- if(oldEquation == null || oldDelayTime == null || oldOrder == null \r
- || oldInitialValue == null || oldIsInformationDelay == null \r
- || !oldEquation.equals(currentEquation) || !oldDelayTime.equals(currentDelayTime) \r
- || !oldOrder.equals(currentOrder) || !oldInitialValue.equals(currentInitialValue)\r
- || !oldIsInformationDelay.equals(currentIsInformationDelay)) {\r
- // old value was null or value has changed -> Do save\r
-\r
- data.putAll(data);\r
- data.put("equation", currentEquation);\r
- data.put("delayTime", currentDelayTime);\r
- data.put("initialValue", currentInitialValue);\r
- data.put("order", currentOrder);\r
- data.put("isInformationDelay", currentIsInformationDelay);\r
-\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph g)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
-\r
- if(!g.isInstanceOf(expression, sr.DelayExpression)) {\r
- // Create a new DelayExpression, if the old expression was something else\r
- final Resource newExpression = GraphUtils.create2(g, sr.DelayExpression);\r
- String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);\r
- if(arrayRange != null)\r
- g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);\r
-\r
- final Resource variable = g.getPossibleObject(expression, l0.PartOf);\r
- Resource ownerList = g.getPossibleObject(variable, sr.Variable_expressionList);\r
- ListUtils.replace(g, ownerList, expression, newExpression);\r
- g.deny(expression, l0.PartOf);\r
- g.claim(newExpression, l0.PartOf, variable);\r
-\r
- VirtualGraph runtime = g.getService(VirtualGraph.class);\r
- g.syncRequest(new WriteRequest(runtime) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
- graph.deny(variable, sr.IndependentVariable_activeExpression);\r
- graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);\r
- }\r
- });\r
- expression = newExpression;\r
- }\r
- \r
- // Claim values\r
- g.claimLiteral(expression, sr.DelayExpression_expression, currentEquation);\r
- g.claimLiteral(expression, sr.DelayExpression_delayTime, currentDelayTime);\r
- g.claimLiteral(expression, sr.DelayExpression_initialValue, currentInitialValue);\r
- g.claimLiteral(expression, sr.DelayExpression_order, currentOrder);\r
- if (currentIsInformationDelay)\r
- g.claim(expression, sr.DelayExpression_isInformationDelay, expression);\r
- else\r
- g.deny(expression, sr.DelayExpression_isInformationDelay, expression);\r
- \r
- g.markUndoPoint();\r
- CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
- g.addMetadata(cm.add("Set delay expression"));\r
- \r
- }\r
- });\r
- }\r
-\r
- }\r
-\r
- @Override\r
- public void updateData(Map<String, Object> data) {\r
- if(this.equation != null && this.equation.getExpression() != null)\r
- data.put("equation", this.equation.getExpression());\r
- if(this.delayTime != null && this.delayTime.getExpression() != null)\r
- data.put("delayTime", this.delayTime.getExpression()); \r
- if(this.initialValue != null && this.initialValue.getExpression() != null)\r
- data.put("initialValue", this.initialValue.getExpression()); \r
- if(this.order != null)\r
- data.put("order", this.order.getSelection()); \r
- if(this.delayTypeCombo != null)\r
- data.put("isInformationDelay", (this.delayTypeCombo.getSelectionIndex() == 1));\r
- }\r
-\r
- @Override\r
- public void addKeyListener(KeyListener listener) {\r
- this.equation.getSourceViewer().getTextWidget().addKeyListener(listener);\r
- this.delayTime.getSourceViewer().getTextWidget().addKeyListener(listener);\r
- this.initialValue.getSourceViewer().getTextWidget().addKeyListener(listener);\r
- }\r
-\r
- @Override\r
- public void addModifyListener(ModifyListener listener) {\r
- this.equation.getSourceViewer().getTextWidget().addModifyListener(listener);\r
- this.delayTime.getSourceViewer().getTextWidget().addModifyListener(listener);\r
- this.initialValue.getSourceViewer().getTextWidget().addModifyListener(listener);\r
- }\r
-\r
- @Override\r
- public void addFocusListener(FocusListener listener) {\r
- this.equation.getSourceViewer().getTextWidget().addFocusListener(listener);\r
- this.delayTime.getSourceViewer().getTextWidget().addFocusListener(listener);\r
- this.initialValue.getSourceViewer().getTextWidget().addFocusListener(listener);\r
- }\r
-\r
- @Override\r
- public void addVerifyKeyListener(VerifyKeyListener listener) {\r
- this.equation.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
- this.delayTime.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
- this.initialValue.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
- }\r
-\r
- @Override\r
- public IUndoManager getUndoManager() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets.expressions;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IUndoManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.VerifyKeyListener;
+import org.eclipse.swt.events.FocusAdapter;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Spinner;
+import org.eclipse.swt.widgets.Table;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.VirtualGraph;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.CommentMetadata;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+
+/**
+ * IExpression for displaying fields of DelayExpression
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class DelayExpression implements IExpression {
+
+ private ExpressionField equation, delayTime, initialValue;
+ private ExpressionField lastSelectedText;
+ private Spinner order;
+ private final ExpressionWidgetInput input;
+ private Resource expression;
+ private Combo delayTypeCombo;
+
+ /**
+ * Creates a new DelayExpression
+ * @param expression
+ */
+ public DelayExpression(ExpressionWidgetInput input) {
+ this.input = input;
+ this.expression = input.expression;
+ }
+
+ /**
+ * Displays the fields for delayExpression
+ */
+ @Override
+ public void createExpressionFields(Composite parent, final Map<String, Object> data, Table allowedVariables) {
+ // Get possible existing data
+ GridLayoutFactory.fillDefaults().numColumns(5).applyTo(parent);
+ String eq = data.get("equation") != null ? (String)data.get("equation") : "";
+ String dt = data.get("delayTime") != null ? (String)data.get("delayTime") : "";
+ String iv = data.get("initialValue") != null ? (String)data.get("initialValue") : "";
+ int o = data.get("order") != null ? (Integer)data.get("order") : 3;
+
+ Label l = new Label(parent, SWT.NONE);
+ l.setText("Expression");
+
+ // Equation that is delayed
+ equation = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);
+ equation.setExpression(eq);
+ GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(equation);
+ equation.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ lastSelectedText = equation;
+ }
+ });
+
+ l = new Label(parent, SWT.NONE);
+ l.setText("Delay time");
+
+ // How much the equation is delayed
+ delayTime = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);
+ delayTime.setExpression(dt);
+ GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(delayTime);
+
+ delayTime.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ lastSelectedText = delayTime;
+ }
+ });
+
+ l = new Label(parent, SWT.NONE);
+ l.setText("Initial value");
+
+ // What is the initial value of the delay (empty == same as equation)
+ initialValue = new ExpressionField(parent, SWT.BORDER, allowedVariables, true, input);
+ initialValue.setExpression(iv);
+ GridDataFactory.fillDefaults().span(4, 1).grab(true, true).applyTo(initialValue);
+
+ initialValue.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ lastSelectedText = initialValue;
+ }
+ });
+
+
+ l = new Label(parent, SWT.NONE);
+ l.setText("Order");
+
+ // The order of the delay (default == 3)
+ order = new Spinner(parent, SWT.BORDER);
+ order.setMinimum(1);
+ order.setSelection(o);
+ order.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ save(expression, data);
+ }
+ });
+ GridDataFactory.fillDefaults().grab(false, false).applyTo(order);
+
+ l = new Label(parent, SWT.NONE);
+ l.setText("Delay type");
+ GridDataFactory.fillDefaults().grab(true, false).align(SWT.END, SWT.CENTER).applyTo(l);
+
+ // The type of the delay (material / information delay)
+ delayTypeCombo = new Combo(parent, SWT.DROP_DOWN | SWT.BORDER | SWT.READ_ONLY);
+ delayTypeCombo.add("Material");
+ delayTypeCombo.add("Information");
+ GridDataFactory.fillDefaults().applyTo(delayTypeCombo);
+
+ // Initial selection to the combo
+ try {
+ boolean isInformationDelay = Simantics.getSession().syncRequest(new Read<Boolean>(){
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ return graph.hasStatement(expression, sr.DelayExpression_isInformationDelay, expression);
+ }
+ });
+ delayTypeCombo.select(isInformationDelay ? 1 : 0);
+ } catch (DatabaseException e1) {
+ delayTypeCombo.select(0);
+ e1.printStackTrace();
+ }
+
+ // Modify listener for selecting the delay type
+ delayTypeCombo.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ save(expression, data);
+ }
+ });
+
+ lastSelectedText = equation;
+ }
+
+ @Override
+ public void focus() {
+ lastSelectedText.setFocus();
+ }
+
+ @Override
+ public List<ExpressionField> getExpressionFields() {
+ return Arrays.asList(equation, delayTime, initialValue);
+ }
+
+ @Override
+ public void readData(final Resource expression, Map<String, Object> data) {
+ class Auxiliary {
+ String equation, delayTime, initialValue;
+ Integer order;
+ Boolean isInformationDelay;
+ }
+
+ Auxiliary results = null;
+
+ try {
+ results = Simantics.getSession().syncRequest(new Read<Auxiliary>() {
+
+ @Override
+ public Auxiliary perform(ReadGraph graph) throws DatabaseException {
+ Auxiliary results = new Auxiliary();
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if (expression != null && graph.isInstanceOf(expression, sr.DelayExpression)) {
+ results.equation = graph.getPossibleRelatedValue(expression, sr.DelayExpression_expression);
+ results.delayTime = graph.getPossibleRelatedValue(expression, sr.DelayExpression_delayTime);
+ results.initialValue = graph.getPossibleRelatedValue(expression, sr.DelayExpression_initialValue);
+ results.order = graph.getPossibleRelatedValue(expression, sr.DelayExpression_order);
+ results.isInformationDelay = graph.hasStatement(expression, sr.DelayExpression_isInformationDelay, expression);
+ } else {
+ results.equation = "";
+ results.delayTime = "";
+ results.order = 1;
+ results.isInformationDelay = false;
+ }
+ return results;
+ }
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ if(results.equation != null)
+ data.put("equation", results.equation);
+ if(results.delayTime != null)
+ data.put("delayTime", results.delayTime);
+ if(results.initialValue != null)
+ data.put("initialValue", results.initialValue);
+ if(results.order != null)
+ data.put("order", results.order);
+ if(results.isInformationDelay != null)
+ data.put("isInformationDelay", results.isInformationDelay);
+ }
+
+ @Override
+ public void replaceSelection(String var) {
+ if(lastSelectedText != null) {
+ IDocument doc = lastSelectedText.getDocument();
+ try {
+ Point selection = lastSelectedText.getSelection();
+ doc.replace(selection.x, selection.y, var);
+ lastSelectedText.setSelection(selection.x + var.length());
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void save(Resource expr, Map<String, Object> data) {
+ this.expression = expr;
+ final String currentEquation = this.equation.getExpression();
+ final String currentDelayTime = this.delayTime.getExpression();
+ final String currentInitialValue = this.initialValue.getExpression();
+ final Integer currentOrder = this.order.getSelection();
+ final Boolean currentIsInformationDelay = (this.delayTypeCombo.getSelectionIndex() == 1);
+
+ String oldEquation = (String)data.get("equation");
+ String oldDelayTime = (String)data.get("delayTime");
+ String oldInitialValue = (String)data.get("initialValue");
+ Integer oldOrder = (Integer)data.get("order");
+ Boolean oldIsInformationDelay = (Boolean)data.get("isInformationDelay");
+
+ if(oldEquation == null || oldDelayTime == null || oldOrder == null
+ || oldInitialValue == null || oldIsInformationDelay == null
+ || !oldEquation.equals(currentEquation) || !oldDelayTime.equals(currentDelayTime)
+ || !oldOrder.equals(currentOrder) || !oldInitialValue.equals(currentInitialValue)
+ || !oldIsInformationDelay.equals(currentIsInformationDelay)) {
+ // old value was null or value has changed -> Do save
+
+ data.putAll(data);
+ data.put("equation", currentEquation);
+ data.put("delayTime", currentDelayTime);
+ data.put("initialValue", currentInitialValue);
+ data.put("order", currentOrder);
+ data.put("isInformationDelay", currentIsInformationDelay);
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph g)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+
+ if(!g.isInstanceOf(expression, sr.DelayExpression)) {
+ // Create a new DelayExpression, if the old expression was something else
+ final Resource newExpression = GraphUtils.create2(g, sr.DelayExpression);
+ String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);
+ if(arrayRange != null)
+ g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);
+
+ final Resource variable = g.getPossibleObject(expression, l0.PartOf);
+ Resource ownerList = g.getPossibleObject(variable, sr.Variable_expressionList);
+ ListUtils.replace(g, ownerList, expression, newExpression);
+ g.deny(expression, l0.PartOf);
+ g.claim(newExpression, l0.PartOf, variable);
+
+ VirtualGraph runtime = g.getService(VirtualGraph.class);
+ g.syncRequest(new WriteRequest(runtime) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))
+ graph.deny(variable, sr.IndependentVariable_activeExpression);
+ graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);
+ }
+ });
+ expression = newExpression;
+ }
+
+ // Claim values
+ g.claimLiteral(expression, sr.DelayExpression_expression, currentEquation);
+ g.claimLiteral(expression, sr.DelayExpression_delayTime, currentDelayTime);
+ g.claimLiteral(expression, sr.DelayExpression_initialValue, currentInitialValue);
+ g.claimLiteral(expression, sr.DelayExpression_order, currentOrder);
+ if (currentIsInformationDelay)
+ g.claim(expression, sr.DelayExpression_isInformationDelay, expression);
+ else
+ g.deny(expression, sr.DelayExpression_isInformationDelay, expression);
+
+ g.markUndoPoint();
+ CommentMetadata cm = g.getMetadata(CommentMetadata.class);
+ g.addMetadata(cm.add("Set delay expression"));
+
+ }
+ });
+ }
+
+ }
+
+ @Override
+ public void updateData(Map<String, Object> data) {
+ if(this.equation != null && this.equation.getExpression() != null)
+ data.put("equation", this.equation.getExpression());
+ if(this.delayTime != null && this.delayTime.getExpression() != null)
+ data.put("delayTime", this.delayTime.getExpression());
+ if(this.initialValue != null && this.initialValue.getExpression() != null)
+ data.put("initialValue", this.initialValue.getExpression());
+ if(this.order != null)
+ data.put("order", this.order.getSelection());
+ if(this.delayTypeCombo != null)
+ data.put("isInformationDelay", (this.delayTypeCombo.getSelectionIndex() == 1));
+ }
+
+ @Override
+ public void addKeyListener(KeyListener listener) {
+ this.equation.getSourceViewer().getTextWidget().addKeyListener(listener);
+ this.delayTime.getSourceViewer().getTextWidget().addKeyListener(listener);
+ this.initialValue.getSourceViewer().getTextWidget().addKeyListener(listener);
+ }
+
+ @Override
+ public void addModifyListener(ModifyListener listener) {
+ this.equation.getSourceViewer().getTextWidget().addModifyListener(listener);
+ this.delayTime.getSourceViewer().getTextWidget().addModifyListener(listener);
+ this.initialValue.getSourceViewer().getTextWidget().addModifyListener(listener);
+ }
+
+ @Override
+ public void addFocusListener(FocusListener listener) {
+ this.equation.getSourceViewer().getTextWidget().addFocusListener(listener);
+ this.delayTime.getSourceViewer().getTextWidget().addFocusListener(listener);
+ this.initialValue.getSourceViewer().getTextWidget().addFocusListener(listener);
+ }
+
+ @Override
+ public void addVerifyKeyListener(VerifyKeyListener listener) {
+ this.equation.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);
+ this.delayTime.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);
+ this.initialValue.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);
+ }
+
+ @Override
+ public IUndoManager getUndoManager() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
-\r
-\r
-import java.util.Map;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.CommentMetadata;\r
-import org.simantics.db.common.request.WriteResultRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperiment;\r
-import org.simantics.simulation.project.IExperimentManager;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynGameExperimentBase;\r
-import org.simantics.sysdyn.ui.utils.ExpressionUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ParameterExpression extends BasicExpression {\r
-\r
- Variable variable;\r
-\r
- public ParameterExpression(ExpressionWidgetInput input) {\r
- super(input);\r
- try {\r
- this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return SysdynResource.getInstance(graph).ParameterExpression;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- } \r
- \r
- this.variable = input.variable;\r
- }\r
-\r
-\r
- @Override\r
- public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {\r
- // Create the single field\r
- GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);\r
- String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
-\r
- Label l = new Label(parent, SWT.NONE);\r
- l.setText("=");\r
-\r
- expression = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
- expression.setExpression(equation);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
-\r
- }\r
-\r
- @Override\r
- public void readData(final Resource expression, Map<String, Object> data) {\r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment == null || !(experiment instanceof SysdynGameExperimentBase)) {\r
- super.readData(expression, data);\r
- } else {\r
- Double value;\r
- ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState();\r
- if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) {\r
- try {\r
- value = SimanticsUI.getSession().syncRequest(new Read<Double>() {\r
-\r
- @Override\r
- public Double perform(ReadGraph graph) throws DatabaseException {\r
- try {\r
- Variable valuesVariable = variable.browsePossible(graph, "#value#");\r
- double[] res = valuesVariable.getValue(graph);\r
- if(res != null && res.length == 1)\r
- return res[0];\r
- else\r
- return null;\r
- } catch (DatabaseException e) {\r
- throw new DatabaseException(e.getMessage());\r
- } \r
- }\r
- });\r
- if(value != null)\r
- data.put("equation", value.toString());\r
- } catch (DatabaseException e) {}\r
- }\r
- super.readData(expression, data);\r
-\r
- }\r
- }\r
-\r
- @Override\r
- public void save(final Resource expression, Map<String, Object> data) {\r
-\r
- IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
- IExperiment experiment = manager.getActiveExperiment();\r
- if(experiment != null && experiment instanceof SysdynGameExperimentBase) {\r
- final String currentText = this.expression.getExpression();\r
- final String oldEquation = (String)data.get("equation");\r
- if(oldEquation == null || \r
- (currentText != null && oldEquation != null && !currentText.equals(oldEquation) && expressionType != null)) {\r
- if(ExpressionUtils.isParameter(currentText)) {\r
- Boolean savedIntoFMU = false;\r
-\r
- ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState();\r
- // Set value to control only if the simulation is running or stopped, not before initialization\r
- if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) {\r
- try {\r
- savedIntoFMU = SimanticsUI.getSession().syncRequest(new WriteResultRequest<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(WriteGraph graph)\r
- throws DatabaseException {\r
- try {\r
- Variable valuesVariable = variable.browsePossible(graph, "#value#");\r
- if(valuesVariable == null)\r
- return false;\r
- valuesVariable.setValue(graph, new double[] {Double.parseDouble(currentText)});\r
- \r
- graph.markUndoPoint();\r
- CommentMetadata cm = graph.getMetadata(CommentMetadata.class);\r
- graph.addMetadata(cm.add("Set parameter"));\r
- \r
- return true;\r
- } catch (Exception e) {\r
- return false;\r
- }\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {}\r
- }\r
-\r
- if(savedIntoFMU) {\r
- data.put("equation", currentText);\r
- return;\r
- }\r
- }\r
- }\r
- }\r
-\r
- // If setting a parameter value was not succesful, use the normal save-method\r
- super.save(expression, data);\r
- }\r
-\r
- public ParameterExpression() {\r
- super(null);\r
- try {\r
- this.expressionType = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return SysdynResource.getInstance(graph).ParameterExpression;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.properties.widgets.expressions;
+
+
+import java.util.Map;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.CommentMetadata;
+import org.simantics.db.common.request.WriteResultRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.request.Read;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperiment;
+import org.simantics.simulation.project.IExperimentManager;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynGameExperimentBase;
+import org.simantics.sysdyn.ui.utils.ExpressionUtils;
+
+public class ParameterExpression extends BasicExpression {
+
+ Variable variable;
+
+ public ParameterExpression(ExpressionWidgetInput input) {
+ super(input);
+ try {
+ this.expressionType = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return SysdynResource.getInstance(graph).ParameterExpression;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ this.variable = input.variable;
+ }
+
+
+ @Override
+ public void createExpressionFields(Composite parent, Map<String, Object> data, Table allowedVariables) {
+ // Create the single field
+ GridLayoutFactory.fillDefaults().numColumns(2).applyTo(parent);
+ String equation = data.get("equation") != null ? (String)data.get("equation") : "";
+
+ Label l = new Label(parent, SWT.NONE);
+ l.setText("=");
+
+ expression = new ExpressionField(parent, SWT.BORDER, null, false, input);
+ expression.setExpression(equation);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);
+
+ }
+
+ @Override
+ public void readData(final Resource expression, Map<String, Object> data) {
+ IExperimentManager manager = Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment == null || !(experiment instanceof SysdynGameExperimentBase)) {
+ super.readData(expression, data);
+ } else {
+ Double value;
+ ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState();
+ if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) {
+ try {
+ value = Simantics.getSession().syncRequest(new Read<Double>() {
+
+ @Override
+ public Double perform(ReadGraph graph) throws DatabaseException {
+ try {
+ Variable valuesVariable = variable.browsePossible(graph, "#value#");
+ double[] res = valuesVariable.getValue(graph);
+ if(res != null && res.length == 1)
+ return res[0];
+ else
+ return null;
+ } catch (DatabaseException e) {
+ throw new DatabaseException(e.getMessage());
+ }
+ }
+ });
+ if(value != null)
+ data.put("equation", value.toString());
+ } catch (DatabaseException e) {}
+ }
+ super.readData(expression, data);
+
+ }
+ }
+
+ @Override
+ public void save(final Resource expression, Map<String, Object> data) {
+
+ IExperimentManager manager = Simantics.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
+ IExperiment experiment = manager.getActiveExperiment();
+ if(experiment != null && experiment instanceof SysdynGameExperimentBase) {
+ final String currentText = this.expression.getExpression();
+ final String oldEquation = (String)data.get("equation");
+ if(oldEquation == null ||
+ (currentText != null && oldEquation != null && !currentText.equals(oldEquation) && expressionType != null)) {
+ if(ExpressionUtils.isParameter(currentText)) {
+ Boolean savedIntoFMU = false;
+
+ ExperimentState state = ((SysdynGameExperimentBase)experiment).getSysdynExperimentState();
+ // Set value to control only if the simulation is running or stopped, not before initialization
+ if(ExperimentState.RUNNING.equals(state) || ExperimentState.STOPPED.equals(state)) {
+ try {
+ savedIntoFMU = Simantics.getSession().syncRequest(new WriteResultRequest<Boolean>() {
+
+ @Override
+ public Boolean perform(WriteGraph graph)
+ throws DatabaseException {
+ try {
+ Variable valuesVariable = variable.browsePossible(graph, "#value#");
+ if(valuesVariable == null)
+ return false;
+ valuesVariable.setValue(graph, new double[] {Double.parseDouble(currentText)});
+
+ graph.markUndoPoint();
+ CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
+ graph.addMetadata(cm.add("Set parameter"));
+
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ });
+ } catch (DatabaseException e) {}
+ }
+
+ if(savedIntoFMU) {
+ data.put("equation", currentText);
+ return;
+ }
+ }
+ }
+ }
+
+ // If setting a parameter value was not succesful, use the normal save-method
+ super.save(expression, data);
+ }
+
+ public ParameterExpression() {
+ super(null);
+ try {
+ this.expressionType = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return SysdynResource.getInstance(graph).ParameterExpression;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.expressions;\r
-\r
-import java.awt.BasicStroke;\r
-import java.awt.Frame;\r
-import java.awt.event.ActionEvent;\r
-import java.awt.event.ActionListener;\r
-import java.awt.geom.Point2D;\r
-import java.io.StringReader;\r
-import java.util.ArrayList;\r
-import java.util.Arrays;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import javax.swing.Timer;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.text.BadLocationException;\r
-import org.eclipse.jface.text.IDocument;\r
-import org.eclipse.jface.text.IUndoManager;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.awt.SWT_AWT;\r
-import org.eclipse.swt.custom.VerifyKeyListener;\r
-import org.eclipse.swt.events.FocusAdapter;\r
-import org.eclipse.swt.events.FocusEvent;\r
-import org.eclipse.swt.events.FocusListener;\r
-import org.eclipse.swt.events.KeyListener;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.jfree.chart.ChartFactory;\r
-import org.jfree.chart.ChartPanel;\r
-import org.jfree.chart.JFreeChart;\r
-import org.jfree.chart.plot.PlotOrientation;\r
-import org.jfree.data.xy.XYDataset;\r
-import org.jfree.data.xy.XYSeries;\r
-import org.jfree.data.xy.XYSeriesCollection;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.VirtualGraph;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.CommentMetadata;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.tableParser.ParseException;\r
-import org.simantics.sysdyn.tableParser.TableParser;\r
-import org.simantics.sysdyn.tableParser.Token;\r
-import org.simantics.sysdyn.ui.utils.SyntaxError;\r
-import org.simantics.sysdyn.utils.SheetUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class WithLookupExpression implements IExpression {\r
-\r
- private ExpressionField expression;\r
- private ExpressionField lookup;\r
- private ExpressionField lastSelectedText = expression;\r
- private Timer updateChartTimer;\r
-\r
- private ChartPanel smallPanel;\r
- private Frame smallFrame;\r
-\r
- private final ExpressionWidgetInput input;\r
- private Resource expr;\r
-\r
- public WithLookupExpression(ExpressionWidgetInput input) {\r
- this.input = input;\r
- this.expr = input.expression;\r
- }\r
-\r
- @Override\r
- public void createExpressionFields(Composite parent, final Map<String, Object> data, Table allowedVariables) {\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parent);\r
-\r
- updateChartTimer = new Timer(1000, new ActionListener() {\r
-\r
- @Override\r
- public void actionPerformed(ActionEvent e) {\r
- updateChart();\r
- }\r
- });\r
- updateChartTimer.setRepeats(false);\r
-\r
- String equation = data.get("equation") != null ? (String)data.get("equation") : "";\r
- String lookupTable = data.get("lookup") != null ? (String)data.get("lookup") : "";\r
-\r
- Label l = new Label(parent, SWT.NONE);\r
- l.setText("With\nLookup");\r
-\r
- expression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true ,input);\r
- expression.setExpression(equation);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);\r
-\r
- expression.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
-\r
- @Override\r
- public void focusLost(FocusEvent e) {\r
- lastSelectedText = expression;\r
- }\r
- });\r
-\r
- Composite chartContainer = new Composite(parent, SWT.NONE);\r
- createChart(chartContainer, data);\r
-\r
-\r
- l = new Label(parent, SWT.NONE);\r
- l.setText("Lookup\ntable");\r
-\r
- lookup = new ExpressionField(parent, SWT.BORDER, null, false, input);\r
- lookup.setExpression(lookupTable);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(lookup);\r
-\r
- lookup.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
-\r
- @Override\r
- public void focusLost(FocusEvent e) {\r
- lastSelectedText = lookup;\r
- save(expr, data);\r
- }\r
- });\r
-\r
- lookup.getSourceViewer().getTextWidget().addModifyListener(new ModifyListener() {\r
-\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- if(!updateChartTimer.isRunning())\r
- updateChartTimer.start();\r
- else\r
- updateChartTimer.restart();\r
- }\r
- });\r
-\r
-\r
- SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- String result = "";\r
- if (expr != null && graph.isInstanceOf(expr, sr.WithLookupExpression)) {\r
- result = graph.getPossibleRelatedValue(expr, sr.WithLookupExpression_lookup);\r
- }\r
- return result;\r
- }\r
- }, new Listener<String>() {\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(final String result) {\r
- if(lookup != null)\r
- lookup.getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- lookup.setExpression(result); \r
- updateChart();\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- if(lookup != null && !lookup.isDisposed()) {\r
- return false;\r
- }\r
- return true;\r
- }\r
- });\r
-\r
- updateChart();\r
- }\r
-\r
- @Override\r
- public void focus() {\r
- if(this.lastSelectedText != null) this.lastSelectedText.focus(); \r
- }\r
-\r
- @Override\r
- public List<ExpressionField> getExpressionFields() {\r
- return Arrays.asList(this.expression, this.lookup);\r
- }\r
-\r
- @Override\r
- public void readData(final Resource expression, Map<String, Object> data) {\r
-\r
- class Auxiliary {\r
- String equation, lookup;\r
- }\r
-\r
- Auxiliary results = null;\r
-\r
- if (data.get("equation") == null) {\r
- try {\r
- results = SimanticsUI.getSession().syncRequest(new Read<Auxiliary>() {\r
-\r
- @Override\r
- public Auxiliary perform(ReadGraph graph) throws DatabaseException {\r
- Auxiliary results = new Auxiliary();\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if (expression != null && graph.isInstanceOf(expression, sr.WithLookupExpression)) {\r
- results.equation = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_expression);\r
- results.lookup = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);\r
- } else {\r
- results.equation = "";\r
- results.lookup = "";\r
- }\r
- return results;\r
- }\r
- });\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- data.put("equation", results.equation == null ? "" : results.equation);\r
- data.put("lookup", results.lookup == null ? "" : results.lookup);\r
- }\r
-\r
- }\r
-\r
- @Override\r
- public void replaceSelection(String var) {\r
- if(lastSelectedText != null) {\r
- IDocument doc = lastSelectedText.getDocument();\r
- try {\r
- Point selection = lastSelectedText.getSelection();\r
- doc.replace(selection.x, selection.y, var);\r
- lastSelectedText.setSelection(selection.x + var.length());\r
- } catch (BadLocationException e) {\r
- e.printStackTrace();\r
- }\r
- } \r
- }\r
-\r
- @Override\r
- public void save(final Resource expression, Map<String, Object> data) {\r
- final String currentExpression = this.expression.getExpression();\r
- final String currentLookupTable = lookup.getExpression();\r
- String oldExpression = (String)data.get("equation");\r
- String oldLookupTable = (String)data.get("lookup");\r
-\r
- if(oldExpression == null || oldLookupTable == null ||\r
- (currentExpression != null && currentLookupTable != null\r
- && (!currentExpression.equals(oldExpression) || \r
- !currentLookupTable.equals(oldLookupTable)))) {\r
- data.putAll(data);\r
- data.put("equation", currentExpression);\r
- data.put("lookup", currentLookupTable);\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph g)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Layer0 l0 = Layer0.getInstance(g);\r
-\r
- if(!g.isInstanceOf(expr, sr.WithLookupExpression)) {\r
-\r
-\r
- final Resource newExpression = GraphUtils.create2(g, sr.WithLookupExpression,\r
- sr.WithLookupExpression_minX, 0.0,\r
- sr.WithLookupExpression_maxX, 10.0,\r
- sr.WithLookupExpression_minY, 0.0,\r
- sr.WithLookupExpression_maxY, 10.0);\r
- String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);\r
- if(arrayRange != null)\r
- g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);\r
-\r
- final Resource variable = g.getSingleObject(expression, l0.PartOf);\r
- Resource expressions = g.getPossibleObject(variable, sr.Variable_expressionList);\r
- Resource node = ListUtils.getNode(g, expressions, expression);\r
- g.deny(node, l0.List_Element);\r
- g.claim(node, l0.List_Element, newExpression);\r
-\r
- g.deny(expression, l0.PartOf);\r
- g.claim(newExpression, l0.PartOf, variable);\r
-\r
- VirtualGraph runtime = g.getService(VirtualGraph.class);\r
- g.syncRequest(new WriteRequest(runtime) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))\r
- graph.deny(variable, sr.IndependentVariable_activeExpression);\r
- graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);\r
- }\r
- }\r
- );\r
- expr = newExpression;\r
-\r
- }\r
- g.claimLiteral(expr, sr.WithLookupExpression_expression, currentExpression);\r
- g.claimLiteral(expr, sr.WithLookupExpression_lookup, currentLookupTable);\r
- \r
- g.markUndoPoint();\r
- CommentMetadata cm = g.getMetadata(CommentMetadata.class);\r
- g.addMetadata(cm.add("Set lookup expression"));\r
- \r
- }\r
- });\r
- }\r
-\r
- }\r
-\r
- @Override\r
- public void updateData(Map<String, Object> data) {\r
- if(this.expression != null && this.expression.getExpression() != null)\r
- data.put("equation", this.expression.getExpression());\r
- if(this.lookup != null && this.lookup.getExpression() != null)\r
- data.put("lookup", this.lookup.getExpression()); \r
- }\r
-\r
- @Override\r
- public void addKeyListener(KeyListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addKeyListener(listener);\r
- this.lookup.getSourceViewer().getTextWidget().addKeyListener(listener);\r
- }\r
-\r
- @Override\r
- public void addVerifyKeyListener(VerifyKeyListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
- this.lookup.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);\r
- }\r
-\r
- @Override\r
- public void addModifyListener(ModifyListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addModifyListener(listener);\r
- this.lookup.getSourceViewer().getTextWidget().addModifyListener(listener);\r
- }\r
-\r
- @Override\r
- public void addFocusListener(FocusListener listener) {\r
- this.expression.getSourceViewer().getTextWidget().addFocusListener(listener);\r
- this.lookup.getSourceViewer().getTextWidget().addFocusListener(listener);\r
- }\r
-\r
- private void createChart(Composite composite, final Map<String, Object> data) {\r
- GridLayoutFactory.fillDefaults().applyTo(composite);\r
- GridDataFactory.fillDefaults().span(1, 2).hint(150, SWT.DEFAULT).applyTo(composite);\r
- final Composite chartComposite = new Composite(composite, \r
- SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(chartComposite);\r
- smallFrame = SWT_AWT.new_Frame(chartComposite);\r
-\r
- XYDataset dataset = new XYSeriesCollection(new XYSeries("Lookup Table"));\r
- JFreeChart chart = createChart(dataset);\r
- smallPanel = new ChartPanel(chart);\r
- smallFrame.add(smallPanel);\r
-\r
- }\r
-\r
- private static JFreeChart createChart(XYDataset dataset) {\r
- JFreeChart chart = ChartFactory.createXYLineChart(\r
- null,\r
- null,\r
- null,\r
- dataset,\r
- PlotOrientation.VERTICAL,\r
- true,\r
- true,\r
- false\r
- );\r
- chart.removeLegend();\r
- chart.getXYPlot().getDomainAxis().setTickLabelsVisible(true);\r
- chart.getXYPlot().getDomainAxis().setAxisLineVisible(false);\r
- chart.getXYPlot().getDomainAxis().setTickMarksVisible(true);\r
- chart.getXYPlot().getRangeAxis().setTickLabelsVisible(true);\r
- chart.getXYPlot().getRangeAxis().setAxisLineVisible(false);\r
- chart.getXYPlot().getRangeAxis().setTickMarksVisible(true);\r
- chart.getXYPlot().getRenderer().setSeriesStroke(0, new BasicStroke(3.0f));\r
- return chart;\r
- }\r
-\r
- private void updateChart() {\r
- ArrayList<Point2D> dataPoints = new ArrayList<Point2D>();\r
- TableParser parser = new TableParser(new StringReader(""));\r
- parser.ReInit(new StringReader(lookup.getExpression()));\r
- try {\r
- parser.table();\r
- ArrayList<Token> xTokens = parser.getXTokens();\r
- ArrayList<Token> yTokens = parser.getYTokens();\r
- for(int i = 0; i < xTokens.size(); i++) {\r
- dataPoints.add(new Point2D.Double(\r
- Double.parseDouble(xTokens.get(i).image), \r
- Double.parseDouble(yTokens.get(i).image)));\r
- }\r
- } catch (ParseException e1) {\r
- if(lookup.getExpression().matches("[a-zA-Z0-9]*\\([a-zA-Z0-9:]*\\)")) {\r
- // Might be a sheet reference\r
- try {\r
- final String name = lookup.getExpression().substring(0, lookup.getExpression().indexOf("("));\r
- final String range = lookup.getExpression().substring(lookup.getExpression().indexOf("(") + 1, lookup.getExpression().indexOf(")"));\r
- String possibleTable = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- Variable variable = input.variable;\r
- Resource model = Variables.getModel(graph, variable);\r
- return SheetUtils.getStringRepresentation(graph, model, name, range);\r
- }\r
-\r
- });\r
- \r
-\r
- try {\r
- if(possibleTable == null) {\r
- ParseException e = new ParseException(e1.getMessage());\r
- e.currentToken = e1.currentToken;\r
- throw e;\r
- }\r
- \r
- parser.ReInit(new StringReader(possibleTable));\r
- parser.table();\r
- ArrayList<Token> xTokens = parser.getXTokens();\r
- ArrayList<Token> yTokens = parser.getYTokens();\r
- for(int i = 0; i < xTokens.size(); i++) {\r
- dataPoints.add(new Point2D.Double(\r
- Double.parseDouble(xTokens.get(i).image), \r
- Double.parseDouble(yTokens.get(i).image)));\r
- }\r
- } catch (ParseException e2) {\r
- this.lookup.setSyntaxError(new SyntaxError(e2.currentToken, "Syntax Error"));\r
- System.out.println("MESSAGE: " + e2.getMessage());\r
- return;\r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- }\r
-\r
- XYSeries series = new XYSeries("Lookup Table");\r
- for(Point2D point : dataPoints) {\r
- series.add(point.getX(), point.getY());\r
- }\r
- XYSeriesCollection dataset = new XYSeriesCollection(series);\r
- smallPanel.getChart().getXYPlot().setDataset(dataset);\r
- }\r
-\r
- @Override\r
- public IUndoManager getUndoManager() {\r
- // TODO Auto-generated method stub\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.properties.widgets.expressions;
+
+import java.awt.BasicStroke;
+import java.awt.Frame;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.geom.Point2D;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import javax.swing.Timer;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.IUndoManager;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.awt.SWT_AWT;
+import org.eclipse.swt.custom.VerifyKeyListener;
+import org.eclipse.swt.events.FocusAdapter;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.events.FocusListener;
+import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Table;
+import org.jfree.chart.ChartFactory;
+import org.jfree.chart.ChartPanel;
+import org.jfree.chart.JFreeChart;
+import org.jfree.chart.plot.PlotOrientation;
+import org.jfree.data.xy.XYDataset;
+import org.jfree.data.xy.XYSeries;
+import org.jfree.data.xy.XYSeriesCollection;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.VirtualGraph;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.CommentMetadata;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.tableParser.ParseException;
+import org.simantics.sysdyn.tableParser.TableParser;
+import org.simantics.sysdyn.tableParser.Token;
+import org.simantics.sysdyn.ui.utils.SyntaxError;
+import org.simantics.sysdyn.utils.SheetUtils;
+
+public class WithLookupExpression implements IExpression {
+
+ private ExpressionField expression;
+ private ExpressionField lookup;
+ private ExpressionField lastSelectedText = expression;
+ private Timer updateChartTimer;
+
+ private ChartPanel smallPanel;
+ private Frame smallFrame;
+
+ private final ExpressionWidgetInput input;
+ private Resource expr;
+
+ public WithLookupExpression(ExpressionWidgetInput input) {
+ this.input = input;
+ this.expr = input.expression;
+ }
+
+ @Override
+ public void createExpressionFields(Composite parent, final Map<String, Object> data, Table allowedVariables) {
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(parent);
+
+ updateChartTimer = new Timer(1000, new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ updateChart();
+ }
+ });
+ updateChartTimer.setRepeats(false);
+
+ String equation = data.get("equation") != null ? (String)data.get("equation") : "";
+ String lookupTable = data.get("lookup") != null ? (String)data.get("lookup") : "";
+
+ Label l = new Label(parent, SWT.NONE);
+ l.setText("With\nLookup");
+
+ expression = new ExpressionField(parent, SWT.BORDER, allowedVariables, true ,input);
+ expression.setExpression(equation);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(expression);
+
+ expression.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ lastSelectedText = expression;
+ }
+ });
+
+ Composite chartContainer = new Composite(parent, SWT.NONE);
+ createChart(chartContainer, data);
+
+
+ l = new Label(parent, SWT.NONE);
+ l.setText("Lookup\ntable");
+
+ lookup = new ExpressionField(parent, SWT.BORDER, null, false, input);
+ lookup.setExpression(lookupTable);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(lookup);
+
+ lookup.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ lastSelectedText = lookup;
+ save(expr, data);
+ }
+ });
+
+ lookup.getSourceViewer().getTextWidget().addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ if(!updateChartTimer.isRunning())
+ updateChartTimer.start();
+ else
+ updateChartTimer.restart();
+ }
+ });
+
+
+ Simantics.getSession().asyncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ String result = "";
+ if (expr != null && graph.isInstanceOf(expr, sr.WithLookupExpression)) {
+ result = graph.getPossibleRelatedValue(expr, sr.WithLookupExpression_lookup);
+ }
+ return result;
+ }
+ }, new Listener<String>() {
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public void execute(final String result) {
+ if(lookup != null)
+ lookup.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ lookup.setExpression(result);
+ updateChart();
+ }
+ });
+ }
+
+ @Override
+ public boolean isDisposed() {
+ if(lookup != null && !lookup.isDisposed()) {
+ return false;
+ }
+ return true;
+ }
+ });
+
+ updateChart();
+ }
+
+ @Override
+ public void focus() {
+ if(this.lastSelectedText != null) this.lastSelectedText.focus();
+ }
+
+ @Override
+ public List<ExpressionField> getExpressionFields() {
+ return Arrays.asList(this.expression, this.lookup);
+ }
+
+ @Override
+ public void readData(final Resource expression, Map<String, Object> data) {
+
+ class Auxiliary {
+ String equation, lookup;
+ }
+
+ Auxiliary results = null;
+
+ if (data.get("equation") == null) {
+ try {
+ results = Simantics.getSession().syncRequest(new Read<Auxiliary>() {
+
+ @Override
+ public Auxiliary perform(ReadGraph graph) throws DatabaseException {
+ Auxiliary results = new Auxiliary();
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if (expression != null && graph.isInstanceOf(expression, sr.WithLookupExpression)) {
+ results.equation = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_expression);
+ results.lookup = graph.getPossibleRelatedValue(expression, sr.WithLookupExpression_lookup);
+ } else {
+ results.equation = "";
+ results.lookup = "";
+ }
+ return results;
+ }
+ });
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ data.put("equation", results.equation == null ? "" : results.equation);
+ data.put("lookup", results.lookup == null ? "" : results.lookup);
+ }
+
+ }
+
+ @Override
+ public void replaceSelection(String var) {
+ if(lastSelectedText != null) {
+ IDocument doc = lastSelectedText.getDocument();
+ try {
+ Point selection = lastSelectedText.getSelection();
+ doc.replace(selection.x, selection.y, var);
+ lastSelectedText.setSelection(selection.x + var.length());
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void save(final Resource expression, Map<String, Object> data) {
+ final String currentExpression = this.expression.getExpression();
+ final String currentLookupTable = lookup.getExpression();
+ String oldExpression = (String)data.get("equation");
+ String oldLookupTable = (String)data.get("lookup");
+
+ if(oldExpression == null || oldLookupTable == null ||
+ (currentExpression != null && currentLookupTable != null
+ && (!currentExpression.equals(oldExpression) ||
+ !currentLookupTable.equals(oldLookupTable)))) {
+ data.putAll(data);
+ data.put("equation", currentExpression);
+ data.put("lookup", currentLookupTable);
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph g)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Layer0 l0 = Layer0.getInstance(g);
+
+ if(!g.isInstanceOf(expr, sr.WithLookupExpression)) {
+
+
+ final Resource newExpression = GraphUtils.create2(g, sr.WithLookupExpression,
+ sr.WithLookupExpression_minX, 0.0,
+ sr.WithLookupExpression_maxX, 10.0,
+ sr.WithLookupExpression_minY, 0.0,
+ sr.WithLookupExpression_maxY, 10.0);
+ String arrayRange = g.getPossibleRelatedValue(expression, sr.Expression_arrayRange, Bindings.STRING);
+ if(arrayRange != null)
+ g.claimLiteral(newExpression, sr.Expression_arrayRange, arrayRange);
+
+ final Resource variable = g.getSingleObject(expression, l0.PartOf);
+ Resource expressions = g.getPossibleObject(variable, sr.Variable_expressionList);
+ Resource node = ListUtils.getNode(g, expressions, expression);
+ g.deny(node, l0.List_Element);
+ g.claim(node, l0.List_Element, newExpression);
+
+ g.deny(expression, l0.PartOf);
+ g.claim(newExpression, l0.PartOf, variable);
+
+ VirtualGraph runtime = g.getService(VirtualGraph.class);
+ g.syncRequest(new WriteRequest(runtime) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(graph.hasStatement(variable, sr.IndependentVariable_activeExpression))
+ graph.deny(variable, sr.IndependentVariable_activeExpression);
+ graph.claim(variable, sr.IndependentVariable_activeExpression, newExpression);
+ }
+ }
+ );
+ expr = newExpression;
+
+ }
+ g.claimLiteral(expr, sr.WithLookupExpression_expression, currentExpression);
+ g.claimLiteral(expr, sr.WithLookupExpression_lookup, currentLookupTable);
+
+ g.markUndoPoint();
+ CommentMetadata cm = g.getMetadata(CommentMetadata.class);
+ g.addMetadata(cm.add("Set lookup expression"));
+
+ }
+ });
+ }
+
+ }
+
+ @Override
+ public void updateData(Map<String, Object> data) {
+ if(this.expression != null && this.expression.getExpression() != null)
+ data.put("equation", this.expression.getExpression());
+ if(this.lookup != null && this.lookup.getExpression() != null)
+ data.put("lookup", this.lookup.getExpression());
+ }
+
+ @Override
+ public void addKeyListener(KeyListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addKeyListener(listener);
+ this.lookup.getSourceViewer().getTextWidget().addKeyListener(listener);
+ }
+
+ @Override
+ public void addVerifyKeyListener(VerifyKeyListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);
+ this.lookup.getSourceViewer().getTextWidget().addVerifyKeyListener(listener);
+ }
+
+ @Override
+ public void addModifyListener(ModifyListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addModifyListener(listener);
+ this.lookup.getSourceViewer().getTextWidget().addModifyListener(listener);
+ }
+
+ @Override
+ public void addFocusListener(FocusListener listener) {
+ this.expression.getSourceViewer().getTextWidget().addFocusListener(listener);
+ this.lookup.getSourceViewer().getTextWidget().addFocusListener(listener);
+ }
+
+ private void createChart(Composite composite, final Map<String, Object> data) {
+ GridLayoutFactory.fillDefaults().applyTo(composite);
+ GridDataFactory.fillDefaults().span(1, 2).hint(150, SWT.DEFAULT).applyTo(composite);
+ final Composite chartComposite = new Composite(composite,
+ SWT.NO_BACKGROUND | SWT.EMBEDDED);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(chartComposite);
+ smallFrame = SWT_AWT.new_Frame(chartComposite);
+
+ XYDataset dataset = new XYSeriesCollection(new XYSeries("Lookup Table"));
+ JFreeChart chart = createChart(dataset);
+ smallPanel = new ChartPanel(chart);
+ smallFrame.add(smallPanel);
+
+ }
+
+ private static JFreeChart createChart(XYDataset dataset) {
+ JFreeChart chart = ChartFactory.createXYLineChart(
+ null,
+ null,
+ null,
+ dataset,
+ PlotOrientation.VERTICAL,
+ true,
+ true,
+ false
+ );
+ chart.removeLegend();
+ chart.getXYPlot().getDomainAxis().setTickLabelsVisible(true);
+ chart.getXYPlot().getDomainAxis().setAxisLineVisible(false);
+ chart.getXYPlot().getDomainAxis().setTickMarksVisible(true);
+ chart.getXYPlot().getRangeAxis().setTickLabelsVisible(true);
+ chart.getXYPlot().getRangeAxis().setAxisLineVisible(false);
+ chart.getXYPlot().getRangeAxis().setTickMarksVisible(true);
+ chart.getXYPlot().getRenderer().setSeriesStroke(0, new BasicStroke(3.0f));
+ return chart;
+ }
+
+ private void updateChart() {
+ ArrayList<Point2D> dataPoints = new ArrayList<Point2D>();
+ TableParser parser = new TableParser(new StringReader(""));
+ parser.ReInit(new StringReader(lookup.getExpression()));
+ try {
+ parser.table();
+ ArrayList<Token> xTokens = parser.getXTokens();
+ ArrayList<Token> yTokens = parser.getYTokens();
+ for(int i = 0; i < xTokens.size(); i++) {
+ dataPoints.add(new Point2D.Double(
+ Double.parseDouble(xTokens.get(i).image),
+ Double.parseDouble(yTokens.get(i).image)));
+ }
+ } catch (ParseException e1) {
+ if(lookup.getExpression().matches("[a-zA-Z0-9]*\\([a-zA-Z0-9:]*\\)")) {
+ // Might be a sheet reference
+ try {
+ final String name = lookup.getExpression().substring(0, lookup.getExpression().indexOf("("));
+ final String range = lookup.getExpression().substring(lookup.getExpression().indexOf("(") + 1, lookup.getExpression().indexOf(")"));
+ String possibleTable = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ Variable variable = input.variable;
+ Resource model = Variables.getModel(graph, variable);
+ return SheetUtils.getStringRepresentation(graph, model, name, range);
+ }
+
+ });
+
+
+ try {
+ if(possibleTable == null) {
+ ParseException e = new ParseException(e1.getMessage());
+ e.currentToken = e1.currentToken;
+ throw e;
+ }
+
+ parser.ReInit(new StringReader(possibleTable));
+ parser.table();
+ ArrayList<Token> xTokens = parser.getXTokens();
+ ArrayList<Token> yTokens = parser.getYTokens();
+ for(int i = 0; i < xTokens.size(); i++) {
+ dataPoints.add(new Point2D.Double(
+ Double.parseDouble(xTokens.get(i).image),
+ Double.parseDouble(yTokens.get(i).image)));
+ }
+ } catch (ParseException e2) {
+ this.lookup.setSyntaxError(new SyntaxError(e2.currentToken, "Syntax Error"));
+ System.out.println("MESSAGE: " + e2.getMessage());
+ return;
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ XYSeries series = new XYSeries("Lookup Table");
+ for(Point2D point : dataPoints) {
+ series.add(point.getX(), point.getY());
+ }
+ XYSeriesCollection dataset = new XYSeriesCollection(series);
+ smallPanel.getChart().getXYPlot().setDataset(dataset);
+ }
+
+ @Override
+ public IUndoManager getUndoManager() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.externalFiles;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.request.Write;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ExternalFileNode extends AbstractNode<Resource> implements IModifiableNode, IDeletableNode {\r
-\r
- public ExternalFileNode(Resource data) {\r
- super(data);\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- try {\r
- final Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName;\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), data, hasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (label.isEmpty())\r
- return "Empty label not allowed";\r
- if (label.contains(" "))\r
- return "Spaces are not allowed";\r
- return null;\r
- }\r
-\r
- @Override\r
- protected Write getWriteRequest(final String label) {\r
- return new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph g) throws DatabaseException {\r
- g.claimLiteral(data, hasName, label);\r
- }\r
- };\r
- }\r
- };\r
- return modifier;\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return null;\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- RemoverUtil.remove(graph, data);\r
- }\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.properties.widgets.externalFiles;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.request.Write;
+import org.simantics.layer0.Layer0;
+
+public class ExternalFileNode extends AbstractNode<Resource> implements IModifiableNode, IDeletableNode {
+
+ public ExternalFileNode(Resource data) {
+ super(data);
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ try {
+ final Resource hasName = Layer0.getInstance(Simantics.getSession()).HasName;
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), data, hasName) {
+ @Override
+ public String isValid(String label) {
+ if (label.isEmpty())
+ return "Empty label not allowed";
+ if (label.contains(" "))
+ return "Spaces are not allowed";
+ return null;
+ }
+
+ @Override
+ protected Write getWriteRequest(final String label) {
+ return new WriteRequest() {
+ @Override
+ public void perform(WriteGraph g) throws DatabaseException {
+ g.claimLiteral(data, hasName, label);
+ }
+ };
+ }
+ };
+ return modifier;
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ RemoverUtil.remove(graph, data);
+ }
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.functions;\r
-\r
-import java.awt.event.ActionEvent;\r
-import java.awt.event.ActionListener;\r
-import java.io.StringReader;\r
-import java.util.ArrayList;\r
-\r
-import javax.swing.Timer;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.StyledText;\r
-import org.eclipse.swt.custom.VerifyKeyListener;\r
-import org.eclipse.swt.events.FocusAdapter;\r
-import org.eclipse.swt.events.FocusEvent;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.VerifyEvent;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Listener;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.IsParent;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.modelParser.ModelParser;\r
-import org.simantics.sysdyn.modelParser.ModelParser.Parameter;\r
-import org.simantics.sysdyn.modelParser.ParseException;\r
-import org.simantics.sysdyn.modelParser.Token;\r
-import org.simantics.sysdyn.modelParser.TokenMgrError;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
-import org.simantics.sysdyn.ui.utils.SyntaxError;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class FunctionCodeWidget implements Widget {\r
- \r
- private ExpressionField modelicaCode;\r
- private Resource function;\r
- \r
- private Timer updateChartTimer;\r
- private static int VALIDATION_DELAY_TIME = 500;\r
- \r
- private ArrayList<Parameter> inputs;\r
- private ArrayList<Parameter> outputs;\r
- \r
- public FunctionCodeWidget(Composite parent, WidgetSupport support, int style) {\r
- support.register(this);\r
- modelicaCode = new ExpressionField(parent, SWT.BORDER, null, false, null);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(modelicaCode);\r
- \r
-\r
- // Support shift+enter for line change\r
- modelicaCode.getSourceViewer().getTextWidget().addVerifyKeyListener(new VerifyKeyListener() {\r
-\r
- @Override\r
- public void verifyKey(VerifyEvent event) {\r
- if(event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR) {\r
- if((event.stateMask & SWT.SHIFT) == 0) {\r
- event.doit = false;\r
- Listener[] listeners = modelicaCode.getSourceViewer().getTextWidget().getListeners(SWT.FocusOut);\r
- for(Listener l : listeners) {\r
- modelicaCode.getSourceViewer().getTextWidget().removeListener(SWT.FocusOut, l);\r
- }\r
- ((StyledText)event.widget).getParent().forceFocus();\r
- save();\r
- for(Listener l : listeners) {\r
- modelicaCode.getSourceViewer().getTextWidget().addListener(SWT.FocusOut, l);\r
- }\r
- \r
- }\r
- }\r
- }\r
- });\r
- \r
- \r
- modelicaCode.getSourceViewer().getTextWidget().addModifyListener(new ModifyListener() {\r
-\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- validateFieldsTimed();\r
- }\r
- });\r
- \r
- modelicaCode.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {\r
- @Override\r
- public void focusLost(FocusEvent e) {\r
- save();\r
- }\r
- });\r
- \r
- \r
- updateChartTimer = new Timer(VALIDATION_DELAY_TIME, new ActionListener() {\r
-\r
- @Override\r
- public void actionPerformed(ActionEvent e) {\r
- if(modelicaCode == null || modelicaCode.isDisposed())\r
- return;\r
- modelicaCode.getDisplay().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- validate();\r
- }\r
- });\r
- }\r
- });\r
- updateChartTimer.setRepeats(false);\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- function = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- \r
- try {\r
- String code = context.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- String code = graph.getPossibleRelatedValue(\r
- function, SysdynResource.getInstance(graph).SysdynModelicaFunction_modelicaFunctionCode);\r
- if (code == null) {\r
- code = graph.getPossibleRelatedValue(\r
- function, SysdynResource.getInstance(graph).SysdynModelicaFunction_modelicaFunctionInterface);\r
- if (code == null) {\r
- code = new String("");\r
- }\r
- }\r
- return code;\r
- }\r
- \r
- });\r
- if(code != null) {\r
- modelicaCode.setExpression(code);\r
- \r
- boolean editable = context.getSession().syncRequest(new Read<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- boolean asd = new IsParent(SysdynResource.getInstance(graph).Built$in_Functions, function).perform(graph);\r
- return !asd;\r
- }\r
- });\r
- modelicaCode.getSourceViewer().setEditable(editable);\r
- validate();\r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- \r
- public void validateFieldsTimed() { \r
- validateFieldsTimed(VALIDATION_DELAY_TIME);\r
- }\r
- \r
- public void validateFieldsTimed(int delay) {\r
- updateChartTimer.setDelay(delay);\r
- if(!updateChartTimer.isRunning())\r
- updateChartTimer.start();\r
- else\r
- updateChartTimer.restart();\r
- }\r
- \r
- public void validate() {\r
- modelicaCode.resetAnnotations();\r
- String code = modelicaCode.getExpression();\r
- StringReader sr = new StringReader(code);\r
- ModelParser modelParser = new ModelParser(sr);\r
- \r
- try {\r
- modelParser.parse_composition();\r
- \r
- inputs = modelParser.getInputs();\r
- outputs = modelParser.getOutputs();\r
-\r
- } catch (ParseException e1) {\r
- Token token = e1.currentToken;\r
- modelicaCode.setSyntaxError(new SyntaxError(token.image, "Syntax error", token.beginLine, token.beginColumn, token.endLine, token.endColumn));\r
- } catch (TokenMgrError err) {\r
- String message = err.getMessage();\r
- String line = message.substring(0, message.indexOf(","));\r
- line = line.substring(line.lastIndexOf(" ") + 1);\r
- String column = message.substring(message.indexOf(",") + 1, message.indexOf("."));\r
- column = column.substring(column.lastIndexOf(" ") + 1);\r
- try {\r
- Integer endLine = Integer.parseInt(line);\r
- Integer endColumn = Integer.parseInt(column);\r
- Token token = modelParser.token;\r
- modelicaCode.setSyntaxError(new SyntaxError(token.image, "Syntax error", token.endLine, token.endColumn, endLine, endColumn));\r
- } catch (NumberFormatException e) {\r
- \r
- }\r
- \r
- }\r
- }\r
- \r
- private void save() {\r
- \r
- if (!modelicaCode.getSourceViewer().isEditable())\r
- return;\r
- \r
- final String code = modelicaCode.getExpression();\r
- \r
- // Update input and output lists.\r
- validate();\r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- // Remove the existing input list\r
- removeInputList(graph);\r
- // Create the new input list\r
- createInputList(graph);\r
-\r
- // Remove the existing output list\r
- removeOutputList(graph);\r
- // Create the new output list\r
- createOutputList(graph);\r
- \r
- // Update the function code\r
- graph.claimLiteral(\r
- function, \r
- sr.SysdynModelicaFunction_modelicaFunctionCode, \r
- code);\r
- }\r
- \r
- private void removeInputList(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- \r
- Resource oldInputList = graph.getPossibleObject(function, sr.SysdynModelicaFunction_inputs);\r
- if (oldInputList != null) {\r
- // Find all the inputs \r
- for (Resource input : ListUtils.toList(graph, oldInputList)) {\r
- // Check if we have a variable length input\r
- if (graph.isInstanceOf(input, sr.SysdynModelicaFunction_VariableLengthInput)) {\r
- // The variable length inputs are found here\r
- Resource variableLengthInputLabels = graph.getPossibleObject(input, sr.SysdynModelicaFunction_VariableLengthInput_shownLabels);\r
- if (variableLengthInputLabels != null) {\r
- // Find labels (strings)\r
- for (Resource label : ListUtils.toList(graph, variableLengthInputLabels)) {\r
- //Remove string\r
- RemoverUtil.remove(graph, label);\r
- }\r
- // Remove list\r
- RemoverUtil.remove(graph, variableLengthInputLabels);\r
- }\r
- } \r
- // Remove the input\r
- RemoverUtil.remove(graph, input);\r
- }\r
- // Remove the list\r
- RemoverUtil.remove(graph, oldInputList);\r
- }\r
- }\r
- \r
- private void createInputList(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- \r
- ArrayList<Resource> inputResources = new ArrayList<Resource>();\r
- // Create inputs\r
- if (inputs != null) {\r
- for (Parameter input : inputs) {\r
- Resource r = GraphUtils.create2(graph, sr.SysdynModelicaFunction_Input,\r
- l0.HasName, input.name, \r
- sr.Variable_type, input.type,\r
- sr.SysdynModelicaFunction_optional, input.optional ? l0.True : l0.False);\r
- if (input.description != null) {\r
- // Description is optional\r
- graph.claimLiteral(r, sr.SysdynModelicaFunction_definition, input.description);\r
- }\r
- inputResources.add(r);\r
- }\r
- graph.claim(\r
- function, \r
- sr.SysdynModelicaFunction_inputs, \r
- ListUtils.create(graph, inputResources));\r
- }\r
- }\r
- \r
- private void removeOutputList(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- Resource oldOutputList = graph.getPossibleObject(function, sr.SysdynModelicaFunction_outputs);\r
- if (oldOutputList != null) {\r
- // Find all the outputs \r
- for (Resource output : ListUtils.toList(graph, oldOutputList)) {\r
- // Remove the output\r
- RemoverUtil.remove(graph, output);\r
- }\r
- // Remove the list\r
- RemoverUtil.remove(graph, oldOutputList);\r
- }\r
- }\r
- \r
- private void createOutputList(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- ArrayList<Resource> outputResources = new ArrayList<Resource>();\r
- // Create outputs\r
- if (outputs != null) {\r
- for (Parameter output : outputs) {\r
- Resource r = GraphUtils.create2(graph, sr.SysdynModelicaFunction_Output,\r
- l0.HasName, output.name, \r
- sr.Variable_type, output.type);\r
- if (output.description != null) {\r
- // Description is optional\r
- graph.claimLiteral(r, sr.SysdynModelicaFunction_definition, output.description);\r
- }\r
- outputResources.add(r);\r
- }\r
- graph.claim(\r
- function, \r
- sr.SysdynModelicaFunction_outputs, \r
- ListUtils.create(graph, outputResources));\r
- }\r
- \r
- }\r
-\r
- });\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.properties.widgets.functions;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.StringReader;
+import java.util.ArrayList;
+
+import javax.swing.Timer;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.custom.VerifyKeyListener;
+import org.eclipse.swt.events.FocusAdapter;
+import org.eclipse.swt.events.FocusEvent;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.VerifyEvent;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Listener;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.IsParent;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.modelParser.ModelParser;
+import org.simantics.sysdyn.modelParser.ModelParser.Parameter;
+import org.simantics.sysdyn.modelParser.ParseException;
+import org.simantics.sysdyn.modelParser.Token;
+import org.simantics.sysdyn.modelParser.TokenMgrError;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;
+import org.simantics.sysdyn.ui.utils.SyntaxError;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class FunctionCodeWidget implements Widget {
+
+ private ExpressionField modelicaCode;
+ private Resource function;
+
+ private Timer updateChartTimer;
+ private static int VALIDATION_DELAY_TIME = 500;
+
+ private ArrayList<Parameter> inputs;
+ private ArrayList<Parameter> outputs;
+
+ public FunctionCodeWidget(Composite parent, WidgetSupport support, int style) {
+ support.register(this);
+ modelicaCode = new ExpressionField(parent, SWT.BORDER, null, false, null);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(modelicaCode);
+
+
+ // Support shift+enter for line change
+ modelicaCode.getSourceViewer().getTextWidget().addVerifyKeyListener(new VerifyKeyListener() {
+
+ @Override
+ public void verifyKey(VerifyEvent event) {
+ if(event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR) {
+ if((event.stateMask & SWT.SHIFT) == 0) {
+ event.doit = false;
+ Listener[] listeners = modelicaCode.getSourceViewer().getTextWidget().getListeners(SWT.FocusOut);
+ for(Listener l : listeners) {
+ modelicaCode.getSourceViewer().getTextWidget().removeListener(SWT.FocusOut, l);
+ }
+ ((StyledText)event.widget).getParent().forceFocus();
+ save();
+ for(Listener l : listeners) {
+ modelicaCode.getSourceViewer().getTextWidget().addListener(SWT.FocusOut, l);
+ }
+
+ }
+ }
+ }
+ });
+
+
+ modelicaCode.getSourceViewer().getTextWidget().addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ validateFieldsTimed();
+ }
+ });
+
+ modelicaCode.getSourceViewer().getTextWidget().addFocusListener(new FocusAdapter() {
+ @Override
+ public void focusLost(FocusEvent e) {
+ save();
+ }
+ });
+
+
+ updateChartTimer = new Timer(VALIDATION_DELAY_TIME, new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if(modelicaCode == null || modelicaCode.isDisposed())
+ return;
+ modelicaCode.getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ validate();
+ }
+ });
+ }
+ });
+ updateChartTimer.setRepeats(false);
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ function = AdaptionUtils.adaptToSingle(input, Resource.class);
+
+ try {
+ String code = context.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ String code = graph.getPossibleRelatedValue(
+ function, SysdynResource.getInstance(graph).SysdynModelicaFunction_modelicaFunctionCode);
+ if (code == null) {
+ code = graph.getPossibleRelatedValue(
+ function, SysdynResource.getInstance(graph).SysdynModelicaFunction_modelicaFunctionInterface);
+ if (code == null) {
+ code = new String("");
+ }
+ }
+ return code;
+ }
+
+ });
+ if(code != null) {
+ modelicaCode.setExpression(code);
+
+ boolean editable = context.getSession().syncRequest(new Read<Boolean>() {
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ boolean asd = new IsParent(SysdynResource.getInstance(graph).Built$in_Functions, function).perform(graph);
+ return !asd;
+ }
+ });
+ modelicaCode.getSourceViewer().setEditable(editable);
+ validate();
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ public void validateFieldsTimed() {
+ validateFieldsTimed(VALIDATION_DELAY_TIME);
+ }
+
+ public void validateFieldsTimed(int delay) {
+ updateChartTimer.setDelay(delay);
+ if(!updateChartTimer.isRunning())
+ updateChartTimer.start();
+ else
+ updateChartTimer.restart();
+ }
+
+ public void validate() {
+ modelicaCode.resetAnnotations();
+ String code = modelicaCode.getExpression();
+ StringReader sr = new StringReader(code);
+ ModelParser modelParser = new ModelParser(sr);
+
+ try {
+ modelParser.parse_composition();
+
+ inputs = modelParser.getInputs();
+ outputs = modelParser.getOutputs();
+
+ } catch (ParseException e1) {
+ Token token = e1.currentToken;
+ modelicaCode.setSyntaxError(new SyntaxError(token.image, "Syntax error", token.beginLine, token.beginColumn, token.endLine, token.endColumn));
+ } catch (TokenMgrError err) {
+ String message = err.getMessage();
+ String line = message.substring(0, message.indexOf(","));
+ line = line.substring(line.lastIndexOf(" ") + 1);
+ String column = message.substring(message.indexOf(",") + 1, message.indexOf("."));
+ column = column.substring(column.lastIndexOf(" ") + 1);
+ try {
+ Integer endLine = Integer.parseInt(line);
+ Integer endColumn = Integer.parseInt(column);
+ Token token = modelParser.token;
+ modelicaCode.setSyntaxError(new SyntaxError(token.image, "Syntax error", token.endLine, token.endColumn, endLine, endColumn));
+ } catch (NumberFormatException e) {
+
+ }
+
+ }
+ }
+
+ private void save() {
+
+ if (!modelicaCode.getSourceViewer().isEditable())
+ return;
+
+ final String code = modelicaCode.getExpression();
+
+ // Update input and output lists.
+ validate();
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ // Remove the existing input list
+ removeInputList(graph);
+ // Create the new input list
+ createInputList(graph);
+
+ // Remove the existing output list
+ removeOutputList(graph);
+ // Create the new output list
+ createOutputList(graph);
+
+ // Update the function code
+ graph.claimLiteral(
+ function,
+ sr.SysdynModelicaFunction_modelicaFunctionCode,
+ code);
+ }
+
+ private void removeInputList(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ Resource oldInputList = graph.getPossibleObject(function, sr.SysdynModelicaFunction_inputs);
+ if (oldInputList != null) {
+ // Find all the inputs
+ for (Resource input : ListUtils.toList(graph, oldInputList)) {
+ // Check if we have a variable length input
+ if (graph.isInstanceOf(input, sr.SysdynModelicaFunction_VariableLengthInput)) {
+ // The variable length inputs are found here
+ Resource variableLengthInputLabels = graph.getPossibleObject(input, sr.SysdynModelicaFunction_VariableLengthInput_shownLabels);
+ if (variableLengthInputLabels != null) {
+ // Find labels (strings)
+ for (Resource label : ListUtils.toList(graph, variableLengthInputLabels)) {
+ //Remove string
+ RemoverUtil.remove(graph, label);
+ }
+ // Remove list
+ RemoverUtil.remove(graph, variableLengthInputLabels);
+ }
+ }
+ // Remove the input
+ RemoverUtil.remove(graph, input);
+ }
+ // Remove the list
+ RemoverUtil.remove(graph, oldInputList);
+ }
+ }
+
+ private void createInputList(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ ArrayList<Resource> inputResources = new ArrayList<Resource>();
+ // Create inputs
+ if (inputs != null) {
+ for (Parameter input : inputs) {
+ Resource r = GraphUtils.create2(graph, sr.SysdynModelicaFunction_Input,
+ l0.HasName, input.name,
+ sr.Variable_type, input.type,
+ sr.SysdynModelicaFunction_optional, input.optional ? l0.True : l0.False);
+ if (input.description != null) {
+ // Description is optional
+ graph.claimLiteral(r, sr.SysdynModelicaFunction_definition, input.description);
+ }
+ inputResources.add(r);
+ }
+ graph.claim(
+ function,
+ sr.SysdynModelicaFunction_inputs,
+ ListUtils.create(graph, inputResources));
+ }
+ }
+
+ private void removeOutputList(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ Resource oldOutputList = graph.getPossibleObject(function, sr.SysdynModelicaFunction_outputs);
+ if (oldOutputList != null) {
+ // Find all the outputs
+ for (Resource output : ListUtils.toList(graph, oldOutputList)) {
+ // Remove the output
+ RemoverUtil.remove(graph, output);
+ }
+ // Remove the list
+ RemoverUtil.remove(graph, oldOutputList);
+ }
+ }
+
+ private void createOutputList(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ ArrayList<Resource> outputResources = new ArrayList<Resource>();
+ // Create outputs
+ if (outputs != null) {
+ for (Parameter output : outputs) {
+ Resource r = GraphUtils.create2(graph, sr.SysdynModelicaFunction_Output,
+ l0.HasName, output.name,
+ sr.Variable_type, output.type);
+ if (output.description != null) {
+ // Description is optional
+ graph.claimLiteral(r, sr.SysdynModelicaFunction_definition, output.description);
+ }
+ outputResources.add(r);
+ }
+ graph.claim(
+ function,
+ sr.SysdynModelicaFunction_outputs,
+ ListUtils.create(graph, outputResources));
+ }
+
+ }
+
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.modules;\r
-\r
-import java.util.HashMap;\r
-\r
-import org.eclipse.jface.viewers.CellEditor;\r
-import org.eclipse.jface.viewers.ComboBoxCellEditor;\r
-import org.eclipse.jface.viewers.EditingSupport;\r
-import org.eclipse.jface.viewers.TableViewer;\r
-import org.eclipse.jface.viewers.TextCellEditor;\r
-import org.eclipse.swt.SWT;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ModuleInputEditingSupport extends EditingSupport {\r
- private CellEditor editor;\r
- private int column;\r
- private HashMap<String, Resource> optionResources;\r
- private String[] options;\r
- private TableViewer tableViewer;\r
-\r
- public ModuleInputEditingSupport(TableViewer viewer, int column) {\r
- super(viewer);\r
- this.tableViewer = (TableViewer)viewer;\r
- this.column = column;\r
- }\r
-\r
- @Override\r
- protected boolean canEdit(Object element) {\r
- switch (this.column) {\r
- case 0: return false;\r
- default: return true;\r
- }\r
- }\r
-\r
- \r
- @Override\r
- protected CellEditor getCellEditor(Object element) {\r
- // Create the correct editor based on the column index\r
- switch (column) {\r
- case 0: \r
- editor = new TextCellEditor(this.tableViewer.getTable());\r
- case 1:\r
- ReferenceRow row = (ReferenceRow)element;\r
- final Resource module = row.getModule();\r
- final Resource inputVariable = row.getVariable();\r
-\r
- optionResources = new HashMap<String, Resource>();\r
- try {\r
- optionResources = SimanticsUI.getSession().syncRequest(new Read<HashMap<String, Resource>>() {\r
-\r
- @Override\r
- public HashMap<String, Resource> perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- HashMap<String, Resource> result = new HashMap<String, Resource>();\r
- for(Resource dependency : graph.syncRequest(new ObjectsWithType(module, sr.Variable_isHeadOf, sr.Dependency))) {\r
- if(graph.getPossibleObject(dependency, sr.Dependency_refersTo) == null ||\r
- graph.getPossibleObject(dependency, sr.Dependency_refersTo).equals(inputVariable)) {\r
- Resource output = graph.getSingleObject(dependency, sr.Variable_HasTail);\r
- \r
- if(graph.isInstanceOf(output, sr.Shadow)) {\r
- output = graph.getPossibleObject(output, sr.Shadow_original);\r
- }\r
- \r
- if(output != null)\r
- result.put((String)graph.getRelatedValue(output, l0.HasName), dependency);\r
- }\r
- }\r
- return result;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- options = optionResources.keySet().toArray(new String[optionResources.keySet().size() + 1]);\r
- options[optionResources.keySet().size()] = "";\r
- ComboBoxCellEditor ceditor = new ComboBoxCellEditor(this.tableViewer.getTable(), options, SWT.READ_ONLY);\r
- ceditor.setActivationStyle(1);\r
- editor = ceditor;\r
- break;\r
- default:\r
- editor = null;\r
- }\r
-\r
- return editor;\r
- }\r
-\r
- @Override\r
- protected Object getValue(Object element) {\r
- ReferenceRow referenceRow = (ReferenceRow) element;\r
-\r
- switch (this.column) {\r
- case 0:\r
- return referenceRow.getName();\r
- case 1:\r
- String refersToName = referenceRow.getValue();\r
- if (refersToName == null) return options.length - 1;\r
- for(int i = 0; i < options.length ; i++) {\r
- if(refersToName.equals(options[i])) return i;\r
- }\r
- return options[options.length - 1];\r
- default:\r
- break;\r
- }\r
- return null;\r
- }\r
-\r
- @Override\r
- protected void setValue(Object element, Object value) {\r
- ReferenceRow referenceRow = (ReferenceRow) element;\r
- String valueString = String.valueOf(value);\r
- switch (this.column) {\r
- case 0:\r
- break;\r
- case 1:\r
- referenceRow.setRefersTo(optionResources.get(options[Integer.parseInt(valueString)]));\r
- break;\r
- default:\r
- break;\r
- }\r
-\r
- getViewer().update(element, null);\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.properties.widgets.modules;
+
+import java.util.HashMap;
+
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ComboBoxCellEditor;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.swt.SWT;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+
+public class ModuleInputEditingSupport extends EditingSupport {
+ private CellEditor editor;
+ private int column;
+ private HashMap<String, Resource> optionResources;
+ private String[] options;
+ private TableViewer tableViewer;
+
+ public ModuleInputEditingSupport(TableViewer viewer, int column) {
+ super(viewer);
+ this.tableViewer = (TableViewer)viewer;
+ this.column = column;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ switch (this.column) {
+ case 0: return false;
+ default: return true;
+ }
+ }
+
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ // Create the correct editor based on the column index
+ switch (column) {
+ case 0:
+ editor = new TextCellEditor(this.tableViewer.getTable());
+ case 1:
+ ReferenceRow row = (ReferenceRow)element;
+ final Resource module = row.getModule();
+ final Resource inputVariable = row.getVariable();
+
+ optionResources = new HashMap<String, Resource>();
+ try {
+ optionResources = Simantics.getSession().syncRequest(new Read<HashMap<String, Resource>>() {
+
+ @Override
+ public HashMap<String, Resource> perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ HashMap<String, Resource> result = new HashMap<String, Resource>();
+ for(Resource dependency : graph.syncRequest(new ObjectsWithType(module, sr.Variable_isHeadOf, sr.Dependency))) {
+ if(graph.getPossibleObject(dependency, sr.Dependency_refersTo) == null ||
+ graph.getPossibleObject(dependency, sr.Dependency_refersTo).equals(inputVariable)) {
+ Resource output = graph.getSingleObject(dependency, sr.Variable_HasTail);
+
+ if(graph.isInstanceOf(output, sr.Shadow)) {
+ output = graph.getPossibleObject(output, sr.Shadow_original);
+ }
+
+ if(output != null)
+ result.put((String)graph.getRelatedValue(output, l0.HasName), dependency);
+ }
+ }
+ return result;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ options = optionResources.keySet().toArray(new String[optionResources.keySet().size() + 1]);
+ options[optionResources.keySet().size()] = "";
+ ComboBoxCellEditor ceditor = new ComboBoxCellEditor(this.tableViewer.getTable(), options, SWT.READ_ONLY);
+ ceditor.setActivationStyle(1);
+ editor = ceditor;
+ break;
+ default:
+ editor = null;
+ }
+
+ return editor;
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ ReferenceRow referenceRow = (ReferenceRow) element;
+
+ switch (this.column) {
+ case 0:
+ return referenceRow.getName();
+ case 1:
+ String refersToName = referenceRow.getValue();
+ if (refersToName == null) return options.length - 1;
+ for(int i = 0; i < options.length ; i++) {
+ if(refersToName.equals(options[i])) return i;
+ }
+ return options[options.length - 1];
+ default:
+ break;
+ }
+ return null;
+ }
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ ReferenceRow referenceRow = (ReferenceRow) element;
+ String valueString = String.valueOf(value);
+ switch (this.column) {
+ case 0:
+ break;
+ case 1:
+ referenceRow.setRefersTo(optionResources.get(options[Integer.parseInt(valueString)]));
+ break;
+ default:
+ break;
+ }
+
+ getViewer().update(element, null);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.modules;\r
-\r
-import java.util.HashMap;\r
-\r
-import org.eclipse.jface.viewers.CellEditor;\r
-import org.eclipse.jface.viewers.ComboBoxCellEditor;\r
-import org.eclipse.jface.viewers.EditingSupport;\r
-import org.eclipse.jface.viewers.TableViewer;\r
-import org.eclipse.jface.viewers.TextCellEditor;\r
-import org.eclipse.swt.SWT;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ModuleOutputEditingSupport extends EditingSupport {\r
- private CellEditor editor;\r
- private int column;\r
- private HashMap<String, Resource> optionResources;\r
- private String[] options;\r
- private TableViewer tableViewer;\r
-\r
- public ModuleOutputEditingSupport(TableViewer viewer, int column) {\r
- super(viewer);\r
- this.tableViewer = (TableViewer)viewer;\r
- this.column = column;\r
- }\r
-\r
- @Override\r
- protected boolean canEdit(Object element) {\r
- switch (this.column) {\r
- case 0: return false;\r
- default: return true;\r
- }\r
- }\r
-\r
- \r
- @Override\r
- protected CellEditor getCellEditor(Object element) {\r
- // Create the correct editor based on the column index\r
- switch (column) {\r
- case 0: \r
- editor = new TextCellEditor(this.tableViewer.getTable());\r
- case 1:\r
- ReferenceRow row = (ReferenceRow)element;\r
- final Resource module = row.getModule();\r
- final Resource outputVariable = row.getVariable();\r
-\r
- optionResources = new HashMap<String, Resource>();\r
- try {\r
- optionResources = SimanticsUI.getSession().syncRequest(new Read<HashMap<String, Resource>>() {\r
-\r
- @Override\r
- public HashMap<String, Resource> perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- HashMap<String, Resource> result = new HashMap<String, Resource>();\r
- for(Resource dependency : graph.syncRequest(new ObjectsWithType(module, sr.Variable_isTailOf, sr.Dependency))) {\r
- if(graph.getPossibleObject(dependency, sr.Dependency_refersTo) == null \r
- || !graph.hasStatement(graph.getPossibleObject(dependency, sr.Dependency_refersTo), l0.HasName)\r
- || graph.getPossibleObject(dependency, sr.Dependency_refersTo).equals(outputVariable)) {\r
- Resource input = graph.getSingleObject(dependency, sr.Variable_HasHead);\r
- result.put((String)graph.getRelatedValue(input, l0.HasName), dependency);\r
- }\r
- }\r
- return result;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- options = optionResources.keySet().toArray(new String[optionResources.keySet().size() + 1]);\r
- options[optionResources.keySet().size()] = "";\r
- ComboBoxCellEditor ceditor = new ComboBoxCellEditor(this.tableViewer.getTable(), options, SWT.READ_ONLY);\r
- ceditor.setActivationStyle(1);\r
- editor = ceditor;\r
- break;\r
- default:\r
- editor = null;\r
- }\r
-\r
- return editor;\r
- }\r
-\r
- @Override\r
- protected Object getValue(Object element) {\r
- ReferenceRow referenceRow = (ReferenceRow) element;\r
-\r
- switch (this.column) {\r
- case 0:\r
- return referenceRow.getName();\r
- case 1:\r
- String refersToName = referenceRow.getValue();\r
- if (refersToName == null) return options.length - 1;\r
- for(int i = 0; i < options.length ; i++) {\r
- if(refersToName.equals(options[i])) return i;\r
- }\r
- return options[options.length - 1];\r
- default:\r
- break;\r
- }\r
- return null;\r
- }\r
-\r
- @Override\r
- protected void setValue(Object element, Object value) {\r
- ReferenceRow referenceRow = (ReferenceRow) element;\r
- String valueString = String.valueOf(value);\r
- switch (this.column) {\r
- case 0:\r
- break;\r
- case 1:\r
- referenceRow.setRefersTo(optionResources.get(options[Integer.parseInt(valueString)]));\r
- break;\r
- default:\r
- break;\r
- }\r
-\r
- getViewer().update(element, null);\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.properties.widgets.modules;
+
+import java.util.HashMap;
+
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ComboBoxCellEditor;
+import org.eclipse.jface.viewers.EditingSupport;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.swt.SWT;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+
+public class ModuleOutputEditingSupport extends EditingSupport {
+ private CellEditor editor;
+ private int column;
+ private HashMap<String, Resource> optionResources;
+ private String[] options;
+ private TableViewer tableViewer;
+
+ public ModuleOutputEditingSupport(TableViewer viewer, int column) {
+ super(viewer);
+ this.tableViewer = (TableViewer)viewer;
+ this.column = column;
+ }
+
+ @Override
+ protected boolean canEdit(Object element) {
+ switch (this.column) {
+ case 0: return false;
+ default: return true;
+ }
+ }
+
+
+ @Override
+ protected CellEditor getCellEditor(Object element) {
+ // Create the correct editor based on the column index
+ switch (column) {
+ case 0:
+ editor = new TextCellEditor(this.tableViewer.getTable());
+ case 1:
+ ReferenceRow row = (ReferenceRow)element;
+ final Resource module = row.getModule();
+ final Resource outputVariable = row.getVariable();
+
+ optionResources = new HashMap<String, Resource>();
+ try {
+ optionResources = Simantics.getSession().syncRequest(new Read<HashMap<String, Resource>>() {
+
+ @Override
+ public HashMap<String, Resource> perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ HashMap<String, Resource> result = new HashMap<String, Resource>();
+ for(Resource dependency : graph.syncRequest(new ObjectsWithType(module, sr.Variable_isTailOf, sr.Dependency))) {
+ if(graph.getPossibleObject(dependency, sr.Dependency_refersTo) == null
+ || !graph.hasStatement(graph.getPossibleObject(dependency, sr.Dependency_refersTo), l0.HasName)
+ || graph.getPossibleObject(dependency, sr.Dependency_refersTo).equals(outputVariable)) {
+ Resource input = graph.getSingleObject(dependency, sr.Variable_HasHead);
+ result.put((String)graph.getRelatedValue(input, l0.HasName), dependency);
+ }
+ }
+ return result;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ options = optionResources.keySet().toArray(new String[optionResources.keySet().size() + 1]);
+ options[optionResources.keySet().size()] = "";
+ ComboBoxCellEditor ceditor = new ComboBoxCellEditor(this.tableViewer.getTable(), options, SWT.READ_ONLY);
+ ceditor.setActivationStyle(1);
+ editor = ceditor;
+ break;
+ default:
+ editor = null;
+ }
+
+ return editor;
+ }
+
+ @Override
+ protected Object getValue(Object element) {
+ ReferenceRow referenceRow = (ReferenceRow) element;
+
+ switch (this.column) {
+ case 0:
+ return referenceRow.getName();
+ case 1:
+ String refersToName = referenceRow.getValue();
+ if (refersToName == null) return options.length - 1;
+ for(int i = 0; i < options.length ; i++) {
+ if(refersToName.equals(options[i])) return i;
+ }
+ return options[options.length - 1];
+ default:
+ break;
+ }
+ return null;
+ }
+
+ @Override
+ protected void setValue(Object element, Object value) {
+ ReferenceRow referenceRow = (ReferenceRow) element;
+ String valueString = String.valueOf(value);
+ switch (this.column) {
+ case 0:
+ break;
+ case 1:
+ referenceRow.setRefersTo(optionResources.get(options[Integer.parseInt(valueString)]));
+ break;
+ default:
+ break;
+ }
+
+ getViewer().update(element, null);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.modules;\r
-\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.model.modifiers.ModifierRule;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.representation.Variability;\r
-import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ParameterModifierRule implements ModifierRule {\r
-\r
- @Override\r
- public boolean isCompatible(Class<?> contentType) {\r
- return contentType.equals(Object.class);\r
- }\r
-\r
- @Override\r
- public Modifier getModifier(ReadGraph graph, Object content, String columnKey) throws DatabaseException {\r
- if(content instanceof ParameterNode && ColumnKeys.VALUE.equals(columnKey)) {\r
- final ParameterNode node = (ParameterNode) content;\r
- return new Modifier() {\r
-\r
- @Override\r
- public String getValue() {\r
- Read<String> request =\r
- new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- String parameterExpression = ModuleParameterOverrideUtils.getParameterExpressionOrOverride(\r
- graph, \r
- node.getParent(), \r
- node.getIndependentVariable());\r
-\r
- return parameterExpression != null ? parameterExpression : "";\r
- }\r
-\r
- };\r
- try {\r
- return SimanticsUI.getSession().syncRequest(request);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- return "";\r
- }\r
- }\r
-\r
- @Override\r
- public String isValid(String label) {\r
- if(label.isEmpty())\r
- return null;\r
- \r
- if(Variability.CONTINUOUS.equals(Variability.getVariability(node.getIndependentVariable(), label, false, node.getParentConfiguration()))) \r
- return "Not valid";\r
- else\r
- return null;\r
- }\r
-\r
- @Override\r
- public void modify(final String label) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 L0 = Layer0.getInstance(graph);\r
-\r
- // Remove possible old override\r
- for(Resource r : graph.syncRequest(new ObjectsWithType(node.getParent(), L0.ConsistsOf, sr.Module_ParameterOverride))) {\r
- if(node.getVariableResource().equals(graph.getPossibleObject(r, sr.Module_ParameterOverride_overriddenParameter))) {\r
- RemoverUtil.remove(graph, r);\r
- break;\r
- }\r
- }\r
-\r
- // Write the new override, if there is one\r
- if(label != null && !label.isEmpty()) {\r
- GraphUtils.create2(graph, sr.Module_ParameterOverride,\r
- sr.Module_ParameterOverride_overriddenParameter, node.getVariableResource(),\r
- sr.Module_ParameterOverride_overrideExpression, label,\r
- L0.PartOf, node.getParent()\r
- );\r
- }\r
- }\r
- });\r
- }\r
-\r
- };\r
- } else {\r
- return null;\r
- }\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.properties.widgets.modules;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.model.modifiers.ModifierRule;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.util.RemoverUtil;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.representation.Variability;
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;
+
+public class ParameterModifierRule implements ModifierRule {
+
+ @Override
+ public boolean isCompatible(Class<?> contentType) {
+ return contentType.equals(Object.class);
+ }
+
+ @Override
+ public Modifier getModifier(ReadGraph graph, Object content, String columnKey) throws DatabaseException {
+ if(content instanceof ParameterNode && ColumnKeys.VALUE.equals(columnKey)) {
+ final ParameterNode node = (ParameterNode) content;
+ return new Modifier() {
+
+ @Override
+ public String getValue() {
+ Read<String> request =
+ new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ String parameterExpression = ModuleParameterOverrideUtils.getParameterExpressionOrOverride(
+ graph,
+ node.getParent(),
+ node.getIndependentVariable());
+
+ return parameterExpression != null ? parameterExpression : "";
+ }
+
+ };
+ try {
+ return Simantics.getSession().syncRequest(request);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ return "";
+ }
+ }
+
+ @Override
+ public String isValid(String label) {
+ if(label.isEmpty())
+ return null;
+
+ if(Variability.CONTINUOUS.equals(Variability.getVariability(node.getIndependentVariable(), label, false, node.getParentConfiguration())))
+ return "Not valid";
+ else
+ return null;
+ }
+
+ @Override
+ public void modify(final String label) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 L0 = Layer0.getInstance(graph);
+
+ // Remove possible old override
+ for(Resource r : graph.syncRequest(new ObjectsWithType(node.getParent(), L0.ConsistsOf, sr.Module_ParameterOverride))) {
+ if(node.getVariableResource().equals(graph.getPossibleObject(r, sr.Module_ParameterOverride_overriddenParameter))) {
+ RemoverUtil.remove(graph, r);
+ break;
+ }
+ }
+
+ // Write the new override, if there is one
+ if(label != null && !label.isEmpty()) {
+ GraphUtils.create2(graph, sr.Module_ParameterOverride,
+ sr.Module_ParameterOverride_overriddenParameter, node.getVariableResource(),
+ sr.Module_ParameterOverride_overrideExpression, label,
+ L0.PartOf, node.getParent()
+ );
+ }
+ }
+ });
+ }
+
+ };
+ } else {
+ return null;
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.modules;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ReferenceRow {\r
-\r
- Resource variable, module, dependency;\r
- String name;\r
-\r
- public ReferenceRow(Resource module, Resource dependency, Resource variable) {\r
- this.module = module;\r
- this.variable = variable;\r
- this.dependency = dependency;\r
- }\r
-\r
-\r
- public Resource getModule() {\r
- return this.module;\r
- }\r
-\r
- public Resource getVariable() {\r
- return this.variable;\r
- }\r
-\r
- public Resource getDependency() {\r
- return this.dependency;\r
- }\r
-\r
- public String getName() {\r
- String name = null;\r
- try {\r
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- return (String)graph.getRelatedValue(getVariable(), Layer0.getInstance(graph).HasName);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return name;\r
- }\r
-\r
- public String getValue() {\r
- if(dependency == null) return "";\r
-\r
- String value = null;\r
- try {\r
- value = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource valueResource = graph.getPossibleObject(dependency, sr.Variable_HasTail);\r
- if(!graph.isInstanceOf(valueResource, sr.Variable))\r
- valueResource = graph.getPossibleObject(dependency, sr.Variable_HasHead);\r
- \r
- if(graph.isInstanceOf(valueResource, sr.Shadow))\r
- valueResource = graph.getPossibleObject(valueResource, sr.Shadow_original);\r
- \r
- if(valueResource == null || !graph.isInstanceOf(valueResource, sr.Variable))\r
- return "";\r
- \r
- return (String)graph.getRelatedValue(valueResource, l0.HasName, Bindings.STRING);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return value;\r
- }\r
-\r
- public void setRefersTo(final Resource dependency) {\r
- if(dependency != null && dependency.equals(this.dependency)) return;\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- if(getDependency() != null && graph.hasStatement(getDependency(), sr.Dependency_refersTo))\r
- graph.deny(getDependency(), sr.Dependency_refersTo);\r
- if(dependency != null && graph.hasStatement(dependency, sr.Dependency_refersTo))\r
- graph.deny(dependency, sr.Dependency_refersTo);\r
- setDependency(null);\r
- if(dependency != null) {\r
- setDependency(dependency);\r
- graph.claim(getDependency(), SysdynResource.getInstance(graph).Dependency_refersTo, getVariable());\r
- }\r
- }\r
- });\r
- }\r
-\r
- private void setDependency(Resource dependency) {\r
- this.dependency = dependency;\r
- }\r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.properties.widgets.modules;
+
+import org.simantics.Simantics;
+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.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+
+public class ReferenceRow {
+
+ Resource variable, module, dependency;
+ String name;
+
+ public ReferenceRow(Resource module, Resource dependency, Resource variable) {
+ this.module = module;
+ this.variable = variable;
+ this.dependency = dependency;
+ }
+
+
+ public Resource getModule() {
+ return this.module;
+ }
+
+ public Resource getVariable() {
+ return this.variable;
+ }
+
+ public Resource getDependency() {
+ return this.dependency;
+ }
+
+ public String getName() {
+ String name = null;
+ try {
+ name = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ return (String)graph.getRelatedValue(getVariable(), Layer0.getInstance(graph).HasName);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return name;
+ }
+
+ public String getValue() {
+ if(dependency == null) return "";
+
+ String value = null;
+ try {
+ value = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource valueResource = graph.getPossibleObject(dependency, sr.Variable_HasTail);
+ if(!graph.isInstanceOf(valueResource, sr.Variable))
+ valueResource = graph.getPossibleObject(dependency, sr.Variable_HasHead);
+
+ if(graph.isInstanceOf(valueResource, sr.Shadow))
+ valueResource = graph.getPossibleObject(valueResource, sr.Shadow_original);
+
+ if(valueResource == null || !graph.isInstanceOf(valueResource, sr.Variable))
+ return "";
+
+ return (String)graph.getRelatedValue(valueResource, l0.HasName, Bindings.STRING);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return value;
+ }
+
+ public void setRefersTo(final Resource dependency) {
+ if(dependency != null && dependency.equals(this.dependency)) return;
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ if(getDependency() != null && graph.hasStatement(getDependency(), sr.Dependency_refersTo))
+ graph.deny(getDependency(), sr.Dependency_refersTo);
+ if(dependency != null && graph.hasStatement(dependency, sr.Dependency_refersTo))
+ graph.deny(dependency, sr.Dependency_refersTo);
+ setDependency(null);
+ if(dependency != null) {
+ setDependency(dependency);
+ graph.claim(getDependency(), SysdynResource.getInstance(graph).Dependency_refersTo, getVariable());
+ }
+ }
+ });
+ }
+
+ private void setDependency(Resource dependency) {
+ this.dependency = dependency;
+ }
+}
+
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.modules;\r
-\r
-import java.util.ArrayList;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.IBaseLabelProvider;\r
-import org.eclipse.jface.viewers.IContentProvider;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.TableViewer;\r
-import org.eclipse.jface.viewers.Viewer;\r
-import org.eclipse.jface.viewers.ViewerComparator;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-\r
-public class ReferenceTable implements Widget{\r
-\r
- private TableViewer tableViewer;\r
- private RowProvider rowProvider;\r
-\r
- public static final String FIRSTCOLUMN = "Inputs";\r
- public static final String SECONDCOLUMN = "Outputs";\r
- \r
- public ReferenceTable(Composite parent, WidgetSupport support, int style) {\r
- support.register(this);\r
-\r
- Composite base = new Composite(parent, style);\r
- GridLayoutFactory.fillDefaults().applyTo(base);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(base);\r
-\r
- Table table = new Table(base, SWT.BORDER|SWT.SINGLE|SWT.FULL_SELECTION);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(table);\r
- table.setHeaderVisible (true);\r
- table.setLinesVisible(true);\r
- table.getVerticalBar().setVisible(true);\r
-\r
- tableViewer = new TableViewer (table);\r
- tableViewer.setComparator(new ReferenceRowComparator());\r
- }\r
-\r
- public TableViewer getTableViewer() {\r
- return this.tableViewer;\r
- }\r
-\r
- public void setRowProvider(RowProvider rowProvider) {\r
- this.rowProvider = rowProvider;\r
- }\r
- \r
- public void setContentProvider(IContentProvider provider) {\r
- tableViewer.setContentProvider(provider);\r
- }\r
- \r
- public void setLabelProvider(IBaseLabelProvider labelProvider) {\r
- tableViewer.setLabelProvider(labelProvider);\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- final Resource module = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);\r
- if(this.rowProvider != null) {\r
- try {\r
- SimanticsUI.getSession().syncRequest(new Read<ArrayList<ReferenceRow>>() {\r
-\r
- @Override\r
- public ArrayList<ReferenceRow> perform(ReadGraph graph) throws DatabaseException {\r
- return rowProvider.getRows(graph, module);\r
- }\r
- } , new Listener<ArrayList<ReferenceRow>>() {\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- if(tableViewer != null && tableViewer.getTable() != null)\r
- return getTableViewer().getTable().isDisposed();\r
- else\r
- return true;\r
- }\r
-\r
- @Override\r
- public void execute(final ArrayList<ReferenceRow> result) {\r
- if(!isDisposed())\r
- getTableViewer().getTable().getDisplay().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- if(!isDisposed())\r
- getTableViewer().setInput(result);\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- }\r
- }\r
- );\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- }\r
-\r
- private class ReferenceRowComparator extends ViewerComparator {\r
- @Override\r
- public int compare(Viewer viewer, Object e1, Object e2) {\r
- ReferenceRow rr1 = (ReferenceRow)e1;\r
- ReferenceRow rr2 = (ReferenceRow)e2;\r
- return rr1.getName().compareTo(rr2.getName());\r
- }\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 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.sysdyn.ui.properties.widgets.modules;
+
+import java.util.ArrayList;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.IBaseLabelProvider;
+import org.eclipse.jface.viewers.IContentProvider;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.jface.viewers.ViewerComparator;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Table;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.utils.ui.ISelectionUtils;
+
+public class ReferenceTable implements Widget{
+
+ private TableViewer tableViewer;
+ private RowProvider rowProvider;
+
+ public static final String FIRSTCOLUMN = "Inputs";
+ public static final String SECONDCOLUMN = "Outputs";
+
+ public ReferenceTable(Composite parent, WidgetSupport support, int style) {
+ support.register(this);
+
+ Composite base = new Composite(parent, style);
+ GridLayoutFactory.fillDefaults().applyTo(base);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(base);
+
+ Table table = new Table(base, SWT.BORDER|SWT.SINGLE|SWT.FULL_SELECTION);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(table);
+ table.setHeaderVisible (true);
+ table.setLinesVisible(true);
+ table.getVerticalBar().setVisible(true);
+
+ tableViewer = new TableViewer (table);
+ tableViewer.setComparator(new ReferenceRowComparator());
+ }
+
+ public TableViewer getTableViewer() {
+ return this.tableViewer;
+ }
+
+ public void setRowProvider(RowProvider rowProvider) {
+ this.rowProvider = rowProvider;
+ }
+
+ public void setContentProvider(IContentProvider provider) {
+ tableViewer.setContentProvider(provider);
+ }
+
+ public void setLabelProvider(IBaseLabelProvider labelProvider) {
+ tableViewer.setLabelProvider(labelProvider);
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ final Resource module = ISelectionUtils.filterSingleSelection((ISelection)input, Resource.class);
+ if(this.rowProvider != null) {
+ try {
+ Simantics.getSession().syncRequest(new Read<ArrayList<ReferenceRow>>() {
+
+ @Override
+ public ArrayList<ReferenceRow> perform(ReadGraph graph) throws DatabaseException {
+ return rowProvider.getRows(graph, module);
+ }
+ } , new Listener<ArrayList<ReferenceRow>>() {
+
+ @Override
+ public boolean isDisposed() {
+ if(tableViewer != null && tableViewer.getTable() != null)
+ return getTableViewer().getTable().isDisposed();
+ else
+ return true;
+ }
+
+ @Override
+ public void execute(final ArrayList<ReferenceRow> result) {
+ if(!isDisposed())
+ getTableViewer().getTable().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if(!isDisposed())
+ getTableViewer().setInput(result);
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ }
+ }
+ );
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private class ReferenceRowComparator extends ViewerComparator {
+ @Override
+ public int compare(Viewer viewer, Object e1, Object e2) {
+ ReferenceRow rr1 = (ReferenceRow)e1;
+ ReferenceRow rr2 = (ReferenceRow)e2;
+ return rr1.getName().compareTo(rr2.getName());
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties.widgets.sensitivity;\r
-\r
-import java.util.HashMap;\r
-\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.StructuredSelection;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class DistributionPropertyWidget extends Composite implements Widget {\r
- \r
- private IDistributionProperties distributionProperties = null;\r
- private WidgetSupportImpl distributionSupport = new WidgetSupportImpl();\r
- private HashMap<String, String> cache = new HashMap<String, String>();\r
- private Resource oldInput;\r
-\r
- public DistributionPropertyWidget(Composite parent, ISessionContext context, WidgetSupport support, int style) {\r
- super(parent, style);\r
- GridLayoutFactory.fillDefaults().applyTo(this);\r
- support.register(this);\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- if(resource == null)\r
- return;\r
-\r
- IDistributionProperties newProperties = null;\r
- Resource distribution = null;\r
- try {\r
- distribution = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- Resource distribution = graph.getPossibleObject(\r
- resource, \r
- SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_propabilityDistribution\r
- );\r
- \r
- return distribution;\r
- }\r
-\r
- });\r
- \r
- newProperties = SimanticsUI.getSession().syncRequest(new Read<IDistributionProperties>() {\r
-\r
- @Override\r
- public IDistributionProperties perform(ReadGraph graph) throws DatabaseException {\r
- Resource distribution = graph.getPossibleObject(\r
- resource, \r
- SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_propabilityDistribution\r
- );\r
- \r
- return graph.adapt(distribution, IDistributionProperties.class);\r
- }\r
-\r
- });\r
- \r
- // Create a PropertyComposite for the selected node\r
- if(newProperties != null) {\r
-\r
- if(distributionProperties != null)\r
- distributionProperties.getCachedValues(cache);\r
- \r
- if(oldInput != null && !oldInput.equals(resource))\r
- cache.clear();\r
- \r
- oldInput = resource;\r
- \r
- for(Control child : this.getChildren()) {\r
- child.dispose();\r
- }\r
- \r
- newProperties.createContent(this, context, distributionSupport);\r
- distributionProperties = newProperties;\r
- \r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- distributionProperties.applyCache(graph, cache);\r
- \r
- }\r
- });\r
- \r
- distributionSupport.fireInput(context, new StructuredSelection(distribution));\r
- }\r
- \r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.properties.widgets.sensitivity;
+
+import java.util.HashMap;
+
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class DistributionPropertyWidget extends Composite implements Widget {
+
+ private IDistributionProperties distributionProperties = null;
+ private WidgetSupportImpl distributionSupport = new WidgetSupportImpl();
+ private HashMap<String, String> cache = new HashMap<String, String>();
+ private Resource oldInput;
+
+ public DistributionPropertyWidget(Composite parent, ISessionContext context, WidgetSupport support, int style) {
+ super(parent, style);
+ GridLayoutFactory.fillDefaults().applyTo(this);
+ support.register(this);
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);
+ if(resource == null)
+ return;
+
+ IDistributionProperties newProperties = null;
+ Resource distribution = null;
+ try {
+ distribution = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ Resource distribution = graph.getPossibleObject(
+ resource,
+ SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_propabilityDistribution
+ );
+
+ return distribution;
+ }
+
+ });
+
+ newProperties = Simantics.getSession().syncRequest(new Read<IDistributionProperties>() {
+
+ @Override
+ public IDistributionProperties perform(ReadGraph graph) throws DatabaseException {
+ Resource distribution = graph.getPossibleObject(
+ resource,
+ SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_propabilityDistribution
+ );
+
+ return graph.adapt(distribution, IDistributionProperties.class);
+ }
+
+ });
+
+ // Create a PropertyComposite for the selected node
+ if(newProperties != null) {
+
+ if(distributionProperties != null)
+ distributionProperties.getCachedValues(cache);
+
+ if(oldInput != null && !oldInput.equals(resource))
+ cache.clear();
+
+ oldInput = resource;
+
+ for(Control child : this.getChildren()) {
+ child.dispose();
+ }
+
+ newProperties.createContent(this, context, distributionSupport);
+ distributionProperties = newProperties;
+
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ distributionProperties.applyCache(graph, cache);
+
+ }
+ });
+
+ distributionSupport.fireInput(context, new StructuredSelection(distribution));
+ }
+
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010, 2012, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.structure;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.CTabFolder;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.layout.RowLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Spinner;\r
-import org.simantics.db.Resource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class Dependencies extends StructureTabItem {\r
- \r
- private boolean isInverted = false;\r
- private Button bButton, fButton;\r
- private int levels = 3;\r
-\r
- private static int MAXLEVELS = 4;\r
- private static int MINLEVELS = 1;\r
-\r
- public Dependencies(CTabFolder parent, int style) {\r
- super(parent, style);\r
- \r
- Label line = new Label(structureComposite, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL);\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(line);\r
- \r
- Composite composite = new Composite(structureComposite, SWT.NONE);\r
- RowLayout layout = new RowLayout();\r
- layout.center = true;\r
- composite.setLayout(layout);\r
-\r
- Label label = new Label(composite, SWT.NONE);\r
- label.setText("Direction: ");\r
-\r
- bButton = new Button(composite, SWT.RADIO);\r
- bButton.setText("Backward");\r
- bButton.setSelection(true);\r
- bButton.addSelectionListener(new SelectionAdapter() {\r
- public void widgetSelected(SelectionEvent event) {\r
- if(bButton.getSelection())\r
- isInverted = false;\r
- else \r
- isInverted = true;\r
- if(currentSelection != null) {\r
- readGraph(currentSelection);\r
- }\r
- }\r
- });\r
-\r
- fButton = new Button(composite, SWT.RADIO);\r
- fButton.setText("Forward");\r
-\r
- label = new Label(composite, SWT.NONE);\r
- label.setText("Steps: ");\r
-\r
- Spinner spinner = new Spinner(composite, SWT.BORDER);\r
- spinner.setMaximum(MAXLEVELS);\r
- spinner.setMinimum(MINLEVELS);\r
- spinner.setTextLimit(1);\r
- spinner.setSelection(levels);\r
-\r
- spinner.addModifyListener(new ModifyListener() {\r
-\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- Spinner s = (Spinner)e.widget;\r
- int lvls = Integer.parseInt(s.getText());\r
- if(lvls > MAXLEVELS)\r
- levels = MAXLEVELS;\r
- else if (lvls < MINLEVELS)\r
- levels = MINLEVELS;\r
- levels = lvls;\r
- if(currentSelection != null) {\r
- readGraph(currentSelection);\r
- }\r
-\r
- }\r
- });\r
- \r
- this.setText("Dependencies");\r
- this.setControl(structureComposite);\r
- }\r
-\r
- protected void readGraph(Resource resource) {\r
- if(graphListener != null)\r
- graphListener.dispose();\r
- \r
- graphListener = new GraphListener();\r
- SimanticsUI.getSession().asyncRequest(new DependencyGraphRequest(\r
- resource, levels, isInverted), graphListener);\r
- }\r
-\r
- protected String getJobLabel() {\r
- return "Loading dependencies graph";\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2012, 2014 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.sysdyn.ui.structure;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CTabFolder;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Spinner;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+
+public class Dependencies extends StructureTabItem {
+
+ private boolean isInverted = false;
+ private Button bButton, fButton;
+ private int levels = 3;
+
+ private static int MAXLEVELS = 4;
+ private static int MINLEVELS = 1;
+
+ public Dependencies(CTabFolder parent, int style) {
+ super(parent, style);
+
+ Label line = new Label(structureComposite, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL);
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(line);
+
+ Composite composite = new Composite(structureComposite, SWT.NONE);
+ RowLayout layout = new RowLayout();
+ layout.center = true;
+ composite.setLayout(layout);
+
+ Label label = new Label(composite, SWT.NONE);
+ label.setText("Direction: ");
+
+ bButton = new Button(composite, SWT.RADIO);
+ bButton.setText("Backward");
+ bButton.setSelection(true);
+ bButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent event) {
+ if(bButton.getSelection())
+ isInverted = false;
+ else
+ isInverted = true;
+ if(currentSelection != null) {
+ readGraph(currentSelection);
+ }
+ }
+ });
+
+ fButton = new Button(composite, SWT.RADIO);
+ fButton.setText("Forward");
+
+ label = new Label(composite, SWT.NONE);
+ label.setText("Steps: ");
+
+ Spinner spinner = new Spinner(composite, SWT.BORDER);
+ spinner.setMaximum(MAXLEVELS);
+ spinner.setMinimum(MINLEVELS);
+ spinner.setTextLimit(1);
+ spinner.setSelection(levels);
+
+ spinner.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ Spinner s = (Spinner)e.widget;
+ int lvls = Integer.parseInt(s.getText());
+ if(lvls > MAXLEVELS)
+ levels = MAXLEVELS;
+ else if (lvls < MINLEVELS)
+ levels = MINLEVELS;
+ levels = lvls;
+ if(currentSelection != null) {
+ readGraph(currentSelection);
+ }
+
+ }
+ });
+
+ this.setText("Dependencies");
+ this.setControl(structureComposite);
+ }
+
+ protected void readGraph(Resource resource) {
+ if(graphListener != null)
+ graphListener.dispose();
+
+ graphListener = new GraphListener();
+ Simantics.getSession().asyncRequest(new DependencyGraphRequest(
+ resource, levels, isInverted), graphListener);
+ }
+
+ protected String getJobLabel() {
+ return "Loading dependencies graph";
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.structure;\r
-\r
-import org.eclipse.swt.custom.CTabFolder;\r
-import org.simantics.db.Resource;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Tab for loops.\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class Loops extends StructureTabItem {\r
-\r
- public Loops(CTabFolder parent, int style) {\r
- super(parent, style);\r
- this.setText("Loops");\r
- this.setControl(structureComposite);\r
- }\r
-\r
- protected void readGraph(Resource resource) {\r
- if(graphListener != null)\r
- graphListener.dispose();\r
- \r
- graphListener = new GraphListener();\r
- SimanticsUI.getSession().asyncRequest(new LoopGraphRequest(\r
- resource), graphListener);\r
- }\r
-\r
- protected String getJobLabel() {\r
- return "Loading loops graph";\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2014 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.sysdyn.ui.structure;
+
+import org.eclipse.swt.custom.CTabFolder;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+
+/**
+ * Tab for loops.
+ * @author Tuomas Miettinen
+ *
+ */
+public class Loops extends StructureTabItem {
+
+ public Loops(CTabFolder parent, int style) {
+ super(parent, style);
+ this.setText("Loops");
+ this.setControl(structureComposite);
+ }
+
+ protected void readGraph(Resource resource) {
+ if(graphListener != null)
+ graphListener.dispose();
+
+ graphListener = new GraphListener();
+ Simantics.getSession().asyncRequest(new LoopGraphRequest(
+ resource), graphListener);
+ }
+
+ protected String getJobLabel() {
+ return "Loading loops graph";
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.structure;\r
-\r
-import java.util.Set;\r
-\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.core.runtime.jobs.Job;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.CTabFolder;\r
-import org.eclipse.swt.custom.CTabItem;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.graphviz.Graph;\r
-import org.simantics.graphviz.ui.GraphvizComponent;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.RunnableWithObject;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-\r
-/**\r
- * Tab for displaying hierarchical model structure\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ModuleStructure extends CTabItem {\r
-\r
- private GraphvizComponent component;\r
- private GraphListener graphListener;\r
-\r
- \r
- public ModuleStructure(CTabFolder parent, int style) {\r
- super(parent, style);\r
- \r
- Composite moduleStructure = new Composite(parent, SWT.NONE);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(moduleStructure);\r
- GridLayoutFactory.fillDefaults().applyTo(moduleStructure);\r
-\r
- component = new GraphvizComponent(moduleStructure, SWT.NONE);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(component);\r
- \r
- this.setText("Model Hierarchy");\r
- this.setControl(moduleStructure);\r
-\r
- }\r
-\r
- /**\r
- * Draw a graph about the model of the selected resource\r
- * @param selection\r
- */\r
- public void drawSelection(ISelection selection) {\r
- if(selection == null || selection.isEmpty())\r
- return;\r
-\r
- if(selection instanceof IStructuredSelection) { \r
- Object[] els = ((IStructuredSelection) selection).toArray();\r
- if(els.length == 1) {\r
- Set<Resource> ress = ISelectionUtils.filterSetSelection(selection, Resource.class);\r
- if(ress.isEmpty()) return;\r
- Resource r = (ress.toArray(Resource.NONE))[0];\r
- if(r != null) {\r
- // Read graph for the resource\r
- if(graphListener != null)\r
- graphListener.dispose(); // Dispose possible previous listener\r
- \r
- graphListener = new GraphListener();\r
- SimanticsUI.getSession().asyncRequest(new ModuleStructureGraphRequest(r), graphListener);\r
- }\r
- }\r
- } \r
- }\r
- \r
- /**\r
- * Listener for updating hierarchical model graph\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class GraphListener implements Listener<Graph> {\r
- private boolean disposed = false;\r
- \r
- public void dispose() {\r
- disposed = true;\r
- }\r
- \r
- @Override\r
- public void exception(Throwable e) {\r
- e.printStackTrace();\r
- }\r
-\r
- @Override\r
- public void execute(final Graph graph) {\r
- Job job = new Job("Loading model structure graph") {\r
-\r
- @Override\r
- protected IStatus run(IProgressMonitor monitor) {\r
- if(!isDisposed()) {\r
- component.getDisplay().asyncExec(new RunnableWithObject(graph) {\r
- \r
- @Override\r
- public void run() {\r
- if (component.isDisposed()) return;\r
- component.setGraph((Graph)getObject(), "dot");\r
- component.fit(); \r
- }\r
- });\r
- \r
- }\r
- return Status.OK_STATUS;\r
- }\r
- };\r
- job.schedule();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * 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.sysdyn.ui.structure;
+
+import java.util.Set;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.CTabFolder;
+import org.eclipse.swt.custom.CTabItem;
+import org.eclipse.swt.widgets.Composite;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.procedure.Listener;
+import org.simantics.graphviz.Graph;
+import org.simantics.graphviz.ui.GraphvizComponent;
+import org.simantics.utils.RunnableWithObject;
+import org.simantics.utils.ui.ISelectionUtils;
+
+/**
+ * Tab for displaying hierarchical model structure
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ModuleStructure extends CTabItem {
+
+ private GraphvizComponent component;
+ private GraphListener graphListener;
+
+
+ public ModuleStructure(CTabFolder parent, int style) {
+ super(parent, style);
+
+ Composite moduleStructure = new Composite(parent, SWT.NONE);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(moduleStructure);
+ GridLayoutFactory.fillDefaults().applyTo(moduleStructure);
+
+ component = new GraphvizComponent(moduleStructure, SWT.NONE);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(component);
+
+ this.setText("Model Hierarchy");
+ this.setControl(moduleStructure);
+
+ }
+
+ /**
+ * Draw a graph about the model of the selected resource
+ * @param selection
+ */
+ public void drawSelection(ISelection selection) {
+ if(selection == null || selection.isEmpty())
+ return;
+
+ if(selection instanceof IStructuredSelection) {
+ Object[] els = ((IStructuredSelection) selection).toArray();
+ if(els.length == 1) {
+ Set<Resource> ress = ISelectionUtils.filterSetSelection(selection, Resource.class);
+ if(ress.isEmpty()) return;
+ Resource r = (ress.toArray(Resource.NONE))[0];
+ if(r != null) {
+ // Read graph for the resource
+ if(graphListener != null)
+ graphListener.dispose(); // Dispose possible previous listener
+
+ graphListener = new GraphListener();
+ Simantics.getSession().asyncRequest(new ModuleStructureGraphRequest(r), graphListener);
+ }
+ }
+ }
+ }
+
+ /**
+ * Listener for updating hierarchical model graph
+ * @author Teemu Lempinen
+ *
+ */
+ private class GraphListener implements Listener<Graph> {
+ private boolean disposed = false;
+
+ public void dispose() {
+ disposed = true;
+ }
+
+ @Override
+ public void exception(Throwable e) {
+ e.printStackTrace();
+ }
+
+ @Override
+ public void execute(final Graph graph) {
+ Job job = new Job("Loading model structure graph") {
+
+ @Override
+ protected IStatus run(IProgressMonitor monitor) {
+ if(!isDisposed()) {
+ component.getDisplay().asyncExec(new RunnableWithObject(graph) {
+
+ @Override
+ public void run() {
+ if (component.isDisposed()) return;
+ component.setGraph((Graph)getObject(), "dot");
+ component.fit();
+ }
+ });
+
+ }
+ return Status.OK_STATUS;
+ }
+ };
+ job.schedule();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+ }
+}
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.List;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.properties.ChartVariable;\r
-import org.simantics.jfreechart.chart.properties.IAllVariablesOfModel;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.strings.AlphanumComparator;\r
-import org.simantics.sysdyn.manager.SysdynModel;\r
-import org.simantics.sysdyn.manager.SysdynModelManager;\r
-import org.simantics.sysdyn.representation.IElement;\r
-import org.simantics.sysdyn.representation.IndependentVariable;\r
-import org.simantics.sysdyn.representation.Variability;\r
-\r
-/**\r
- * Request for getting all variables of a model in a String array. Includes also \r
- * variables inside modules.\r
- * \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class AllParametersOfModel implements IAllVariablesOfModel {\r
- \r
- protected final Resource model;\r
- \r
- public AllParametersOfModel(Resource model) {\r
- this.model = model;\r
- }\r
-\r
- @Override\r
- public Read<Collection<ChartVariable>> getVariablesQuery() {\r
- return new VariableQuery();\r
- } \r
- \r
- \r
- private class VariableQuery implements Read<Collection<ChartVariable>> {\r
- @Override\r
- public Collection<ChartVariable> perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SimulationResource simu = SimulationResource.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- \r
- List<ChartVariable> result = new ArrayList<ChartVariable>();\r
- // Find the model of this resource\r
- Resource model = AllParametersOfModel.this.model;\r
- while(model != null && !graph.isInstanceOf(model, sr.SysdynModel))\r
- model = graph.getPossibleObject(model, l0.PartOf);\r
- \r
- if(model == null)\r
- return result;\r
- \r
- // Find the models configuration\r
- Resource conf = graph.getSingleObject(model, simu.HasConfiguration);\r
- \r
- // Recursively read all configurations and add items\r
- ReadConfiguration(graph, conf, "", result);\r
- \r
- // Finally sort the results\r
- Collections.sort(result, AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
- return result;\r
- }\r
- }\r
- \r
- \r
- \r
- /**\r
- * Read components in a configuration and recursively all module configurations\r
- * \r
- * @param graph ReadGraph\r
- * @param configuration Resource to be read\r
- * @param path Current path from base realization\r
- * @param items Found variables\r
- * @throws DatabaseException\r
- */\r
- private void ReadConfiguration(ReadGraph graph, Resource configuration, String path, Collection<ChartVariable> items) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
-\r
- SysdynModelManager sdm = SysdynModelManager.getInstance(SimanticsUI.getSession());\r
- SysdynModel sm = sdm.getModel(graph, configuration);\r
- try {\r
- sm.update(graph);\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- \r
- String name;\r
- for(Resource resource : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.IndependentVariable))) {\r
- name = path + NameUtils.getSafeName(graph, resource);\r
- IElement element = sm.getElement(resource);\r
- if (element instanceof IndependentVariable) {\r
- IndependentVariable variable = (IndependentVariable)element; \r
- Variability variability = Variability.getVariability(variable, false, null);\r
- if (variability == Variability.PARAMETER) {\r
- items.add(new ChartVariable(name, name));\r
- }\r
- }\r
- }\r
- \r
- for(Resource module : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {\r
- Resource instanceOf = graph.getPossibleObject(module, l0.InstanceOf);\r
- Resource conf = graph.getPossibleObject(instanceOf, sr2.IsDefinedBy);\r
- if(conf != null) {\r
- String p = path + NameUtils.getSafeName(graph, module) + ".";\r
- ReadConfiguration(graph, conf, p, items);\r
- }\r
- }\r
- }\r
- \r
- @Override\r
- public String getVariablesLabel(ReadGraph graph, String variableId)\r
- throws DatabaseException {\r
- return variableId.substring(1).replace('/', '.');\r
- }\r
-\r
-}\r
-\r
+package org.simantics.sysdyn.ui.trend;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.properties.ChartVariable;
+import org.simantics.jfreechart.chart.properties.IAllVariablesOfModel;
+import org.simantics.layer0.Layer0;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.structural.stubs.StructuralResource2;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynModel;
+import org.simantics.sysdyn.manager.SysdynModelManager;
+import org.simantics.sysdyn.representation.IElement;
+import org.simantics.sysdyn.representation.IndependentVariable;
+import org.simantics.sysdyn.representation.Variability;
+import org.simantics.utils.strings.AlphanumComparator;
+
+/**
+ * Request for getting all variables of a model in a String array. Includes also
+ * variables inside modules.
+ *
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class AllParametersOfModel implements IAllVariablesOfModel {
+
+ protected final Resource model;
+
+ public AllParametersOfModel(Resource model) {
+ this.model = model;
+ }
+
+ @Override
+ public Read<Collection<ChartVariable>> getVariablesQuery() {
+ return new VariableQuery();
+ }
+
+
+ private class VariableQuery implements Read<Collection<ChartVariable>> {
+ @Override
+ public Collection<ChartVariable> perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SimulationResource simu = SimulationResource.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ List<ChartVariable> result = new ArrayList<ChartVariable>();
+ // Find the model of this resource
+ Resource model = AllParametersOfModel.this.model;
+ while(model != null && !graph.isInstanceOf(model, sr.SysdynModel))
+ model = graph.getPossibleObject(model, l0.PartOf);
+
+ if(model == null)
+ return result;
+
+ // Find the models configuration
+ Resource conf = graph.getSingleObject(model, simu.HasConfiguration);
+
+ // Recursively read all configurations and add items
+ ReadConfiguration(graph, conf, "", result);
+
+ // Finally sort the results
+ Collections.sort(result, AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);
+ return result;
+ }
+ }
+
+
+
+ /**
+ * Read components in a configuration and recursively all module configurations
+ *
+ * @param graph ReadGraph
+ * @param configuration Resource to be read
+ * @param path Current path from base realization
+ * @param items Found variables
+ * @throws DatabaseException
+ */
+ private void ReadConfiguration(ReadGraph graph, Resource configuration, String path, Collection<ChartVariable> items) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+
+ SysdynModelManager sdm = SysdynModelManager.getInstance(Simantics.getSession());
+ SysdynModel sm = sdm.getModel(graph, configuration);
+ try {
+ sm.update(graph);
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+
+ String name;
+ for(Resource resource : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.IndependentVariable))) {
+ name = path + NameUtils.getSafeName(graph, resource);
+ IElement element = sm.getElement(resource);
+ if (element instanceof IndependentVariable) {
+ IndependentVariable variable = (IndependentVariable)element;
+ Variability variability = Variability.getVariability(variable, false, null);
+ if (variability == Variability.PARAMETER) {
+ items.add(new ChartVariable(name, name));
+ }
+ }
+ }
+
+ for(Resource module : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {
+ Resource instanceOf = graph.getPossibleObject(module, l0.InstanceOf);
+ Resource conf = graph.getPossibleObject(instanceOf, sr2.IsDefinedBy);
+ if(conf != null) {
+ String p = path + NameUtils.getSafeName(graph, module) + ".";
+ ReadConfiguration(graph, conf, p, items);
+ }
+ }
+ }
+
+ @Override
+ public String getVariablesLabel(ReadGraph graph, String variableId)
+ throws DatabaseException {
+ return variableId.substring(1).replace('/', '.');
+ }
+
+}
+
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import javax.swing.SwingUtilities;\r
-\r
-import org.jfree.chart.plot.DefaultDrawingSupplier;\r
-import org.jfree.chart.renderer.AbstractRenderer;\r
-import org.jfree.chart.renderer.category.BarRenderer;\r
-import org.jfree.data.category.DefaultCategoryDataset;\r
-import org.jfree.data.general.Dataset;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.exception.MissingVariableException;\r
-import org.simantics.db.layer0.request.PossibleActiveExperiment;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.AbstractDataset;\r
-import org.simantics.jfreechart.chart.IRenderer;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.sysdyn.Functions;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.adapter.VariableRVIUtils;\r
-import org.simantics.sysdyn.manager.SysdynDataSet;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Class representing a JFreeChart.CategoryDataset\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class CategoryDataset extends AbstractDataset implements org.simantics.jfreechart.chart.CategoryDataset{\r
-\r
- private List<Resource> seriesList;\r
- private String realizationURI;\r
- private IRenderer renderer;\r
- private DefaultCategoryDataset dataset;\r
-\r
- public CategoryDataset(ReadGraph graph, Resource resource) throws DatabaseException {\r
- super(graph, resource);\r
-\r
- \r
- Layer0 l0 = Layer0.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- // Find the model where the chart is located\r
- Resource model = resource;\r
- do {\r
- model = graph.getPossibleObject(model, l0.PartOf);\r
- } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));\r
-\r
- // Find the variable realization of the current experiment\r
- realizationURI = null;\r
- Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));\r
- if (realization == null) {\r
- Layer0X L0X = Layer0X.getInstance(graph);\r
- realization = graph.getPossibleObject(model, L0X.HasBaseRealization);\r
- }\r
- if (realization != null)\r
- realizationURI = graph.getURI(realization);\r
-\r
- if(realizationURI == null)\r
- return; // No experiment -> No results\r
-\r
- Resource seriesList = graph.getPossibleObject(resource, jfree.Dataset_seriesList);\r
- if(seriesList != null)\r
- this.seriesList = ListUtils.toList(graph, seriesList);\r
-\r
- Resource rendererResource = graph.getPossibleObject(resource, jfree.Dataset_renderer);\r
- renderer = graph.adapt(rendererResource, IRenderer.class);\r
-\r
- \r
- }\r
-\r
- private DatasetListener listener;\r
-\r
- @Override\r
- public Dataset getDataset() {\r
-\r
- if(seriesList == null || seriesList.isEmpty() || SimanticsUI.getSession() == null)\r
- return null;\r
-\r
- if(dataset == null) {\r
- dataset = new DefaultCategoryDataset();\r
- }\r
-\r
- if(listener == null || listener.isDisposed()) {\r
- listener = new DatasetListener();\r
- SimanticsUI.getSession().asyncRequest(new Read<ArrayList<TempSeries>>() {\r
-\r
- @Override\r
- public ArrayList<TempSeries> perform(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- ArrayList<TempSeries> series = new ArrayList<TempSeries>();\r
- // Get properties for all series\r
- if(seriesList != null) {\r
- for(Resource r : seriesList) {\r
- String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);\r
- if(rvi == null)\r
- continue;\r
-\r
- try {\r
- // Get a variable for the series\r
- Variable v = Variables.getVariable(graph, realizationURI + rvi);\r
- // Get values\r
- Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
- if(dsVariable == null)\r
- return series;\r
- \r
- Object object = dsVariable.getValue(graph);\r
- \r
- if(object == null || !(object instanceof ArrayList<?>))\r
- return series;\r
-\r
- ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
-\r
- for(Object o : (ArrayList<?>)object) {\r
- if(o instanceof SysdynDataSet)\r
- datasets.add((SysdynDataSet)o);\r
- }\r
-\r
- String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter);\r
- if(filter != null) {\r
- ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);\r
- if(result2 != null) {\r
- datasets = result2;\r
- }\r
- }\r
-\r
- // Find if a specific time is set for this chart\r
- Double chartTime = null;\r
- if(!datasets.isEmpty()) {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource datasetResource = graph.getPossibleObject(r, l0.PartOf);\r
- if(datasetResource != null) {\r
- Resource plot = graph.getPossibleObject(datasetResource, l0.PartOf);\r
- if(plot != null) {\r
- Resource chart = graph.getPossibleObject(plot, l0.PartOf);\r
- if(chart != null)\r
- chartTime = graph.getPossibleRelatedValue(chart, jfree.Chart_time);\r
- }\r
- }\r
- }\r
-\r
- for(SysdynDataSet dataset : datasets) {\r
- double[] va = dataset.values;\r
-\r
-\r
- if(va == null || va.length == 0)\r
- continue;\r
-\r
- /*\r
- * Time\r
- * \r
- * 1. find time for the individual series.\r
- * 2. find time for the whole chart\r
- * 3. find simulation time\r
- */\r
- Double time = graph.getPossibleRelatedValue(r, jfree.Series_time, Bindings.DOUBLE);\r
- if(time == null)\r
- time = chartTime;\r
- if(time == null) {\r
- // Get a variable for the experiment run\r
- Variable run = Variables.getVariable(graph, realizationURI);\r
- if(run == null)\r
- return null;\r
- Variable timeVar = run.browsePossible(graph, "#" + Functions.TIME + "#");\r
- if(timeVar != null)\r
- time = timeVar.getValue(graph, Bindings.DOUBLE);\r
- \r
- }\r
-\r
- // Value\r
- Double value = null;\r
- if(time == null) {\r
- value = va[va.length - 1];\r
- } else {\r
- double[] ta = dataset.times;\r
- for(int i = 0; i < ta.length; i++) {\r
- double t = ta[i];\r
- if(time <= t) {\r
- value = va[i]; \r
- break;\r
- }\r
- }\r
-\r
- if(value == null)\r
- value = va[va.length - 1];\r
- }\r
- String label = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasLabel); // Called to refresh paints when label changes\r
- String name = label == null || label.isEmpty() ? dataset.name : label;\r
- if (dataset.resultIndex != null) {\r
- name += "(" + dataset.resultIndex + ")"; \r
- }\r
- series.add(new TempSeries(name, dataset.result, value));\r
- }\r
- } catch (MissingVariableException e) {\r
- // Do nothing, if variable was not found. Move on to the next series\r
- }\r
- }\r
- }\r
- return series;\r
- }\r
-\r
- }, listener);\r
- }\r
- return dataset;\r
- }\r
-\r
- @Override\r
- public AbstractRenderer getRenderer() {\r
- return renderer.getRenderer();\r
- }\r
-\r
- private class DatasetListener implements Listener<ArrayList<TempSeries>> {\r
- private boolean disposed = false;\r
-\r
- public void dispose() {\r
- disposed = true;\r
- }\r
-\r
- @Override\r
- public void execute(final ArrayList<TempSeries> series) {\r
- // Modify series in AWT thread to avoid synchronization problems\r
- SwingUtilities.invokeLater(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- // Remove all unused series\r
- dataset.clear();\r
- BarRenderer renderer = ((BarRenderer)getRenderer());\r
- renderer.getPlot().setDrawingSupplier(new DefaultDrawingSupplier());\r
-\r
- // Add found series\r
- for(int i = 0; i < series.size(); i++) {\r
- TempSeries s = series.get(i);\r
- if(renderer instanceof org.jfree.chart.renderer.category.StackedBarRenderer && s.name.contains("[")) {\r
- String category = s.name.substring(0, s.name.indexOf('['));\r
- if(s.result != null)\r
- category = category + " : " + s.result;\r
- String series = s.name.substring(s.name.indexOf('['));\r
- dataset.addValue(s.value, series, category);\r
- } else {\r
- dataset.addValue(s.value, s.result == null ? "Current" : s.result, s.name);\r
- }\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
- };\r
-\r
- @Override\r
- public void dispose() {\r
- super.dispose();\r
- if(listener != null) {\r
- listener.dispose();\r
- listener = null;\r
- }\r
- }\r
-\r
- /**\r
- * Auxiliary class containing all information needed to define a single series\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class TempSeries {\r
- public String name;\r
- public String result;\r
- public Double value;\r
-\r
- public TempSeries(String name, String result, Double value) {\r
- this.name = name;\r
- this.value = value;\r
- this.result = result;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return "TempSeries: " + name + ", " + value + ", " + result;\r
- }\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.trend;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.SwingUtilities;
+
+import org.jfree.chart.plot.DefaultDrawingSupplier;
+import org.jfree.chart.renderer.AbstractRenderer;
+import org.jfree.chart.renderer.category.BarRenderer;
+import org.jfree.data.category.DefaultCategoryDataset;
+import org.jfree.data.general.Dataset;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.exception.MissingVariableException;
+import org.simantics.db.layer0.request.PossibleActiveExperiment;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.AbstractDataset;
+import org.simantics.jfreechart.chart.IRenderer;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.operation.Layer0X;
+import org.simantics.sysdyn.Functions;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.adapter.VariableRVIUtils;
+import org.simantics.sysdyn.manager.SysdynDataSet;
+
+/**
+ * Class representing a JFreeChart.CategoryDataset
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class CategoryDataset extends AbstractDataset implements org.simantics.jfreechart.chart.CategoryDataset{
+
+ private List<Resource> seriesList;
+ private String realizationURI;
+ private IRenderer renderer;
+ private DefaultCategoryDataset dataset;
+
+ public CategoryDataset(ReadGraph graph, Resource resource) throws DatabaseException {
+ super(graph, resource);
+
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ // Find the model where the chart is located
+ Resource model = resource;
+ do {
+ model = graph.getPossibleObject(model, l0.PartOf);
+ } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));
+
+ // Find the variable realization of the current experiment
+ realizationURI = null;
+ Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));
+ if (realization == null) {
+ Layer0X L0X = Layer0X.getInstance(graph);
+ realization = graph.getPossibleObject(model, L0X.HasBaseRealization);
+ }
+ if (realization != null)
+ realizationURI = graph.getURI(realization);
+
+ if(realizationURI == null)
+ return; // No experiment -> No results
+
+ Resource seriesList = graph.getPossibleObject(resource, jfree.Dataset_seriesList);
+ if(seriesList != null)
+ this.seriesList = ListUtils.toList(graph, seriesList);
+
+ Resource rendererResource = graph.getPossibleObject(resource, jfree.Dataset_renderer);
+ renderer = graph.adapt(rendererResource, IRenderer.class);
+
+
+ }
+
+ private DatasetListener listener;
+
+ @Override
+ public Dataset getDataset() {
+
+ if(seriesList == null || seriesList.isEmpty() || Simantics.getSession() == null)
+ return null;
+
+ if(dataset == null) {
+ dataset = new DefaultCategoryDataset();
+ }
+
+ if(listener == null || listener.isDisposed()) {
+ listener = new DatasetListener();
+ Simantics.getSession().asyncRequest(new Read<ArrayList<TempSeries>>() {
+
+ @Override
+ public ArrayList<TempSeries> perform(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ ArrayList<TempSeries> series = new ArrayList<TempSeries>();
+ // Get properties for all series
+ if(seriesList != null) {
+ for(Resource r : seriesList) {
+ String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);
+ if(rvi == null)
+ continue;
+
+ try {
+ // Get a variable for the series
+ Variable v = Variables.getVariable(graph, realizationURI + rvi);
+ // Get values
+ Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");
+ if(dsVariable == null)
+ return series;
+
+ Object object = dsVariable.getValue(graph);
+
+ if(object == null || !(object instanceof ArrayList<?>))
+ return series;
+
+ ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();
+
+ for(Object o : (ArrayList<?>)object) {
+ if(o instanceof SysdynDataSet)
+ datasets.add((SysdynDataSet)o);
+ }
+
+ String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter);
+ if(filter != null) {
+ ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);
+ if(result2 != null) {
+ datasets = result2;
+ }
+ }
+
+ // Find if a specific time is set for this chart
+ Double chartTime = null;
+ if(!datasets.isEmpty()) {
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource datasetResource = graph.getPossibleObject(r, l0.PartOf);
+ if(datasetResource != null) {
+ Resource plot = graph.getPossibleObject(datasetResource, l0.PartOf);
+ if(plot != null) {
+ Resource chart = graph.getPossibleObject(plot, l0.PartOf);
+ if(chart != null)
+ chartTime = graph.getPossibleRelatedValue(chart, jfree.Chart_time);
+ }
+ }
+ }
+
+ for(SysdynDataSet dataset : datasets) {
+ double[] va = dataset.values;
+
+
+ if(va == null || va.length == 0)
+ continue;
+
+ /*
+ * Time
+ *
+ * 1. find time for the individual series.
+ * 2. find time for the whole chart
+ * 3. find simulation time
+ */
+ Double time = graph.getPossibleRelatedValue(r, jfree.Series_time, Bindings.DOUBLE);
+ if(time == null)
+ time = chartTime;
+ if(time == null) {
+ // Get a variable for the experiment run
+ Variable run = Variables.getVariable(graph, realizationURI);
+ if(run == null)
+ return null;
+ Variable timeVar = run.browsePossible(graph, "#" + Functions.TIME + "#");
+ if(timeVar != null)
+ time = timeVar.getValue(graph, Bindings.DOUBLE);
+
+ }
+
+ // Value
+ Double value = null;
+ if(time == null) {
+ value = va[va.length - 1];
+ } else {
+ double[] ta = dataset.times;
+ for(int i = 0; i < ta.length; i++) {
+ double t = ta[i];
+ if(time <= t) {
+ value = va[i];
+ break;
+ }
+ }
+
+ if(value == null)
+ value = va[va.length - 1];
+ }
+ String label = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasLabel); // Called to refresh paints when label changes
+ String name = label == null || label.isEmpty() ? dataset.name : label;
+ if (dataset.resultIndex != null) {
+ name += "(" + dataset.resultIndex + ")";
+ }
+ series.add(new TempSeries(name, dataset.result, value));
+ }
+ } catch (MissingVariableException e) {
+ // Do nothing, if variable was not found. Move on to the next series
+ }
+ }
+ }
+ return series;
+ }
+
+ }, listener);
+ }
+ return dataset;
+ }
+
+ @Override
+ public AbstractRenderer getRenderer() {
+ return renderer.getRenderer();
+ }
+
+ private class DatasetListener implements Listener<ArrayList<TempSeries>> {
+ private boolean disposed = false;
+
+ public void dispose() {
+ disposed = true;
+ }
+
+ @Override
+ public void execute(final ArrayList<TempSeries> series) {
+ // Modify series in AWT thread to avoid synchronization problems
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run() {
+ // Remove all unused series
+ dataset.clear();
+ BarRenderer renderer = ((BarRenderer)getRenderer());
+ renderer.getPlot().setDrawingSupplier(new DefaultDrawingSupplier());
+
+ // Add found series
+ for(int i = 0; i < series.size(); i++) {
+ TempSeries s = series.get(i);
+ if(renderer instanceof org.jfree.chart.renderer.category.StackedBarRenderer && s.name.contains("[")) {
+ String category = s.name.substring(0, s.name.indexOf('['));
+ if(s.result != null)
+ category = category + " : " + s.result;
+ String series = s.name.substring(s.name.indexOf('['));
+ dataset.addValue(s.value, series, category);
+ } else {
+ dataset.addValue(s.value, s.result == null ? "Current" : s.result, s.name);
+ }
+ }
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+ };
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ if(listener != null) {
+ listener.dispose();
+ listener = null;
+ }
+ }
+
+ /**
+ * Auxiliary class containing all information needed to define a single series
+ * @author Teemu Lempinen
+ *
+ */
+ private class TempSeries {
+ public String name;
+ public String result;
+ public Double value;
+
+ public TempSeries(String name, String result, Double value) {
+ this.name = name;
+ this.value = value;
+ this.result = result;
+ }
+
+ @Override
+ public String toString() {
+ return "TempSeries: " + name + ", " + value + ", " + result;
+ }
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import java.util.List;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.StructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.properties.ColorPicker;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;\r
-import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-import org.simantics.utils.ui.validators.DoubleValidator;\r
-\r
-/**\r
- * Widget for setting percentage and color for a confidence bound\r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class ConfidenceBoundWidget extends Composite implements Widget {\r
-\r
- private WidgetSupportImpl confidenceBoundSupport;\r
- private int index;\r
- \r
- public ConfidenceBoundWidget(Composite parent, ISessionContext context, WidgetSupport support, int style, int index) {\r
- super(parent, style);\r
- this.index = index;\r
- \r
- support.register(this);\r
- \r
- GridLayoutFactory.fillDefaults().applyTo(this);\r
- \r
- confidenceBoundSupport = new WidgetSupportImpl();\r
- \r
- ColorPicker colorPicker = new ColorPicker(this, context, confidenceBoundSupport, SWT.NONE, false) {\r
- @Override\r
- protected Resource getColorRelation(ReadGraph graph) throws DatabaseException {\r
- return SysdynResource.getInstance(graph).Charts_SensitivityDataset_ConfidenceBound_color;\r
- }\r
- };\r
- GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BEGINNING).applyTo(colorPicker);\r
- \r
- TrackedText variable = new TrackedText(this, confidenceBoundSupport, SWT.BORDER);\r
- variable.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.Charts_SensitivityDataset_ConfidenceBound_percent));\r
- variable.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.Charts_SensitivityDataset_ConfidenceBound_percent));\r
- variable.setColorProvider(new SysdynBasicColorProvider(variable.getResourceManager()));\r
- variable.setInputValidator(new DoubleValidator() {\r
- public String isValid(String newText) {\r
- if(newText == null || newText.isEmpty())\r
- return null;\r
- else\r
- return super.isValid(newText);\r
- }\r
-\r
- });\r
- GridDataFactory.fillDefaults().hint(27, SWT.DEFAULT).align(SWT.CENTER, SWT.CENTER).applyTo(variable.getWidget());\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- try {\r
- Resource confidenceBound = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- return getResource(graph, resource);\r
- }\r
- \r
- });\r
- \r
- if(confidenceBound != null)\r
- confidenceBoundSupport.fireInput(context, new StructuredSelection(confidenceBound));\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- private Resource getResource(ReadGraph graph, Resource input) throws DatabaseException {\r
- Resource dataset = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- Resource confidenceBoundsList = graph.getPossibleObject(dataset, SR.Charts_SensitivityDataset_confidenceBounds);\r
- if(confidenceBoundsList == null)\r
- return null;\r
- List<Resource> confidenceBounds = ListUtils.toList(graph, confidenceBoundsList);\r
- return confidenceBounds.get(index);\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.trend;
+
+import java.util.List;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.TrackedText;
+import org.simantics.browsing.ui.swt.widgets.impl.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.properties.ColorPicker;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.properties.SysdynBasicColorProvider;
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyFactory;
+import org.simantics.sysdyn.ui.properties.widgets.factories.DoublePropertyModifier;
+import org.simantics.utils.ui.AdaptionUtils;
+import org.simantics.utils.ui.validators.DoubleValidator;
+
+/**
+ * Widget for setting percentage and color for a confidence bound
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class ConfidenceBoundWidget extends Composite implements Widget {
+
+ private WidgetSupportImpl confidenceBoundSupport;
+ private int index;
+
+ public ConfidenceBoundWidget(Composite parent, ISessionContext context, WidgetSupport support, int style, int index) {
+ super(parent, style);
+ this.index = index;
+
+ support.register(this);
+
+ GridLayoutFactory.fillDefaults().applyTo(this);
+
+ confidenceBoundSupport = new WidgetSupportImpl();
+
+ ColorPicker colorPicker = new ColorPicker(this, context, confidenceBoundSupport, SWT.NONE, false) {
+ @Override
+ protected Resource getColorRelation(ReadGraph graph) throws DatabaseException {
+ return SysdynResource.getInstance(graph).Charts_SensitivityDataset_ConfidenceBound_color;
+ }
+ };
+ GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.BEGINNING).applyTo(colorPicker);
+
+ TrackedText variable = new TrackedText(this, confidenceBoundSupport, SWT.BORDER);
+ variable.setTextFactory(new DoublePropertyFactory(SysdynResource.URIs.Charts_SensitivityDataset_ConfidenceBound_percent));
+ variable.addModifyListener(new DoublePropertyModifier(context, SysdynResource.URIs.Charts_SensitivityDataset_ConfidenceBound_percent));
+ variable.setColorProvider(new SysdynBasicColorProvider(variable.getResourceManager()));
+ variable.setInputValidator(new DoubleValidator() {
+ public String isValid(String newText) {
+ if(newText == null || newText.isEmpty())
+ return null;
+ else
+ return super.isValid(newText);
+ }
+
+ });
+ GridDataFactory.fillDefaults().hint(27, SWT.DEFAULT).align(SWT.CENTER, SWT.CENTER).applyTo(variable.getWidget());
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);
+ try {
+ Resource confidenceBound = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ return getResource(graph, resource);
+ }
+
+ });
+
+ if(confidenceBound != null)
+ confidenceBoundSupport.fireInput(context, new StructuredSelection(confidenceBound));
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private Resource getResource(ReadGraph graph, Resource input) throws DatabaseException {
+ Resource dataset = graph.getPossibleObject(input, Layer0.getInstance(graph).PartOf);
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ Resource confidenceBoundsList = graph.getPossibleObject(dataset, SR.Charts_SensitivityDataset_confidenceBounds);
+ if(confidenceBoundsList == null)
+ return null;
+ List<Resource> confidenceBounds = ListUtils.toList(graph, confidenceBoundsList);
+ return confidenceBounds.get(index);
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import java.awt.Color;\r
-import java.util.ArrayList;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-\r
-import javax.swing.SwingUtilities;\r
-\r
-import org.jfree.chart.renderer.AbstractRenderer;\r
-import org.jfree.data.general.Dataset;\r
-import org.jfree.data.general.DefaultPieDataset;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.exception.MissingVariableException;\r
-import org.simantics.db.layer0.request.PossibleActiveExperiment;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.diagram.G2DUtils;\r
-import org.simantics.jfreechart.chart.AbstractDataset;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.sysdyn.Functions;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.adapter.VariableRVIUtils;\r
-import org.simantics.sysdyn.manager.SysdynDataSet;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Class representing a PieDataset in JFreeChart ontology\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class PieDataset extends AbstractDataset implements org.simantics.jfreechart.chart.PieDataset<String> {\r
-\r
- private List<Resource> seriesList;\r
- private String realizationURI;\r
- private DefaultPieDataset dataset;\r
-\r
- private HashMap<String, Color> colorMap;\r
- private HashMap<String, Boolean> explodedMap;\r
-\r
- public PieDataset(ReadGraph graph, Resource resource) throws DatabaseException {\r
- super(graph, resource);\r
-\r
- \r
- Layer0 l0 = Layer0.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- // Find the model where the chart is located\r
- Resource model = resource;\r
- do {\r
- model = graph.getPossibleObject(model, l0.PartOf);\r
- } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));\r
-\r
- // Find the variable realization of the current experiment\r
- realizationURI = null;\r
- Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));\r
- if (realization == null) {\r
- Layer0X L0X = Layer0X.getInstance(graph);\r
- realization = graph.getPossibleObject(model, L0X.HasBaseRealization);\r
- }\r
- if (realization != null)\r
- realizationURI = graph.getURI(realization);\r
-\r
- if(realizationURI == null)\r
- return; // No experiment -> No results\r
-\r
- Resource seriesList = graph.getPossibleObject(resource, jfree.Dataset_seriesList);\r
- if(seriesList != null) {\r
- this.seriesList = ListUtils.toList(graph, seriesList);\r
- }\r
- \r
-\r
- }\r
-\r
- /**\r
- * Map of colors for different slices in a pie chart. Name \r
- * indicates the key of the value.\r
- * @return Map of colors for different slices in a pie chart\r
- */\r
- public HashMap<String, Color> getColorMap() {\r
- return colorMap;\r
- }\r
-\r
- /**\r
- * Map of exploded statuses for slices in a pie chart. Name\r
- * indicates the key of the slice.\r
- * @return\r
- */\r
- public HashMap<String, Boolean> getExplodedMap() {\r
- return explodedMap;\r
- }\r
-\r
- @Override\r
- public Dataset getDataset() {\r
- if(seriesList == null || seriesList.isEmpty() || SimanticsUI.getSession() == null)\r
- return null;\r
-\r
- if(dataset == null) {\r
- dataset = new DefaultPieDataset();\r
- }\r
-\r
- if(listener == null) {\r
- listener = new DatasetListener();\r
- SimanticsUI.getSession().asyncRequest(new Read<ArrayList<TempSeries>>() {\r
-\r
- @Override\r
- public ArrayList<TempSeries> perform(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
-\r
- ArrayList<TempSeries> series = new ArrayList<TempSeries>();\r
- // Get properties for all series\r
- if(seriesList != null) {\r
-\r
- colorMap = new HashMap<String, Color>();\r
- explodedMap = new HashMap<String, Boolean>();\r
-\r
- for(Resource r : seriesList) {\r
- String label = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasLabel);\r
- String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);\r
- if(rvi == null)\r
- continue;\r
-\r
- try {\r
- // Get visual properties\r
- Resource c = graph.getPossibleObject(r, jfree.color);\r
- Color color = c == null ? null : G2DUtils.getColor(graph, c);\r
- Boolean exploded = graph.getPossibleRelatedValue(r, jfree.Series_exploded, Bindings.BOOLEAN);\r
-\r
- // Get a variable for the series\r
- Variable v = Variables.getVariable(graph, realizationURI + rvi);\r
-\r
- // Get values\r
- Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
- if(dsVariable == null)\r
- return series;\r
- \r
- Object object = dsVariable.getValue(graph);\r
- if(object == null || !(object instanceof ArrayList<?>))\r
- return series;\r
-\r
- ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
-\r
- for(Object o : (ArrayList<?>)object) {\r
- if(o instanceof SysdynDataSet)\r
- datasets.add((SysdynDataSet)o);\r
- }\r
-\r
- String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter);\r
- if(filter != null) {\r
- ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);\r
- if(result2 != null) {\r
- datasets = result2;\r
- }\r
- }\r
-\r
- // Find if a specific time is set for this chart\r
- Double chartTime = null;\r
- if(!datasets.isEmpty()) {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource datasetResource = graph.getPossibleObject(r, l0.PartOf);\r
- if(datasetResource != null) {\r
- Resource plot = graph.getPossibleObject(datasetResource, l0.PartOf);\r
- if(plot != null) {\r
- Resource chart = graph.getPossibleObject(plot, l0.PartOf);\r
- if(chart != null)\r
- chartTime = graph.getPossibleRelatedValue(chart, jfree.Chart_time);\r
- }\r
- }\r
- }\r
- \r
- for(SysdynDataSet dataset : datasets) {\r
- double[] va = dataset.values;\r
-\r
- if(va == null || va.length == 0)\r
- continue;\r
-\r
- /*\r
- * Time\r
- * \r
- * 1. find time for the individual series.\r
- * 2. find time for the whole chart\r
- * 3. find simulation time\r
- */\r
- Double time = graph.getPossibleRelatedValue(r, jfree.Series_time, Bindings.DOUBLE);\r
- if(time == null)\r
- time = chartTime;\r
- if(time == null) {\r
- // Get a variable for the experiment run\r
- Variable run = Variables.getVariable(graph, realizationURI);\r
- if(run == null)\r
- return null;\r
- Variable timeVar = run.browsePossible(graph, "#" + Functions.TIME + "#");\r
- if(timeVar != null)\r
- time = timeVar.getValue(graph, Bindings.DOUBLE);\r
- }\r
- \r
- // Value\r
- Double value = null;\r
- if(time == null) {\r
- value = va[va.length - 1];\r
- } else {\r
- double[] ta = dataset.times;\r
- for(int i = 0; i < ta.length; i++) {\r
- double t = ta[i];\r
- if(time <= t) {\r
- value = va[i]; \r
- break;\r
- }\r
- }\r
-\r
- if(value == null)\r
- value = va[va.length - 1];\r
- }\r
-\r
- String name = label == null || label.isEmpty() ? dataset.name : label;\r
- if (dataset.resultIndex != null) {\r
- name += "(" + dataset.resultIndex + ")"; \r
- }\r
- if(dataset.result != null)\r
- name = name + " : " + dataset.result; \r
- colorMap.put(name, color);\r
- explodedMap.put(name, exploded);\r
- series.add(new TempSeries(name, value));\r
- }\r
- } catch (MissingVariableException e) {\r
- // Do nothing, if variable was not found. Move on to the next series\r
- }\r
- }\r
- }\r
- return series;\r
- }\r
-\r
- }, listener);\r
- }\r
- return dataset;\r
- }\r
-\r
- private DatasetListener listener;\r
-\r
- private class DatasetListener implements Listener<ArrayList<TempSeries>> {\r
-\r
- private boolean disposed = false;\r
-\r
- @Override\r
- public void execute(final ArrayList<TempSeries> series) {\r
- // Modify series in AWT thread to avoid synchronization problems\r
- SwingUtilities.invokeLater(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- // Remove all series\r
- dataset.clear();\r
-\r
- // Add found series\r
- for(int i = 0; i < series.size(); i++) {\r
- TempSeries s = series.get(i);\r
- dataset.setValue(s.name, s.value);\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
-\r
- public void dispose() {\r
- disposed = true;\r
- }\r
- }\r
-\r
- @Override\r
- public AbstractRenderer getRenderer() {\r
- // No renderer for pie chart\r
- return null;\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- super.dispose();\r
- if(listener != null) {\r
- listener.dispose();\r
- listener = null;\r
- }\r
- }\r
-\r
-\r
- /**\r
- * Auxiliary class containing all information needed to define a single series\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class TempSeries {\r
- public String name;\r
- public Double value;\r
-\r
- public TempSeries(String name, Double value) {\r
- this.name = name;\r
- this.value = value;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return "TempSeries: " + name + ", " + value;\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.trend;
+
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.swing.SwingUtilities;
+
+import org.jfree.chart.renderer.AbstractRenderer;
+import org.jfree.data.general.Dataset;
+import org.jfree.data.general.DefaultPieDataset;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.exception.MissingVariableException;
+import org.simantics.db.layer0.request.PossibleActiveExperiment;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.diagram.G2DUtils;
+import org.simantics.jfreechart.chart.AbstractDataset;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.operation.Layer0X;
+import org.simantics.sysdyn.Functions;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.adapter.VariableRVIUtils;
+import org.simantics.sysdyn.manager.SysdynDataSet;
+
+/**
+ * Class representing a PieDataset in JFreeChart ontology
+ * @author Teemu Lempinen
+ *
+ */
+public class PieDataset extends AbstractDataset implements org.simantics.jfreechart.chart.PieDataset<String> {
+
+ private List<Resource> seriesList;
+ private String realizationURI;
+ private DefaultPieDataset dataset;
+
+ private HashMap<String, Color> colorMap;
+ private HashMap<String, Boolean> explodedMap;
+
+ public PieDataset(ReadGraph graph, Resource resource) throws DatabaseException {
+ super(graph, resource);
+
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ // Find the model where the chart is located
+ Resource model = resource;
+ do {
+ model = graph.getPossibleObject(model, l0.PartOf);
+ } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));
+
+ // Find the variable realization of the current experiment
+ realizationURI = null;
+ Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));
+ if (realization == null) {
+ Layer0X L0X = Layer0X.getInstance(graph);
+ realization = graph.getPossibleObject(model, L0X.HasBaseRealization);
+ }
+ if (realization != null)
+ realizationURI = graph.getURI(realization);
+
+ if(realizationURI == null)
+ return; // No experiment -> No results
+
+ Resource seriesList = graph.getPossibleObject(resource, jfree.Dataset_seriesList);
+ if(seriesList != null) {
+ this.seriesList = ListUtils.toList(graph, seriesList);
+ }
+
+
+ }
+
+ /**
+ * Map of colors for different slices in a pie chart. Name
+ * indicates the key of the value.
+ * @return Map of colors for different slices in a pie chart
+ */
+ public HashMap<String, Color> getColorMap() {
+ return colorMap;
+ }
+
+ /**
+ * Map of exploded statuses for slices in a pie chart. Name
+ * indicates the key of the slice.
+ * @return
+ */
+ public HashMap<String, Boolean> getExplodedMap() {
+ return explodedMap;
+ }
+
+ @Override
+ public Dataset getDataset() {
+ if(seriesList == null || seriesList.isEmpty() || Simantics.getSession() == null)
+ return null;
+
+ if(dataset == null) {
+ dataset = new DefaultPieDataset();
+ }
+
+ if(listener == null) {
+ listener = new DatasetListener();
+ Simantics.getSession().asyncRequest(new Read<ArrayList<TempSeries>>() {
+
+ @Override
+ public ArrayList<TempSeries> perform(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+
+ ArrayList<TempSeries> series = new ArrayList<TempSeries>();
+ // Get properties for all series
+ if(seriesList != null) {
+
+ colorMap = new HashMap<String, Color>();
+ explodedMap = new HashMap<String, Boolean>();
+
+ for(Resource r : seriesList) {
+ String label = graph.getPossibleRelatedValue(r, Layer0.getInstance(graph).HasLabel);
+ String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);
+ if(rvi == null)
+ continue;
+
+ try {
+ // Get visual properties
+ Resource c = graph.getPossibleObject(r, jfree.color);
+ Color color = c == null ? null : G2DUtils.getColor(graph, c);
+ Boolean exploded = graph.getPossibleRelatedValue(r, jfree.Series_exploded, Bindings.BOOLEAN);
+
+ // Get a variable for the series
+ Variable v = Variables.getVariable(graph, realizationURI + rvi);
+
+ // Get values
+ Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");
+ if(dsVariable == null)
+ return series;
+
+ Object object = dsVariable.getValue(graph);
+ if(object == null || !(object instanceof ArrayList<?>))
+ return series;
+
+ ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();
+
+ for(Object o : (ArrayList<?>)object) {
+ if(o instanceof SysdynDataSet)
+ datasets.add((SysdynDataSet)o);
+ }
+
+ String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter);
+ if(filter != null) {
+ ArrayList<SysdynDataSet> result2 = VariableRVIUtils.getDataset(datasets, filter);
+ if(result2 != null) {
+ datasets = result2;
+ }
+ }
+
+ // Find if a specific time is set for this chart
+ Double chartTime = null;
+ if(!datasets.isEmpty()) {
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource datasetResource = graph.getPossibleObject(r, l0.PartOf);
+ if(datasetResource != null) {
+ Resource plot = graph.getPossibleObject(datasetResource, l0.PartOf);
+ if(plot != null) {
+ Resource chart = graph.getPossibleObject(plot, l0.PartOf);
+ if(chart != null)
+ chartTime = graph.getPossibleRelatedValue(chart, jfree.Chart_time);
+ }
+ }
+ }
+
+ for(SysdynDataSet dataset : datasets) {
+ double[] va = dataset.values;
+
+ if(va == null || va.length == 0)
+ continue;
+
+ /*
+ * Time
+ *
+ * 1. find time for the individual series.
+ * 2. find time for the whole chart
+ * 3. find simulation time
+ */
+ Double time = graph.getPossibleRelatedValue(r, jfree.Series_time, Bindings.DOUBLE);
+ if(time == null)
+ time = chartTime;
+ if(time == null) {
+ // Get a variable for the experiment run
+ Variable run = Variables.getVariable(graph, realizationURI);
+ if(run == null)
+ return null;
+ Variable timeVar = run.browsePossible(graph, "#" + Functions.TIME + "#");
+ if(timeVar != null)
+ time = timeVar.getValue(graph, Bindings.DOUBLE);
+ }
+
+ // Value
+ Double value = null;
+ if(time == null) {
+ value = va[va.length - 1];
+ } else {
+ double[] ta = dataset.times;
+ for(int i = 0; i < ta.length; i++) {
+ double t = ta[i];
+ if(time <= t) {
+ value = va[i];
+ break;
+ }
+ }
+
+ if(value == null)
+ value = va[va.length - 1];
+ }
+
+ String name = label == null || label.isEmpty() ? dataset.name : label;
+ if (dataset.resultIndex != null) {
+ name += "(" + dataset.resultIndex + ")";
+ }
+ if(dataset.result != null)
+ name = name + " : " + dataset.result;
+ colorMap.put(name, color);
+ explodedMap.put(name, exploded);
+ series.add(new TempSeries(name, value));
+ }
+ } catch (MissingVariableException e) {
+ // Do nothing, if variable was not found. Move on to the next series
+ }
+ }
+ }
+ return series;
+ }
+
+ }, listener);
+ }
+ return dataset;
+ }
+
+ private DatasetListener listener;
+
+ private class DatasetListener implements Listener<ArrayList<TempSeries>> {
+
+ private boolean disposed = false;
+
+ @Override
+ public void execute(final ArrayList<TempSeries> series) {
+ // Modify series in AWT thread to avoid synchronization problems
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run() {
+ // Remove all series
+ dataset.clear();
+
+ // Add found series
+ for(int i = 0; i < series.size(); i++) {
+ TempSeries s = series.get(i);
+ dataset.setValue(s.name, s.value);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+
+ public void dispose() {
+ disposed = true;
+ }
+ }
+
+ @Override
+ public AbstractRenderer getRenderer() {
+ // No renderer for pie chart
+ return null;
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ if(listener != null) {
+ listener.dispose();
+ listener = null;
+ }
+ }
+
+
+ /**
+ * Auxiliary class containing all information needed to define a single series
+ * @author Teemu Lempinen
+ *
+ */
+ private class TempSeries {
+ public String name;
+ public Double value;
+
+ public TempSeries(String name, Double value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return "TempSeries: " + name + ", " + value;
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2013, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.custom.ScrolledComposite;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.graphics.Point;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.properties.AdjustableTab;\r
-import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;\r
-import org.simantics.jfreechart.chart.properties.xyline.AxisPropertyComposite;\r
-import org.simantics.jfreechart.chart.properties.xyline.SeriesPropertyComposite;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class SensitivityChartAxisAndVariablesTab extends AdjustableTab {\r
-\r
- private GraphExplorerComposite explorer;\r
- private ScrolledComposite propertyContainer;\r
- private WidgetSupportImpl additionalSupport;\r
-\r
- public SensitivityChartAxisAndVariablesTab(Object id) {\r
- super(id);\r
- additionalSupport = new WidgetSupportImpl();\r
- }\r
-\r
- /**\r
- * Updates the content of propertyContainer \r
- * @param context\r
- */\r
- private void updateSelection(ISessionContext context) {\r
- ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);\r
- IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();\r
- final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);\r
- if(resource == null)\r
- return;\r
-\r
- // Get the type of the selected node (axis or series)\r
- String typeUri = null;\r
- try {\r
- typeUri = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- if(graph.isInstanceOf(resource, jfree.Axis))\r
- return graph.getURI(jfree.Axis);\r
- else if (graph.isInstanceOf(resource, jfree.Series))\r
- return graph.getURI(jfree.Series);\r
- return null;\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- // Create a PropertyComposite for the selected node\r
- if(typeUri != null) {\r
-\r
- for(Control child : propertyContainer.getChildren()) {\r
- child.dispose();\r
- }\r
-\r
- if(typeUri.equals(JFreeChartResource.URIs.Axis)) {\r
- AxisPropertyComposite apc = new AxisPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE, isVertical());\r
- propertyContainer.setContent(apc);\r
- Point size = apc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- } else if(typeUri.equals(JFreeChartResource.URIs.Series)) {\r
- SeriesPropertyComposite spc = new SensitivitySeriesPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE);\r
- propertyContainer.setContent(spc);\r
- Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);\r
- propertyContainer.setMinSize(size);\r
- }\r
- }\r
-\r
- additionalSupport.fireInput(context, selection);\r
- }\r
-\r
- @Override\r
- protected void createAndAddControls(Composite body, IWorkbenchSite site,\r
- final ISessionContext context, WidgetSupport support) {\r
- composite = new Composite(body, SWT.NONE);\r
-\r
- // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis\r
- explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);\r
- explorer.setBrowseContexts(JFreeChartResource.URIs.ChartAxisAndVariablesBrowseContext);\r
- explorer.setInputSource(new SingleSelectionInputSource(\r
- Resource.class));\r
- explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning\r
- explorer.finish();\r
-\r
- ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {\r
- public void widgetSelected(SelectionEvent e) {\r
- updateSelection(context);\r
- }\r
- });\r
-\r
- // Scrolled composite for displaying properties of a selection in explorer\r
- propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);\r
- propertyContainer.setExpandHorizontal(true);\r
- propertyContainer.setExpandVertical(true);\r
-\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutVertical() {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);\r
-\r
- GridDataFactory.fillDefaults().hint(220, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
-\r
- // Scrolled composite for displaying properties of a selection in explorer\r
- GridDataFactory.fillDefaults().span(1, 1).hint(SWT.DEFAULT, 210).grab(true, false).applyTo(propertyContainer);\r
- GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
- }\r
-\r
- @Override\r
- protected void createControlLayoutHorizontal(boolean wideScreen) {\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);\r
-\r
- GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);\r
-\r
- // Scrolled composite for displaying properties of a selection in explorer\r
- GridDataFactory.fillDefaults().span(1, 2).hint(SWT.DEFAULT, SWT.DEFAULT).grab(true, true).applyTo(propertyContainer);\r
- GridLayoutFactory.fillDefaults().applyTo(propertyContainer);\r
- }\r
-\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013, 2014 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.trend;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.SingleSelectionInputSource;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.properties.AdjustableTab;
+import org.simantics.jfreechart.chart.properties.xyline.AxisAndVariablesExplorerComposite;
+import org.simantics.jfreechart.chart.properties.xyline.AxisPropertyComposite;
+import org.simantics.jfreechart.chart.properties.xyline.SeriesPropertyComposite;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.utils.datastructures.ArrayMap;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class SensitivityChartAxisAndVariablesTab extends AdjustableTab {
+
+ private GraphExplorerComposite explorer;
+ private ScrolledComposite propertyContainer;
+ private WidgetSupportImpl additionalSupport;
+
+ public SensitivityChartAxisAndVariablesTab(Object id) {
+ super(id);
+ additionalSupport = new WidgetSupportImpl();
+ }
+
+ /**
+ * Updates the content of propertyContainer
+ * @param context
+ */
+ private void updateSelection(ISessionContext context) {
+ ISelectionProvider selectionProvider = (ISelectionProvider)explorer.getAdapter(ISelectionProvider.class);
+ IStructuredSelection selection = (IStructuredSelection)selectionProvider.getSelection();
+ final Resource resource = AdaptionUtils.adaptToSingle(selection, Resource.class);
+ if(resource == null)
+ return;
+
+ // Get the type of the selected node (axis or series)
+ String typeUri = null;
+ try {
+ typeUri = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ if(graph.isInstanceOf(resource, jfree.Axis))
+ return graph.getURI(jfree.Axis);
+ else if (graph.isInstanceOf(resource, jfree.Series))
+ return graph.getURI(jfree.Series);
+ return null;
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ // Create a PropertyComposite for the selected node
+ if(typeUri != null) {
+
+ for(Control child : propertyContainer.getChildren()) {
+ child.dispose();
+ }
+
+ if(typeUri.equals(JFreeChartResource.URIs.Axis)) {
+ AxisPropertyComposite apc = new AxisPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE, isVertical());
+ propertyContainer.setContent(apc);
+ Point size = apc.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ } else if(typeUri.equals(JFreeChartResource.URIs.Series)) {
+ SeriesPropertyComposite spc = new SensitivitySeriesPropertyComposite(propertyContainer, context, additionalSupport, SWT.NONE);
+ propertyContainer.setContent(spc);
+ Point size = spc.computeSize(SWT.DEFAULT, SWT.DEFAULT);
+ propertyContainer.setMinSize(size);
+ }
+ }
+
+ additionalSupport.fireInput(context, selection);
+ }
+
+ @Override
+ protected void createAndAddControls(Composite body, IWorkbenchSite site,
+ final ISessionContext context, WidgetSupport support) {
+ composite = new Composite(body, SWT.NONE);
+
+ // (Ontology-based) GraphExplorer displaying range axis and variables mapped to those axis
+ explorer = new AxisAndVariablesExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), site, composite, support, SWT.FULL_SELECTION | SWT.BORDER | SWT.SINGLE);
+ explorer.setBrowseContexts(JFreeChartResource.URIs.ChartAxisAndVariablesBrowseContext);
+ explorer.setInputSource(new SingleSelectionInputSource(
+ Resource.class));
+ explorer.getExplorer().setAutoExpandLevel(2); // Expand everything in the beginning
+ explorer.finish();
+
+ ((Tree)explorer.getExplorerControl()).addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ updateSelection(context);
+ }
+ });
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ propertyContainer = new ScrolledComposite(composite, SWT.H_SCROLL | SWT.V_SCROLL);
+ propertyContainer.setExpandHorizontal(true);
+ propertyContainer.setExpandVertical(true);
+
+ }
+
+ @Override
+ protected void createControlLayoutVertical() {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().numColumns(1).margins(3, 3).applyTo(composite);
+
+ GridDataFactory.fillDefaults().hint(220, SWT.DEFAULT).grab(false, true).applyTo(explorer);
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ GridDataFactory.fillDefaults().span(1, 1).hint(SWT.DEFAULT, 210).grab(true, false).applyTo(propertyContainer);
+ GridLayoutFactory.fillDefaults().applyTo(propertyContainer);
+ }
+
+ @Override
+ protected void createControlLayoutHorizontal(boolean wideScreen) {
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(composite);
+
+ GridDataFactory.fillDefaults().hint(250, SWT.DEFAULT).grab(false, true).applyTo(explorer);
+
+ // Scrolled composite for displaying properties of a selection in explorer
+ GridDataFactory.fillDefaults().span(1, 2).hint(SWT.DEFAULT, SWT.DEFAULT).grab(true, true).applyTo(propertyContainer);
+ GridLayoutFactory.fillDefaults().applyTo(propertyContainer);
+ }
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * Semantum Oy - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import java.awt.BasicStroke;\r
-import java.awt.Color;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.List;\r
-\r
-import javax.swing.SwingUtilities;\r
-\r
-import org.jfree.chart.LegendItem;\r
-import org.jfree.chart.renderer.AbstractRenderer;\r
-import org.jfree.chart.renderer.xy.DeviationRenderer;\r
-import org.jfree.data.general.Dataset;\r
-import org.jfree.data.xy.YIntervalSeries;\r
-import org.jfree.data.xy.YIntervalSeriesCollection;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.procedure.adapter.DisposableListener;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.diagram.G2DUtils;\r
-import org.simantics.jfreechart.chart.IRenderer;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-/**\r
- * Dataset for sensitivity analysis fan charts.\r
- * \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class SensitivityDataset extends XYDataset {\r
-\r
- DeviationRenderer renderer;\r
- \r
- public SensitivityDataset(ReadGraph graph, Resource resource) throws DatabaseException {\r
- super(graph, resource);\r
- }\r
-\r
- @SuppressWarnings("unchecked")\r
- @Override\r
- public Dataset getDataset() {\r
- if(dataset == null) {\r
- dataset = new YIntervalSeriesCollection();\r
- } \r
-\r
- if(datasetListener == null || datasetListener.isDisposed()) {\r
- datasetListener = new SensitivityDatasetListener();\r
- SimanticsUI.getSession().asyncRequest(\r
- new SensitivityDatasetRequest(resource), \r
- (DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>>) datasetListener); \r
- }\r
-\r
- if(timeListener == null || timeListener.isDisposed()) {\r
- SimanticsUI.getSession().asyncRequest(getTimeRequest(), getTimeListener());\r
- }\r
- return dataset;\r
- }\r
- \r
- /**\r
- * SensitivityDatasetRequest uses {@link XYDatasetRequest} to get values for all sensitivity analysis runs.\r
- * \r
- * In addition, the request finds fan chart properties from dataset resource and passes them to {@link SensitivityDatasetListener}\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class SensitivityDatasetRequest implements Read<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>> {\r
-\r
- private Resource dataset;\r
- \r
- public SensitivityDatasetRequest(Resource dataset) {\r
- this.dataset = dataset;\r
- }\r
- \r
- @Override\r
- public Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> perform(ReadGraph graph) throws DatabaseException {\r
- \r
- Pair<ArrayList<XYDatasetTempSeries>, IRenderer> XYDatasetRequestResult = graph.syncRequest(new XYDatasetRequest(dataset));\r
- \r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- Boolean median = graph.getPossibleRelatedValue(dataset, SR.Charts_SensitivityDataset_median);\r
- if (median == null)\r
- median = false;\r
- \r
- Resource confidenceBoundsList = graph.getPossibleObject(dataset, SR.Charts_SensitivityDataset_confidenceBounds);\r
- ArrayList<ConfidenceBound> confidenceBounds = new ArrayList<ConfidenceBound>();\r
-\r
- if(confidenceBoundsList != null) {\r
- List<Resource> confidenceBoundResources = ListUtils.toList(graph, confidenceBoundsList);\r
-\r
- for(Resource cb : confidenceBoundResources) {\r
- Double percent = graph.getPossibleRelatedValue(cb, SR.Charts_SensitivityDataset_ConfidenceBound_percent);\r
- Resource c = graph.getPossibleObject(cb, SR.Charts_SensitivityDataset_ConfidenceBound_color);\r
- Color color = c == null ? null : G2DUtils.getColor(graph, c);\r
- if(percent != null && color != null)\r
- confidenceBounds.add(new ConfidenceBound(percent, color));\r
- }\r
- }\r
- \r
- SensitivityDatasetProperties properties = new SensitivityDatasetProperties(median, confidenceBounds);\r
- \r
- return new Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> (XYDatasetRequestResult.first, properties);\r
- }\r
- \r
- }\r
-\r
- @Override\r
- public AbstractRenderer getRenderer() {\r
- if(renderer == null)\r
- renderer = new DeviationRenderer(true, false) {\r
- private static final long serialVersionUID = 633310754812851862L;\r
-\r
- /* \r
- * Overridden getLegendElement to provide thick lines for legend.\r
- */\r
- @Override\r
- public LegendItem getLegendItem(int datasetIndex, int series) {\r
- LegendItem item = super.getLegendItem(datasetIndex, series);\r
- return new LegendItem(item.getLabel(), item.getDescription(), item.getToolTipText(), item.getURLText(), item.getLine(), new BasicStroke(5F), item.getLinePaint());\r
- }\r
- };\r
- return renderer;\r
- }\r
- \r
- /**\r
- * SensitivityDatasetListener calculates confidence bounds from all sensitivity analysis run results.\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- private class SensitivityDatasetListener extends DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>> {\r
-\r
- @Override\r
- public void execute(Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> result) {\r
- final ArrayList<XYDatasetTempSeries> series = result.first;\r
- final SensitivityDatasetProperties properties = result.second;\r
- \r
- // Modify series in AWT thread to avoid synchronization problems\r
- SwingUtilities.invokeLater(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
-\r
- if(dataset == null || !(dataset instanceof YIntervalSeriesCollection))\r
- return;\r
- \r
- YIntervalSeriesCollection ds = (YIntervalSeriesCollection)dataset;\r
-\r
- DeviationRenderer dr = (DeviationRenderer)getRenderer();\r
- \r
- ArrayList<ConfidenceBound> confidenceBounds = properties.getConfidenceBounds();\r
-\r
- \r
- // CONFIDENCE BOUND PAINTS\r
- for(int i = 1; i <= confidenceBounds.size(); i++) {\r
- dr.setSeriesStroke(i, new BasicStroke(0F));\r
- dr.setSeriesPaint(i, confidenceBounds.get(i-1).getColor());\r
- dr.setSeriesFillPaint(i, confidenceBounds.get(i-1).getColor());\r
- }\r
- \r
- Color medianColor = Color.RED;\r
- // MEDIAN PAINTS\r
- dr.setSeriesStroke(0, new BasicStroke(2F));\r
- dr.setSeriesPaint(0, medianColor);\r
- dr.setSeriesFillPaint(0, medianColor);\r
- dr.setSeriesVisibleInLegend(0, true);\r
-\r
- \r
- if(!properties.displayMedian()) {\r
- /*\r
- * Median is in the first index position. If it\r
- * is not visible, make it the same color as\r
- * the next series and hide it from legend\r
- */\r
- dr.setSeriesVisibleInLegend(0, false);\r
- dr.setSeriesPaint(0, dr.getSeriesPaint(1));\r
- }\r
- \r
- dr.setAlpha(1);\r
- \r
- // Remove all series\r
- for(int i = ds.getSeriesCount() - 1; i >= 0; i-- ) {\r
- ds.removeSeries(ds.getSeries(i));\r
- }\r
- \r
- int n = series.size();\r
- if(n < 1)\r
- return;\r
- \r
- int length = series.get(0).values[0].length;\r
- \r
- \r
- YIntervalSeries median = new YIntervalSeries("Median");\r
- \r
- YIntervalSeries[] yIntervalSeries = new YIntervalSeries[confidenceBounds.size()];\r
- for(int i = 0; i < confidenceBounds.size(); i++) {\r
- yIntervalSeries[i] = new YIntervalSeries(confidenceBounds.get(i).getPercent() + "%");\r
- }\r
-\r
- ArrayList<Double> sorter = new ArrayList<Double>();\r
- for(int i = 0; i < length; i++) {\r
- sorter.clear();\r
- for(int j = 0; j < n; j++) {\r
- if(series.get(j).values[1].length == 0)\r
- continue; // If there are no values, move on to next dataset\r
- sorter.add(series.get(j).values[1][i]); // values is a two-dimensional array. 0 dimension == times, 1 == values\r
- }\r
- Collections.sort(sorter);\r
- \r
- int sorterSize = sorter.size();\r
- int intervals = sorterSize - 1;\r
- \r
- // MEDIAN\r
- double medianX = series.get(0).values[0][i];\r
- double medianY = sorter.get(sorterSize/2);\r
- median.add(\r
- medianX, \r
- medianY,\r
- medianY,\r
- medianY\r
- );\r
-\r
- // CONFIDENCE BOUNDS\r
- for(int j = 0; j < yIntervalSeries.length; j++) {\r
- YIntervalSeries yis = yIntervalSeries[j];\r
- double percent = properties.getConfidenceBounds().get(j).getPercent() / 100;\r
- if(n >= (1 / percent) * 2) {\r
- // Estimate the confidence limits\r
- double indexLow = (1 - percent) * intervals / 2;\r
- int indexLowLow = (int)Math.floor(indexLow);\r
- int indexLowHigh = (int)Math.ceil(indexLow);\r
- double valueLowLow = sorter.get(indexLowLow);\r
- double valueLowHigh = sorter.get(indexLowHigh);\r
- double decimalLow = indexLow - indexLowLow;\r
- // Linear interpolation; to decrease execution time, use interpolation of degree 0, \r
- // but I didn't find the current approach too time consuming in a simple test. \r
- double estimateLow = (valueLowHigh - valueLowLow) * decimalLow + valueLowLow;\r
- \r
- double indexHigh = (1 + percent) * intervals / 2;;\r
- int indexHighLow = (int)Math.floor(indexHigh);\r
- int indexHighHigh = (int)Math.ceil(indexHigh);\r
- double valueHighLow = sorter.get(indexHighLow);\r
- double valueHighHigh = sorter.get(indexHighHigh);\r
- double decimalHigh = 1 - decimalLow; \r
- double estimateHigh = (valueHighHigh - valueHighLow) * decimalHigh + valueHighLow;\r
- yis.add(\r
- medianX, \r
- medianY,\r
- estimateLow,\r
- estimateHigh\r
- );\r
- }\r
- }\r
- }\r
- \r
- // ADD MEDIAN\r
- ds.addSeries(median);\r
- \r
- // ADD OTHERS\r
- // CONFIDENCE BOUNDS\r
- for(int j = 0; j < yIntervalSeries.length; j++) {\r
- YIntervalSeries yis = yIntervalSeries[j];\r
- double percent = properties.getConfidenceBounds().get(j).getPercent();\r
- if(n >= (1 / percent) * 2)\r
- ds.addSeries(yis);\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
-\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2013 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Semantum Oy - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.trend;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.swing.SwingUtilities;
+
+import org.jfree.chart.LegendItem;
+import org.jfree.chart.renderer.AbstractRenderer;
+import org.jfree.chart.renderer.xy.DeviationRenderer;
+import org.jfree.data.general.Dataset;
+import org.jfree.data.xy.YIntervalSeries;
+import org.jfree.data.xy.YIntervalSeriesCollection;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.procedure.adapter.DisposableListener;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.diagram.G2DUtils;
+import org.simantics.jfreechart.chart.IRenderer;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.utils.datastructures.Pair;
+
+/**
+ * Dataset for sensitivity analysis fan charts.
+ *
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class SensitivityDataset extends XYDataset {
+
+ DeviationRenderer renderer;
+
+ public SensitivityDataset(ReadGraph graph, Resource resource) throws DatabaseException {
+ super(graph, resource);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Dataset getDataset() {
+ if(dataset == null) {
+ dataset = new YIntervalSeriesCollection();
+ }
+
+ if(datasetListener == null || datasetListener.isDisposed()) {
+ datasetListener = new SensitivityDatasetListener();
+ Simantics.getSession().asyncRequest(
+ new SensitivityDatasetRequest(resource),
+ (DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>>) datasetListener);
+ }
+
+ if(timeListener == null || timeListener.isDisposed()) {
+ Simantics.getSession().asyncRequest(getTimeRequest(), getTimeListener());
+ }
+ return dataset;
+ }
+
+ /**
+ * SensitivityDatasetRequest uses {@link XYDatasetRequest} to get values for all sensitivity analysis runs.
+ *
+ * In addition, the request finds fan chart properties from dataset resource and passes them to {@link SensitivityDatasetListener}
+ * @author Teemu Lempinen
+ *
+ */
+ private class SensitivityDatasetRequest implements Read<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>> {
+
+ private Resource dataset;
+
+ public SensitivityDatasetRequest(Resource dataset) {
+ this.dataset = dataset;
+ }
+
+ @Override
+ public Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> perform(ReadGraph graph) throws DatabaseException {
+
+ Pair<ArrayList<XYDatasetTempSeries>, IRenderer> XYDatasetRequestResult = graph.syncRequest(new XYDatasetRequest(dataset));
+
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ Boolean median = graph.getPossibleRelatedValue(dataset, SR.Charts_SensitivityDataset_median);
+ if (median == null)
+ median = false;
+
+ Resource confidenceBoundsList = graph.getPossibleObject(dataset, SR.Charts_SensitivityDataset_confidenceBounds);
+ ArrayList<ConfidenceBound> confidenceBounds = new ArrayList<ConfidenceBound>();
+
+ if(confidenceBoundsList != null) {
+ List<Resource> confidenceBoundResources = ListUtils.toList(graph, confidenceBoundsList);
+
+ for(Resource cb : confidenceBoundResources) {
+ Double percent = graph.getPossibleRelatedValue(cb, SR.Charts_SensitivityDataset_ConfidenceBound_percent);
+ Resource c = graph.getPossibleObject(cb, SR.Charts_SensitivityDataset_ConfidenceBound_color);
+ Color color = c == null ? null : G2DUtils.getColor(graph, c);
+ if(percent != null && color != null)
+ confidenceBounds.add(new ConfidenceBound(percent, color));
+ }
+ }
+
+ SensitivityDatasetProperties properties = new SensitivityDatasetProperties(median, confidenceBounds);
+
+ return new Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> (XYDatasetRequestResult.first, properties);
+ }
+
+ }
+
+ @Override
+ public AbstractRenderer getRenderer() {
+ if(renderer == null)
+ renderer = new DeviationRenderer(true, false) {
+ private static final long serialVersionUID = 633310754812851862L;
+
+ /*
+ * Overridden getLegendElement to provide thick lines for legend.
+ */
+ @Override
+ public LegendItem getLegendItem(int datasetIndex, int series) {
+ LegendItem item = super.getLegendItem(datasetIndex, series);
+ return new LegendItem(item.getLabel(), item.getDescription(), item.getToolTipText(), item.getURLText(), item.getLine(), new BasicStroke(5F), item.getLinePaint());
+ }
+ };
+ return renderer;
+ }
+
+ /**
+ * SensitivityDatasetListener calculates confidence bounds from all sensitivity analysis run results.
+ * @author Teemu Lempinen
+ *
+ */
+ private class SensitivityDatasetListener extends DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties>> {
+
+ @Override
+ public void execute(Pair<ArrayList<XYDatasetTempSeries>, SensitivityDatasetProperties> result) {
+ final ArrayList<XYDatasetTempSeries> series = result.first;
+ final SensitivityDatasetProperties properties = result.second;
+
+ // Modify series in AWT thread to avoid synchronization problems
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run() {
+
+ if(dataset == null || !(dataset instanceof YIntervalSeriesCollection))
+ return;
+
+ YIntervalSeriesCollection ds = (YIntervalSeriesCollection)dataset;
+
+ DeviationRenderer dr = (DeviationRenderer)getRenderer();
+
+ ArrayList<ConfidenceBound> confidenceBounds = properties.getConfidenceBounds();
+
+
+ // CONFIDENCE BOUND PAINTS
+ for(int i = 1; i <= confidenceBounds.size(); i++) {
+ dr.setSeriesStroke(i, new BasicStroke(0F));
+ dr.setSeriesPaint(i, confidenceBounds.get(i-1).getColor());
+ dr.setSeriesFillPaint(i, confidenceBounds.get(i-1).getColor());
+ }
+
+ Color medianColor = Color.RED;
+ // MEDIAN PAINTS
+ dr.setSeriesStroke(0, new BasicStroke(2F));
+ dr.setSeriesPaint(0, medianColor);
+ dr.setSeriesFillPaint(0, medianColor);
+ dr.setSeriesVisibleInLegend(0, true);
+
+
+ if(!properties.displayMedian()) {
+ /*
+ * Median is in the first index position. If it
+ * is not visible, make it the same color as
+ * the next series and hide it from legend
+ */
+ dr.setSeriesVisibleInLegend(0, false);
+ dr.setSeriesPaint(0, dr.getSeriesPaint(1));
+ }
+
+ dr.setAlpha(1);
+
+ // Remove all series
+ for(int i = ds.getSeriesCount() - 1; i >= 0; i-- ) {
+ ds.removeSeries(ds.getSeries(i));
+ }
+
+ int n = series.size();
+ if(n < 1)
+ return;
+
+ int length = series.get(0).values[0].length;
+
+
+ YIntervalSeries median = new YIntervalSeries("Median");
+
+ YIntervalSeries[] yIntervalSeries = new YIntervalSeries[confidenceBounds.size()];
+ for(int i = 0; i < confidenceBounds.size(); i++) {
+ yIntervalSeries[i] = new YIntervalSeries(confidenceBounds.get(i).getPercent() + "%");
+ }
+
+ ArrayList<Double> sorter = new ArrayList<Double>();
+ for(int i = 0; i < length; i++) {
+ sorter.clear();
+ for(int j = 0; j < n; j++) {
+ if(series.get(j).values[1].length == 0)
+ continue; // If there are no values, move on to next dataset
+ sorter.add(series.get(j).values[1][i]); // values is a two-dimensional array. 0 dimension == times, 1 == values
+ }
+ Collections.sort(sorter);
+
+ int sorterSize = sorter.size();
+ int intervals = sorterSize - 1;
+
+ // MEDIAN
+ double medianX = series.get(0).values[0][i];
+ double medianY = sorter.get(sorterSize/2);
+ median.add(
+ medianX,
+ medianY,
+ medianY,
+ medianY
+ );
+
+ // CONFIDENCE BOUNDS
+ for(int j = 0; j < yIntervalSeries.length; j++) {
+ YIntervalSeries yis = yIntervalSeries[j];
+ double percent = properties.getConfidenceBounds().get(j).getPercent() / 100;
+ if(n >= (1 / percent) * 2) {
+ // Estimate the confidence limits
+ double indexLow = (1 - percent) * intervals / 2;
+ int indexLowLow = (int)Math.floor(indexLow);
+ int indexLowHigh = (int)Math.ceil(indexLow);
+ double valueLowLow = sorter.get(indexLowLow);
+ double valueLowHigh = sorter.get(indexLowHigh);
+ double decimalLow = indexLow - indexLowLow;
+ // Linear interpolation; to decrease execution time, use interpolation of degree 0,
+ // but I didn't find the current approach too time consuming in a simple test.
+ double estimateLow = (valueLowHigh - valueLowLow) * decimalLow + valueLowLow;
+
+ double indexHigh = (1 + percent) * intervals / 2;;
+ int indexHighLow = (int)Math.floor(indexHigh);
+ int indexHighHigh = (int)Math.ceil(indexHigh);
+ double valueHighLow = sorter.get(indexHighLow);
+ double valueHighHigh = sorter.get(indexHighHigh);
+ double decimalHigh = 1 - decimalLow;
+ double estimateHigh = (valueHighHigh - valueHighLow) * decimalHigh + valueHighLow;
+ yis.add(
+ medianX,
+ medianY,
+ estimateLow,
+ estimateHigh
+ );
+ }
+ }
+ }
+
+ // ADD MEDIAN
+ ds.addSeries(median);
+
+ // ADD OTHERS
+ // CONFIDENCE BOUNDS
+ for(int j = 0; j < yIntervalSeries.length; j++) {
+ YIntervalSeries yis = yIntervalSeries[j];
+ double percent = properties.getConfidenceBounds().get(j).getPercent();
+ if(n >= (1 / percent) * 2)
+ ds.addSeries(yis);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import java.awt.Frame;\r
-import java.util.Collection;\r
-\r
-import javax.swing.SwingUtilities;\r
-\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.awt.SWT_AWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.ui.part.ViewPart;\r
-import org.jfree.chart.ChartPanel;\r
-import org.jfree.chart.JFreeChart;\r
-import org.jfree.chart.axis.NumberAxis;\r
-import org.jfree.chart.plot.XYPlot;\r
-import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\r
-import org.jfree.data.xy.AbstractXYDataset;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.IJFreeChart;\r
-import org.simantics.sysdyn.manager.SysdynDataSet;\r
-import org.simantics.sysdyn.ui.viewUtils.SysdynDatasetSelectionListener;\r
-import org.simantics.utils.RunnableWithObject;\r
-\r
-/**\r
- * Trend view that shows all active simulation results for selected variables.\r
- * \r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class TrendView extends ViewPart {\r
-\r
- private Frame frame;\r
- private ChartPanel panel;\r
- private SysdynDatasets sysdynDatasets = new SysdynDatasets();\r
- private SysdynDatasetSelectionListener sysdynDatasetSelectionListener;\r
- private JFreeChart defaultchart;\r
- private Composite composite;\r
-\r
- \r
- public Frame getFrame() {\r
- return frame;\r
- }\r
-\r
- public ChartPanel getPanel() {\r
- return panel;\r
- }\r
- \r
- public void setPanel(ChartPanel panel) {\r
- this.panel = panel;\r
- }\r
-\r
- public SysdynDatasets getSysdynDatasets() {\r
- return sysdynDatasets;\r
- }\r
-\r
- /**\r
- * Dataset for jFreeChart\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
- @SuppressWarnings("serial")\r
- class SysdynDatasets extends AbstractXYDataset {\r
-\r
- SysdynDataSet[] sets = new SysdynDataSet[0];\r
-\r
- public void setDatasets(SysdynDataSet[] sets) {\r
- this.sets = sets;\r
- fireDatasetChanged();\r
- }\r
-\r
- @Override\r
- public Number getY(int series, int item) {\r
- return sets[series].values[item];\r
- }\r
-\r
- @Override\r
- public Number getX(int series, int item) {\r
- return sets[series].times[item];\r
- }\r
-\r
- @Override\r
- public int getItemCount(int series) {\r
- return sets[series].times.length;\r
- }\r
-\r
- @Override\r
- public Comparable<String> getSeriesKey(int series) {\r
- SysdynDataSet sds = sets[series];\r
- String name = sds.name;\r
- if(sds.resultIndex != null)\r
- name += "(" + sds.resultIndex + ")"; \r
- if(sds.result == null)\r
- return name;\r
- else\r
- return name + " : " + sds.result;\r
- }\r
-\r
- @Override\r
- public int getSeriesCount() {\r
- return sets.length;\r
- }\r
-\r
- }\r
-\r
- @Override\r
- public void createPartControl(Composite parent) {\r
-\r
- composite = new Composite(parent,\r
- SWT.NO_BACKGROUND | SWT.EMBEDDED);\r
- frame = SWT_AWT.new_Frame(composite);\r
-\r
- // Create the chart\r
- displayDefaultChart();\r
-\r
- // Add a dataset listener that updates datasets for the chart according to current selection \r
- sysdynDatasetSelectionListener = new TrendViewSelectionListner(this);\r
-\r
- getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(sysdynDatasetSelectionListener);\r
-\r
- }\r
- \r
- private class TrendViewSelectionListner extends SysdynDatasetSelectionListener {\r
- \r
- private TrendView trendView;\r
- private CustomChartListener listener;\r
-\r
- public TrendViewSelectionListner(TrendView trendView) {\r
- this.trendView = trendView;\r
- }\r
-\r
- @Override\r
- protected void selectionChanged(final Collection<SysdynDataSet> activeDatasets) {\r
- SwingUtilities.invokeLater(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- if(listener != null) {\r
- listener.dispose();\r
- }\r
- trendView.getSysdynDatasets().setDatasets(activeDatasets.toArray(new SysdynDataSet[activeDatasets.size()]));\r
- displayDefaultChart();\r
- }\r
-\r
- });\r
- }\r
-\r
- @Override\r
- protected void selectionChanged(ReadGraph graph, final Resource chartResource) {\r
-\r
- if(listener != null) {\r
- listener.dispose();\r
- }\r
-\r
- listener = new CustomChartListener(trendView);\r
-\r
- graph.asyncRequest(new Read<JFreeChart>() {\r
-\r
- @Override\r
- public JFreeChart perform(ReadGraph graph) throws DatabaseException {\r
- if(graph.hasStatement(chartResource)) {\r
- IJFreeChart chart = graph.adapt(chartResource, IJFreeChart.class);\r
- if(chart != null) {\r
- return chart.getChart();\r
- }\r
- }\r
- return null;\r
- }\r
- }, listener);\r
- }\r
- }\r
-\r
- private class CustomChartListener implements Listener<JFreeChart> {\r
-\r
- private boolean disposed = false;\r
- private TrendView trendView;\r
- \r
- public CustomChartListener(TrendView trendView) {\r
- this.trendView = trendView;\r
- }\r
-\r
- @Override\r
- public void execute(JFreeChart result) {\r
- if(!disposed)\r
- displayChart(result, trendView);\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
-\r
- public void dispose() {\r
- this.disposed = true;\r
- }\r
-\r
- }\r
-\r
- /**\r
- * Displays jFreeChart\r
- * @param jFreeChart\r
- */\r
- private void displayChart(JFreeChart jFreeChart, TrendView trendView) {\r
- SwingUtilities.invokeLater(new RunnableWithObject(jFreeChart, trendView) {\r
-\r
- @Override\r
- public void run() {\r
- if(count() != 2 || getObject(0) == null || getObject(1) == null)\r
- return;\r
- \r
- if(!(getObject(0) instanceof JFreeChart && getObject(1) instanceof TrendView))\r
- return;\r
- \r
- JFreeChart jFreeChart = (JFreeChart) getObject(0);\r
- TrendView trendView = (TrendView) getObject(1);\r
- \r
- Frame frame = trendView.getFrame();\r
- ChartPanel panel = trendView.getPanel();\r
- \r
- // Do not just simply frame.removeAll();\r
- // Instead, use and reuse only the first component of the frame.\r
- if(jFreeChart != null) {\r
- if (panel == null || frame.getComponentCount() == 0){\r
- panel = new ChartPanel(jFreeChart, false, true, true, true, true);\r
- trendView.setPanel(panel);\r
- frame.add(panel);\r
- } else {\r
-// panel.setChart(jFreeChart);\r
- if ( frame.getComponent(0) instanceof ChartPanel ){\r
- ChartPanel tempPanel = (ChartPanel)frame.getComponent(0);\r
- tempPanel.setChart(jFreeChart);\r
- trendView.setPanel(tempPanel);\r
- }\r
- }\r
- }\r
- frame.repaint();\r
- frame.validate();\r
- panel.requestFocusInWindow();\r
- //panel.requestFocus();\r
- }\r
-\r
- });\r
- }\r
-\r
- /**\r
- * displays a default chart\r
- */\r
- private void displayDefaultChart() {\r
- if(defaultchart == null) {\r
- NumberAxis domainAxis = new NumberAxis("time");\r
- domainAxis.setAutoRangeIncludesZero(false);\r
- XYPlot plot = new XYPlot(\r
- sysdynDatasets,\r
- domainAxis,\r
- new NumberAxis(""),\r
- new XYLineAndShapeRenderer(true, false)\r
- );\r
- defaultchart = new JFreeChart(plot);\r
- }\r
- displayChart(defaultchart, this);\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- super.dispose();\r
- getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(sysdynDatasetSelectionListener);\r
- }\r
-\r
- @Override\r
- public void setFocus() {\r
- if(composite != null)\r
- composite.setFocus();\r
- }\r
-\r
-\r
-\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.trend;
+
+import java.awt.Frame;
+import java.util.Collection;
+
+import javax.swing.SwingUtilities;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.awt.SWT_AWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.ui.part.ViewPart;
+import org.jfree.chart.ChartPanel;
+import org.jfree.chart.JFreeChart;
+import org.jfree.chart.axis.NumberAxis;
+import org.jfree.chart.plot.XYPlot;
+import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
+import org.jfree.data.xy.AbstractXYDataset;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.IJFreeChart;
+import org.simantics.sysdyn.manager.SysdynDataSet;
+import org.simantics.sysdyn.ui.viewUtils.SysdynDatasetSelectionListener;
+import org.simantics.utils.RunnableWithObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Trend view that shows all active simulation results for selected variables.
+ *
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class TrendView extends ViewPart {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(TrendView.class);
+
+ private Frame frame;
+ private ChartPanel panel;
+ private SysdynDatasets sysdynDatasets = new SysdynDatasets();
+ private SysdynDatasetSelectionListener sysdynDatasetSelectionListener;
+ private JFreeChart defaultchart;
+ private Composite composite;
+
+
+ public Frame getFrame() {
+ return frame;
+ }
+
+ public ChartPanel getPanel() {
+ return panel;
+ }
+
+ public void setPanel(ChartPanel panel) {
+ this.panel = panel;
+ }
+
+ public SysdynDatasets getSysdynDatasets() {
+ return sysdynDatasets;
+ }
+
+ /**
+ * Dataset for jFreeChart
+ *
+ * @author Teemu Lempinen
+ *
+ */
+ @SuppressWarnings("serial")
+ class SysdynDatasets extends AbstractXYDataset {
+
+ SysdynDataSet[] sets = new SysdynDataSet[0];
+
+ public void setDatasets(SysdynDataSet[] sets) {
+ this.sets = sets;
+ fireDatasetChanged();
+ }
+
+ @Override
+ public Number getY(int series, int item) {
+ return sets[series].values[item];
+ }
+
+ @Override
+ public Number getX(int series, int item) {
+ return sets[series].times[item];
+ }
+
+ @Override
+ public int getItemCount(int series) {
+ return sets[series].times.length;
+ }
+
+ @Override
+ public Comparable<String> getSeriesKey(int series) {
+ SysdynDataSet sds = sets[series];
+ String name = sds.name;
+ if(sds.resultIndex != null)
+ name += "(" + sds.resultIndex + ")";
+ if(sds.result == null)
+ return name;
+ else
+ return name + " : " + sds.result;
+ }
+
+ @Override
+ public int getSeriesCount() {
+ return sets.length;
+ }
+
+ }
+
+ @Override
+ public void createPartControl(Composite parent) {
+
+ composite = new Composite(parent,
+ SWT.NO_BACKGROUND | SWT.EMBEDDED);
+ frame = SWT_AWT.new_Frame(composite);
+
+ // Create the chart
+ displayDefaultChart();
+
+ // Add a dataset listener that updates datasets for the chart according to current selection
+ sysdynDatasetSelectionListener = new TrendViewSelectionListner(this);
+
+ getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(sysdynDatasetSelectionListener);
+
+ }
+
+ private class TrendViewSelectionListner extends SysdynDatasetSelectionListener {
+
+ private TrendView trendView;
+ private CustomChartListener listener;
+
+ public TrendViewSelectionListner(TrendView trendView) {
+ this.trendView = trendView;
+ }
+
+ @Override
+ protected void selectionChanged(final Collection<SysdynDataSet> activeDatasets) {
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run() {
+ if(listener != null) {
+ listener.dispose();
+ }
+ trendView.getSysdynDatasets().setDatasets(activeDatasets.toArray(new SysdynDataSet[activeDatasets.size()]));
+ displayDefaultChart();
+ }
+
+ });
+ }
+
+ @Override
+ protected void selectionChanged(ReadGraph graph, final Resource chartResource) {
+
+ if(listener != null) {
+ listener.dispose();
+ }
+
+ listener = new CustomChartListener(trendView);
+ graph.getSession().asyncRequest((Read<JFreeChart>) g -> {
+ if (g.hasStatement(chartResource)) {
+ IJFreeChart chart = g.adapt(chartResource, IJFreeChart.class);
+ if (chart != null) {
+ return chart.getChart();
+ }
+ }
+ return null;
+ }, listener);
+ }
+ }
+
+ private class CustomChartListener implements Listener<JFreeChart> {
+
+ private boolean disposed = false;
+ private TrendView trendView;
+
+ public CustomChartListener(TrendView trendView) {
+ this.trendView = trendView;
+ }
+
+ @Override
+ public void execute(JFreeChart result) {
+ if(!disposed)
+ displayChart(result, trendView);
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ LOGGER.error("JFreeChart adaption failed", t);
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+
+ public void dispose() {
+ this.disposed = true;
+ }
+
+ }
+
+ /**
+ * Displays jFreeChart
+ * @param jFreeChart
+ */
+ private void displayChart(JFreeChart jFreeChart, TrendView trendView) {
+ SwingUtilities.invokeLater(new RunnableWithObject(jFreeChart, trendView) {
+
+ @Override
+ public void run() {
+ if(count() != 2 || getObject(0) == null || getObject(1) == null)
+ return;
+
+ if(!(getObject(0) instanceof JFreeChart && getObject(1) instanceof TrendView))
+ return;
+
+ JFreeChart jFreeChart = (JFreeChart) getObject(0);
+ TrendView trendView = (TrendView) getObject(1);
+
+ Frame frame = trendView.getFrame();
+ ChartPanel panel = trendView.getPanel();
+
+ // Do not just simply frame.removeAll();
+ // Instead, use and reuse only the first component of the frame.
+ if(jFreeChart != null) {
+ if (panel == null || frame.getComponentCount() == 0){
+ panel = new ChartPanel(jFreeChart, false, true, true, true, true);
+ trendView.setPanel(panel);
+ frame.add(panel);
+ } else {
+// panel.setChart(jFreeChart);
+ if ( frame.getComponent(0) instanceof ChartPanel ){
+ ChartPanel tempPanel = (ChartPanel)frame.getComponent(0);
+ tempPanel.setChart(jFreeChart);
+ trendView.setPanel(tempPanel);
+ }
+ }
+ }
+ frame.repaint();
+ frame.validate();
+ panel.requestFocusInWindow();
+ //panel.requestFocus();
+ }
+
+ });
+ }
+
+ /**
+ * displays a default chart
+ */
+ private void displayDefaultChart() {
+ if(defaultchart == null) {
+ NumberAxis domainAxis = new NumberAxis("time");
+ domainAxis.setAutoRangeIncludesZero(false);
+ XYPlot plot = new XYPlot(
+ sysdynDatasets,
+ domainAxis,
+ new NumberAxis(""),
+ new XYLineAndShapeRenderer(true, false)
+ );
+ defaultchart = new JFreeChart(plot);
+ }
+ displayChart(defaultchart, this);
+ }
+
+ @Override
+ public void dispose() {
+ super.dispose();
+ getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(sysdynDatasetSelectionListener);
+ }
+
+ @Override
+ public void setFocus() {
+ if(composite != null)
+ composite.setFocus();
+ }
+
+
+
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.trend;\r
-\r
-import java.awt.BasicStroke;\r
-import java.awt.Color;\r
-import java.awt.Paint;\r
-import java.awt.Stroke;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import javax.swing.SwingUtilities;\r
-\r
-import org.jfree.chart.ChartColor;\r
-import org.jfree.chart.labels.StandardXYToolTipGenerator;\r
-import org.jfree.chart.plot.DefaultDrawingSupplier;\r
-import org.jfree.chart.plot.ValueMarker;\r
-import org.jfree.chart.renderer.AbstractRenderer;\r
-import org.jfree.chart.renderer.xy.AbstractXYItemRenderer;\r
-import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;\r
-import org.jfree.data.general.Dataset;\r
-import org.jfree.data.xy.DefaultXYDataset;\r
-import org.jfree.ui.Layer;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.procedure.adapter.DisposableListener;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.exception.MissingVariableException;\r
-import org.simantics.db.layer0.request.PossibleActiveExperiment;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.jfreechart.chart.AbstractDataset;\r
-import org.simantics.jfreechart.chart.IRenderer;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.sysdyn.Functions;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-/**\r
- * Class representing a JFreeChart.XYDataset\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class XYDataset extends AbstractDataset implements org.simantics.jfreechart.chart.XYDataset{\r
-\r
- protected IRenderer renderer;\r
-\r
- public XYDataset(ReadGraph graph, final Resource datasetResource) throws DatabaseException {\r
- super(graph, datasetResource);\r
- }\r
-\r
- protected Dataset dataset;\r
- protected DisposableListener<?> datasetListener;\r
- protected DisposableListener<Double> timeListener;\r
- \r
- protected DisposableListener<Double> getTimeListener() {\r
- if(timeListener == null || timeListener.isDisposed()) {\r
- timeListener = new TimeListener();\r
- }\r
- return timeListener;\r
- }\r
- \r
- protected Read<Double> getTimeRequest() {\r
- return new Read<Double>() {\r
- @Override\r
- public Double perform(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- // Get properties for all series\r
- Resource series = graph.getPossibleObject(resource, jfree.Dataset_seriesList);\r
- if(series != null) {\r
- List<Resource> seriesList = ListUtils.toList(graph, series);\r
- if(seriesList != null) {\r
- String realizationURI = getRealizationURI(graph, resource);\r
- for(Resource r : seriesList) {\r
- String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);\r
- if(rvi == null)\r
- continue;\r
- try {\r
- // Get a variable for the experiment run\r
- Variable v = Variables.getVariable(graph, realizationURI);\r
- if(v == null)\r
- return null;\r
- Variable timeVar = v.browsePossible(graph, "#" + Functions.TIME + "#");\r
- if(timeVar != null)\r
- return timeVar.getValue(graph, Bindings.DOUBLE);\r
- } catch (MissingVariableException e) {\r
- // Do nothing, if variable was not found.\r
- }\r
- }\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- };\r
- }\r
-\r
- @SuppressWarnings("unchecked")\r
- @Override\r
- public Dataset getDataset() {\r
- if(dataset == null) {\r
- dataset = new DefaultXYDataset();\r
- } \r
-\r
- if(datasetListener == null || datasetListener.isDisposed()) {\r
- datasetListener = new DataSetListener();\r
- SimanticsUI.getSession().asyncRequest(\r
- new XYDatasetRequest(resource), \r
- (DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, IRenderer>>) datasetListener); \r
-\r
- }\r
-\r
- if(timeListener == null || timeListener.isDisposed()) {\r
- SimanticsUI.getSession().asyncRequest(getTimeRequest(), getTimeListener());\r
- }\r
- return dataset;\r
- }\r
-\r
- /**\r
- * Class for identifying a time marker in a plot\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- protected class TimeMarker extends ValueMarker {\r
- private static final long serialVersionUID = 2018755066561629172L;\r
-\r
- public TimeMarker(double value, Paint paint, Stroke stroke) {\r
- super(value, paint, stroke);\r
- }\r
- }\r
-\r
- private class DataSetListener extends DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, IRenderer>> {\r
-\r
- @Override\r
- public void execute(Pair<ArrayList<XYDatasetTempSeries>, IRenderer> result) {\r
- final ArrayList<XYDatasetTempSeries> series = result.first;\r
- renderer = result.second;\r
- \r
- // Modify series in AWT thread to avoid synchronization problems\r
- SwingUtilities.invokeLater(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
-\r
- if(dataset == null || !(dataset instanceof DefaultXYDataset))\r
- return;\r
- \r
- DefaultXYDataset ds = (DefaultXYDataset)dataset;\r
- org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();\r
- \r
- if(plot != null) {\r
- /*\r
- * Drawing supplier with a modified first yellow. The default first\r
- * yellow is too light to be visible against a white background\r
- */\r
- Paint[] paintSequence = ChartColor.createDefaultPaintArray();\r
- paintSequence[3] = new Color(0xFF, 0xDD, 0x00);\r
- DefaultDrawingSupplier drawingsupplier = new DefaultDrawingSupplier(\r
- paintSequence,\r
- DefaultDrawingSupplier.DEFAULT_FILL_PAINT_SEQUENCE,\r
- DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,\r
- DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,\r
- DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,\r
- DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);\r
- plot.setDrawingSupplier(drawingsupplier);\r
- }\r
- // Remove all series\r
- for(int i = ds.getSeriesCount() - 1; i >= 0; i-- ) {\r
- ds.removeSeries(ds.getSeriesKey(i));\r
- }\r
-\r
- // Add found series\r
- for(int i = 0; i < series.size(); i++) {\r
- XYDatasetTempSeries s = series.get(i);\r
- String name = s.name;\r
- if(ds.indexOf(name) >= 0)\r
- name = name + (i + 1);\r
- ds.addSeries(name, s.values);\r
- getRenderer().setSeriesStroke(i, new BasicStroke((float)s.width));\r
- getRenderer().setSeriesPaint(i, s.color);\r
- } \r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- }\r
-\r
-\r
- /**\r
- * Listener for updating the time indicator for XY plots\r
- * @author Teemu Lempinen\r
- *\r
- */\r
- protected class TimeListener extends DisposableListener<Double> {\r
-\r
- private ValueMarker marker;\r
- private Stroke dashStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,\r
- BasicStroke.JOIN_MITER, 10.0f, new float[] {5.0f, 3.0f, 1.0f, 3.0f}, 0.0f);\r
-\r
- public TimeListener() {\r
- this.marker = new TimeMarker(0.0, Color.red, dashStroke);\r
- }\r
-\r
- public void dispose() {\r
- super.dispose();\r
- if(marker != null) {\r
- org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();\r
- if(plot != null)\r
- plot.removeDomainMarker(marker);\r
- }\r
- }\r
-\r
- @Override\r
- public void execute(final Double time) {\r
- // Modify in AWT thread to avoid synchronization problems\r
- SwingUtilities.invokeLater(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();\r
-\r
- if(plot == null)\r
- return;\r
-\r
- plot.removeDomainMarker(marker);\r
- if(time != null) {\r
- marker.setValue(time);\r
- if(plot.getDomainMarkers(Layer.FOREGROUND) == null || !plot.getDomainMarkers(Layer.FOREGROUND).contains(marker)) {\r
- int i = 0;\r
- for(i = 0; i < plot.getDatasetCount(); i++) {\r
- if(plot.getDataset(i) != null && plot.getDataset(i).equals(dataset))\r
- break;\r
- }\r
- plot.addDomainMarker(i, marker, Layer.FOREGROUND);\r
- }\r
- }\r
-\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- }\r
-\r
- @Override\r
- public void dispose() {\r
- if(timeListener != null) {\r
- timeListener.dispose();\r
- timeListener = null;\r
- }\r
-\r
- if(datasetListener != null) {\r
- datasetListener.dispose();\r
- datasetListener = null;\r
- }\r
- }\r
-\r
-\r
- @Override\r
- public AbstractRenderer getRenderer() {\r
- if(renderer == null) {\r
-\r
- try {\r
- renderer = SimanticsUI.getSession().syncRequest(new Read<IRenderer>() {\r
-\r
- @Override\r
- public IRenderer perform(ReadGraph graph) throws DatabaseException {\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- IRenderer renderer = null;\r
- Resource rendererResource = graph.getPossibleObject(resource, jfree.Dataset_renderer);\r
- if(rendererResource != null)\r
- renderer = graph.adapt(rendererResource, IRenderer.class);\r
- return renderer;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- }\r
- if(renderer == null) {\r
- XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);\r
- renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());\r
- return renderer;\r
- } else {\r
- return renderer.getRenderer();\r
- }\r
- } else {\r
- return renderer.getRenderer();\r
- }\r
- }\r
-\r
- /**\r
- * Get the realization uri of the current dataset resource\r
- * @param graph ReadGraph\r
- * @return realization uri for current dataset resource\r
- * @throws DatabaseException\r
- */\r
- public static String getRealizationURI(ReadGraph graph, Resource resource) throws DatabaseException {\r
- if(resource == null)\r
- return null;\r
-\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
-\r
- // Find the model where the chart is located\r
- Resource model = resource;\r
- do {\r
- model = graph.getPossibleObject(model, l0.PartOf);\r
- } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));\r
-\r
- if(model == null)\r
- return null;\r
-\r
- // Find the variable realization of the current experiment\r
- String realizationURI = null;\r
- Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));\r
- if (realization == null) {\r
- Layer0X L0X = Layer0X.getInstance(graph);\r
- realization = graph.getPossibleObject(model, L0X.HasBaseRealization);\r
- }\r
- if (realization != null)\r
- realizationURI = graph.getURI(realization);\r
-\r
- return realizationURI;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.trend;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Paint;
+import java.awt.Stroke;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.SwingUtilities;
+
+import org.jfree.chart.ChartColor;
+import org.jfree.chart.labels.StandardXYToolTipGenerator;
+import org.jfree.chart.plot.DefaultDrawingSupplier;
+import org.jfree.chart.plot.ValueMarker;
+import org.jfree.chart.renderer.AbstractRenderer;
+import org.jfree.chart.renderer.xy.AbstractXYItemRenderer;
+import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
+import org.jfree.data.general.Dataset;
+import org.jfree.data.xy.DefaultXYDataset;
+import org.jfree.ui.Layer;
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.procedure.adapter.DisposableListener;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.exception.MissingVariableException;
+import org.simantics.db.layer0.request.PossibleActiveExperiment;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.request.Read;
+import org.simantics.jfreechart.chart.AbstractDataset;
+import org.simantics.jfreechart.chart.IRenderer;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.operation.Layer0X;
+import org.simantics.sysdyn.Functions;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.utils.datastructures.Pair;
+
+/**
+ * Class representing a JFreeChart.XYDataset
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class XYDataset extends AbstractDataset implements org.simantics.jfreechart.chart.XYDataset{
+
+ protected IRenderer renderer;
+
+ public XYDataset(ReadGraph graph, final Resource datasetResource) throws DatabaseException {
+ super(graph, datasetResource);
+ }
+
+ protected Dataset dataset;
+ protected DisposableListener<?> datasetListener;
+ protected DisposableListener<Double> timeListener;
+
+ protected DisposableListener<Double> getTimeListener() {
+ if(timeListener == null || timeListener.isDisposed()) {
+ timeListener = new TimeListener();
+ }
+ return timeListener;
+ }
+
+ protected Read<Double> getTimeRequest() {
+ return new Read<Double>() {
+ @Override
+ public Double perform(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ // Get properties for all series
+ Resource series = graph.getPossibleObject(resource, jfree.Dataset_seriesList);
+ if(series != null) {
+ List<Resource> seriesList = ListUtils.toList(graph, series);
+ if(seriesList != null) {
+ String realizationURI = getRealizationURI(graph, resource);
+ for(Resource r : seriesList) {
+ String rvi = graph.getPossibleRelatedValue(r, jfree.variableRVI);
+ if(rvi == null)
+ continue;
+ try {
+ // Get a variable for the experiment run
+ Variable v = Variables.getVariable(graph, realizationURI);
+ if(v == null)
+ return null;
+ Variable timeVar = v.browsePossible(graph, "#" + Functions.TIME + "#");
+ if(timeVar != null)
+ return timeVar.getValue(graph, Bindings.DOUBLE);
+ } catch (MissingVariableException e) {
+ // Do nothing, if variable was not found.
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ };
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Dataset getDataset() {
+ if(dataset == null) {
+ dataset = new DefaultXYDataset();
+ }
+
+ if(datasetListener == null || datasetListener.isDisposed()) {
+ datasetListener = new DataSetListener();
+ Simantics.getSession().asyncRequest(
+ new XYDatasetRequest(resource),
+ (DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, IRenderer>>) datasetListener);
+
+ }
+
+ if(timeListener == null || timeListener.isDisposed()) {
+ Simantics.getSession().asyncRequest(getTimeRequest(), getTimeListener());
+ }
+ return dataset;
+ }
+
+ /**
+ * Class for identifying a time marker in a plot
+ * @author Teemu Lempinen
+ *
+ */
+ protected class TimeMarker extends ValueMarker {
+ private static final long serialVersionUID = 2018755066561629172L;
+
+ public TimeMarker(double value, Paint paint, Stroke stroke) {
+ super(value, paint, stroke);
+ }
+ }
+
+ private class DataSetListener extends DisposableListener<Pair<ArrayList<XYDatasetTempSeries>, IRenderer>> {
+
+ @Override
+ public void execute(Pair<ArrayList<XYDatasetTempSeries>, IRenderer> result) {
+ final ArrayList<XYDatasetTempSeries> series = result.first;
+ renderer = result.second;
+
+ // Modify series in AWT thread to avoid synchronization problems
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run() {
+
+ if(dataset == null || !(dataset instanceof DefaultXYDataset))
+ return;
+
+ DefaultXYDataset ds = (DefaultXYDataset)dataset;
+ org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();
+
+ if(plot != null) {
+ /*
+ * Drawing supplier with a modified first yellow. The default first
+ * yellow is too light to be visible against a white background
+ */
+ Paint[] paintSequence = ChartColor.createDefaultPaintArray();
+ paintSequence[3] = new Color(0xFF, 0xDD, 0x00);
+ DefaultDrawingSupplier drawingsupplier = new DefaultDrawingSupplier(
+ paintSequence,
+ DefaultDrawingSupplier.DEFAULT_FILL_PAINT_SEQUENCE,
+ DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
+ DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
+ DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
+ DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
+ plot.setDrawingSupplier(drawingsupplier);
+ }
+ // Remove all series
+ for(int i = ds.getSeriesCount() - 1; i >= 0; i-- ) {
+ ds.removeSeries(ds.getSeriesKey(i));
+ }
+
+ // Add found series
+ for(int i = 0; i < series.size(); i++) {
+ XYDatasetTempSeries s = series.get(i);
+ String name = s.name;
+ if(ds.indexOf(name) >= 0)
+ name = name + (i + 1);
+ ds.addSeries(name, s.values);
+ getRenderer().setSeriesStroke(i, new BasicStroke((float)s.width));
+ getRenderer().setSeriesPaint(i, s.color);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ }
+
+
+ /**
+ * Listener for updating the time indicator for XY plots
+ * @author Teemu Lempinen
+ *
+ */
+ protected class TimeListener extends DisposableListener<Double> {
+
+ private ValueMarker marker;
+ private Stroke dashStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
+ BasicStroke.JOIN_MITER, 10.0f, new float[] {5.0f, 3.0f, 1.0f, 3.0f}, 0.0f);
+
+ public TimeListener() {
+ this.marker = new TimeMarker(0.0, Color.red, dashStroke);
+ }
+
+ public void dispose() {
+ super.dispose();
+ if(marker != null) {
+ org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();
+ if(plot != null)
+ plot.removeDomainMarker(marker);
+ }
+ }
+
+ @Override
+ public void execute(final Double time) {
+ // Modify in AWT thread to avoid synchronization problems
+ SwingUtilities.invokeLater(new Runnable() {
+
+ @Override
+ public void run() {
+ org.jfree.chart.plot.XYPlot plot = ((AbstractXYItemRenderer)getRenderer()).getPlot();
+
+ if(plot == null)
+ return;
+
+ plot.removeDomainMarker(marker);
+ if(time != null) {
+ marker.setValue(time);
+ if(plot.getDomainMarkers(Layer.FOREGROUND) == null || !plot.getDomainMarkers(Layer.FOREGROUND).contains(marker)) {
+ int i = 0;
+ for(i = 0; i < plot.getDatasetCount(); i++) {
+ if(plot.getDataset(i) != null && plot.getDataset(i).equals(dataset))
+ break;
+ }
+ plot.addDomainMarker(i, marker, Layer.FOREGROUND);
+ }
+ }
+
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ }
+
+ @Override
+ public void dispose() {
+ if(timeListener != null) {
+ timeListener.dispose();
+ timeListener = null;
+ }
+
+ if(datasetListener != null) {
+ datasetListener.dispose();
+ datasetListener = null;
+ }
+ }
+
+
+ @Override
+ public AbstractRenderer getRenderer() {
+ if(renderer == null) {
+
+ try {
+ renderer = Simantics.getSession().syncRequest(new Read<IRenderer>() {
+
+ @Override
+ public IRenderer perform(ReadGraph graph) throws DatabaseException {
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ IRenderer renderer = null;
+ Resource rendererResource = graph.getPossibleObject(resource, jfree.Dataset_renderer);
+ if(rendererResource != null)
+ renderer = graph.adapt(rendererResource, IRenderer.class);
+ return renderer;
+ }
+ });
+ } catch (DatabaseException e) {
+ }
+ if(renderer == null) {
+ XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
+ renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
+ return renderer;
+ } else {
+ return renderer.getRenderer();
+ }
+ } else {
+ return renderer.getRenderer();
+ }
+ }
+
+ /**
+ * Get the realization uri of the current dataset resource
+ * @param graph ReadGraph
+ * @return realization uri for current dataset resource
+ * @throws DatabaseException
+ */
+ public static String getRealizationURI(ReadGraph graph, Resource resource) throws DatabaseException {
+ if(resource == null)
+ return null;
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+
+ // Find the model where the chart is located
+ Resource model = resource;
+ do {
+ model = graph.getPossibleObject(model, l0.PartOf);
+ } while(model != null && !graph.isInstanceOf(model, mr.StructuralModel));
+
+ if(model == null)
+ return null;
+
+ // Find the variable realization of the current experiment
+ String realizationURI = null;
+ Resource realization = graph.syncRequest(new PossibleActiveExperiment(model));
+ if (realization == null) {
+ Layer0X L0X = Layer0X.getInstance(graph);
+ realization = graph.getPossibleObject(model, L0X.HasBaseRealization);
+ }
+ if (realization != null)
+ realizationURI = graph.getURI(realization);
+
+ return realizationURI;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.utils;\r
-\r
-import java.io.StringReader;\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.HashSet;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Set;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-\r
-import org.eclipse.jface.resource.ColorDescriptor;\r
-import org.eclipse.jface.resource.LocalResourceManager;\r
-import org.eclipse.jface.text.Position;\r
-import org.eclipse.swt.custom.StyledText;\r
-import org.eclipse.swt.graphics.Color;\r
-import org.eclipse.swt.graphics.RGB;\r
-import org.eclipse.swt.widgets.Table;\r
-import org.eclipse.swt.widgets.TableItem;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
-import org.simantics.sysdyn.expressionParser.ParseException;\r
-import org.simantics.sysdyn.expressionParser.Token;\r
-import org.simantics.sysdyn.expressionParser.TokenMgrError;\r
-import org.simantics.sysdyn.manager.SysdynModel;\r
-import org.simantics.sysdyn.manager.SysdynModelManager;\r
-import org.simantics.sysdyn.modelica.ModelicaWriter;\r
-import org.simantics.sysdyn.representation.Configuration;\r
-import org.simantics.sysdyn.representation.Enumeration;\r
-import org.simantics.sysdyn.representation.EnumerationIndex;\r
-import org.simantics.sysdyn.representation.IElement;\r
-import org.simantics.sysdyn.representation.Model;\r
-import org.simantics.sysdyn.representation.Module;\r
-import org.simantics.sysdyn.representation.Sheet;\r
-import org.simantics.sysdyn.representation.Variable;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;\r
-import org.simantics.sysdyn.ui.properties.widgets.expressions.IExpression;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ExpressionUtils {\r
-\r
- /**\r
- * Determines if the given expression is a parameter expression. Parameters are numbers.\r
- * If the expression contains anything other than numbers, it is not a parameter.\r
- * \r
- * @param expression The expression to be checked\r
- * @return is the expression a parameter\r
- */\r
- static public boolean isParameter(String expression) {\r
- try {\r
- /*\r
- StringTokenizer st = new StringTokenizer(expression, "{}[],;");\r
- while(st.hasMoreTokens()) {\r
- Double.parseDouble(st.nextToken().trim());\r
- }\r
- */\r
- Double.parseDouble(expression.trim());\r
- return true;\r
- } catch (NumberFormatException e) {\r
- return false;\r
- }\r
- }\r
- \r
- /**\r
- * Color for a variable found in an expression field, used in shortcut tab.\r
- * This is a bit silly means of communicating the state of a variable using its color.\r
- * @param resourceManager LocalResourceManager for which the color is created.\r
- * @return Color for such variable.\r
- */\r
- public static Color variableFoundColor(LocalResourceManager resourceManager) {\r
- return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(0,0,0)));\r
- }\r
- \r
- /**\r
- * Color for a variable not found in an expression field, used in shortcut tab.\r
- * This is a bit silly means of communicating the state of a variable using its color.\r
- * @param resourceManager LocalResourceManager for which the color is created.\r
- * @return Color for such variable.\r
- */\r
- public static Color variableNotFoundColor(LocalResourceManager resourceManager) {\r
- return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(255,125,0)));\r
- }\r
- \r
- /**\r
- * Color for a variable itself and for the time variable, used in shortcut tab.\r
- * This is a bit silly means of communicating the state of a variable using its color.\r
- * @param resourceManager LocalResourceManager for which the color is created.\r
- * @return Color for such variable.\r
- */\r
- public static Color variableTimeAndSelfColor(LocalResourceManager resourceManager) {\r
- return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(127,127,127)));\r
- }\r
- \r
- /**\r
- * Validates the expressionfield of a given IExpression\r
- * \r
- * @param expression The expression whose fields are validated\r
- * @param resourceManager \r
- * @param connectedVariables Table items from the shortcut widget. (Items needed so that they can be coloured)\r
- * @param configuration configuration where the variable is located\r
- */\r
- static public void validateExpressionFields(final Resource variable, \r
- IExpression expression, \r
- Table variableTable, \r
- LocalResourceManager resourceManager) {\r
- if(variable == null || expression == null || variableTable == null)\r
- return;\r
- \r
- Resource configuration = null;\r
- try {\r
- configuration = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource configuration = variable;\r
- while (configuration != null) {\r
- configuration = graph.getPossibleObject(configuration, Layer0.getInstance(graph).PartOf);\r
-\r
- if(configuration == null || graph.isInstanceOf(configuration, sr.Configuration)) {\r
- break;\r
- }\r
- }\r
- return configuration;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- return;\r
- }\r
-\r
- if(configuration == null)\r
- return;\r
-\r
- ExpressionParser parser = new ExpressionParser(new StringReader(""));\r
- Set<String> variables = new HashSet<String>();\r
- HashMap<ExpressionField, HashMap<String, List<Token>>> references = new HashMap<ExpressionField, HashMap<String, List<Token>>>();\r
- final HashMap<ExpressionField, HashMap<String, List<List<Token>>>> ranges = new HashMap<ExpressionField, HashMap<String, List<List<Token>>>>();\r
- HashMap<ExpressionField, HashMap<Token, List<Token>>> forIndices = new HashMap<ExpressionField, HashMap<Token, List<Token>>>();\r
- HashMap<ExpressionField, HashMap<String, List<Token>>> enumerationReferences = new HashMap<ExpressionField, HashMap<String, List<Token>>>();\r
- HashMap<ExpressionField, HashMap<String, List<Token>>> functionReferences = new HashMap<ExpressionField, HashMap<String, List<Token>>>();\r
-\r
- // Build references and variable array\r
- boolean parsingSucceeded = false;\r
- for(ExpressionField ef : expression.getExpressionFields()) {\r
- ef.resetAnnotations();\r
- String textString = ef.getExpression();\r
- parser.ReInit(new StringReader(textString));\r
- try {\r
- parser.expr();\r
- HashMap<String, List<Token>> refs = parser.getReferences();\r
- references.put(ef, refs);\r
- variables.addAll(refs.keySet());\r
-\r
- ranges.put(ef, parser.getRanges());\r
-\r
- forIndices.put(ef, parser.getForIndices());\r
-\r
- enumerationReferences.put(ef, parser.getEnumerationReferences());\r
-\r
- functionReferences.put(ef, parser.getFunctionCallReferences());\r
-\r
- parsingSucceeded = true;\r
- } catch (ParseException e1) {\r
- ef.setSyntaxError(new SyntaxError(e1.currentToken, "Syntax Error"));\r
- \r
- /* \r
- * If the equation is empty, set the parsingSucceeded = true\r
- * to allow the coloring of the variables succeed. \r
- */\r
- if (textString.equals("")) {\r
- parsingSucceeded = true;\r
- }\r
- } catch (TokenMgrError err) {\r
- ef.setSyntaxError(new SyntaxError(0, textString.length(), ExpressionField.SYNTAX_ERROR, "Expression contains unsupported characters"));\r
- }\r
- }\r
-\r
-\r
- // Get model configuration\r
- SysdynModelManager sdm = SysdynModelManager.getInstance(SimanticsUI.getSession());\r
- SysdynModel model = sdm.getModel(configuration);\r
-// try {\r
-// model.update();\r
-// } catch (DatabaseException e1) {\r
-// e1.printStackTrace();\r
-// }\r
- Configuration conf = model.getConfiguration();\r
- \r
- // Check variable references\r
- final HashMap<String, Variable> modelVariables = new HashMap<String, Variable>();\r
- HashSet<String> ignoreVariables = new HashSet<String>();\r
- if(!variables.isEmpty() || !functionReferences.isEmpty()) {\r
- Set<String> noSuchVariables = new HashSet<String>();\r
- ArrayList<IElement> elements = conf.getElements();\r
- for(IElement e : elements) {\r
- if(e instanceof Variable) {\r
- Variable v = (Variable) e;\r
- modelVariables.put(v.getName(), v);\r
- } else if(e instanceof Module) {\r
- ignoreVariables.add(((Module)e).getName());\r
- }\r
- }\r
-\r
- // Handle reserved variables later\r
- variables.remove(ModelicaWriter.VAR_TIME);\r
- variables.remove(ModelicaWriter.VAR_START);\r
- variables.remove(ModelicaWriter.VAR_STOP);\r
- variables.remove(ModelicaWriter.VAR_STEP);\r
- \r
- // Remove variable references to for indices\r
- for(ExpressionField ef : forIndices.keySet()) {\r
- for(Token t : forIndices.get(ef).keySet()) {\r
- if(variables.contains(t.image))\r
- variables.remove(t.image);\r
- }\r
- }\r
-\r
- // Examine sheets\r
- for(ExpressionField ef : functionReferences.keySet()) {\r
- for(String key : functionReferences.get(ef).keySet()) {\r
- \r
- List<SyntaxError> errors = examineSheetReferences(conf, key, functionReferences.get(ef).get(key), ef.getExpression(), references.get(ef));\r
- if(errors != null) {\r
- for(SyntaxError error : errors)\r
- ef.setSyntaxError(error);\r
- }\r
- }\r
- }\r
-\r
- // Examine variable references\r
- for(String v : variables) {\r
- ReferenceOption option = getReferenceOption(conf, v);\r
- switch(option) {\r
- case DOES_NOT_EXIST:\r
- noSuchVariables.add(v);\r
- break;\r
- case CANNOT_BE_CONNECTED:\r
- ignoreVariables.add(v);\r
- break;\r
- case CAN_BE_CONNECTED:\r
- }\r
- }\r
-\r
- if(!noSuchVariables.isEmpty()) {\r
- noSuchVariables.removeAll(ignoreVariables);\r
- // remove no such variables from variable list\r
- for(String s : noSuchVariables)\r
- variables.remove(s);\r
- // create annotations\r
- HashMap<ExpressionField ,ArrayList<Position>> positions = getPositionsForVariables(references, noSuchVariables);\r
- for(ExpressionField ef : positions.keySet()) {\r
- ef.setNoSuchVariableAnnotations(positions.get(ef));\r
- }\r
- } \r
- }\r
-\r
- // Check that the variables that exist have connections and the connected variables have references in the expressions\r
- // If there are syntax errors, keep the previous coloring.\r
- String selfName = null;\r
- if(variableTable != null && !variableTable.isDisposed()) {\r
- \r
- // Get the name of the variable itself\r
- try {\r
- selfName = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Object selfName = graph.getPossibleRelatedValue(variable, l0.HasName);\r
- if(selfName != null) {\r
- return (String)selfName;\r
- }\r
- return null;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- // Color the items in the table\r
- TableItem[] connectedVariables = variableTable.getItems();\r
- for(TableItem ti : connectedVariables) {\r
- String text = ti.getText();\r
- if (text.equals(ModelicaWriter.VAR_TIME) || \r
- text.equals(ModelicaWriter.VAR_START) || \r
- text.equals(ModelicaWriter.VAR_STOP) || \r
- text.equals(ModelicaWriter.VAR_STEP) || \r
- text.equals(selfName)) {\r
- ti.setForeground(variableTimeAndSelfColor(resourceManager));\r
- } else if (parsingSucceeded && !variables.contains(text)) {\r
- ti.setForeground(variableNotFoundColor(resourceManager));\r
- } else if (parsingSucceeded) {\r
- ti.setForeground(variableFoundColor(resourceManager));\r
- variables.remove(text);\r
- }\r
- }\r
-\r
- // Remove all enumerations and sheets, they cannot have connections\r
- variables.removeAll(ignoreVariables);\r
-\r
- // Always remove self\r
- variables.remove(selfName);\r
-\r
- if(!variables.isEmpty()) {\r
- HashMap<ExpressionField ,ArrayList<Position>> positions = getPositionsForVariables(references, variables);\r
- for(ExpressionField ef : positions.keySet()) {\r
- ef.setMissingLinkAnnotations(positions.get(ef));\r
- }\r
-\r
- }\r
- } \r
-\r
- for(final ExpressionField ef : ranges.keySet()) {\r
- List<SyntaxError> errors = new ArrayList<SyntaxError>();\r
- // RANGES\r
- errors.addAll(examineArrayRanges(conf, ranges.get(ef), forIndices.get(ef)));\r
- \r
- // ENUMERATION REFERENCES IN FOR-LOOPS\r
- errors.addAll(examineEnumerationReferences(conf, enumerationReferences.get(ef)));\r
-\r
- for(SyntaxError error : errors) {\r
- ef.setSyntaxError(error);\r
- }\r
- } \r
- }\r
- \r
- \r
- static public List<SyntaxError> examineArrayRanges(\r
- final Configuration configuration,\r
- final HashMap<String, List<List<Token>>> ranges,\r
- final HashMap<Token, List<Token>> forIndices) {\r
- \r
- List<SyntaxError> result = Collections.emptyList();\r
- try {\r
- result = SimanticsUI.getSession().syncRequest(new Read<List<SyntaxError>>() {\r
-\r
- @Override\r
- public List<SyntaxError> perform(ReadGraph graph) throws DatabaseException {\r
- return examineArrayRanges(graph, configuration, ranges, forIndices);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return result;\r
- }\r
-\r
- static public List<SyntaxError> examineEnumerationReferences(Configuration configuration, HashMap<String, List<Token>> enumRefList) {\r
- ArrayList<SyntaxError> result = new ArrayList<SyntaxError>();\r
- for(String enumeration : enumRefList.keySet()) {\r
- for(Token et : enumRefList.get(enumeration)) {\r
- Object o = getElement(configuration, enumeration);\r
- if(o != null && o instanceof Enumeration) {\r
- boolean isFound = false;\r
- Enumeration e = (Enumeration)o;\r
-\r
- if(enumeration.equals(et.image) ||\r
- "size".equals(et.image) || \r
- "elements".equals(et.image)){\r
- // The full enumeration\r
- isFound = true;\r
- } else {\r
- for(EnumerationIndex ei : e.getEnumerationIndexes()) {\r
- if(ei.getName().equals(et.image)) {\r
- isFound = true;\r
- break;\r
- }\r
- }\r
- }\r
-\r
- if(!isFound) {\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Enumeration ");\r
- sb.append(enumeration);\r
- sb.append(" has no such index.\nAvailable indexes are: ");\r
- Iterator<EnumerationIndex> iterator = e.getEnumerationIndexes().iterator();\r
- while(iterator.hasNext()) {\r
- sb.append(iterator.next().getName());\r
- if(iterator.hasNext()) \r
- sb.append(", ");\r
- }\r
- result.add(new SyntaxError(et, sb.toString()));\r
- }\r
-\r
-\r
- } else {\r
- result.add(new SyntaxError(et, "No such enumeration (" + enumeration + ")")); \r
- }\r
- }\r
- }\r
- return result;\r
- }\r
-\r
- /**\r
- * \r
- * @param graph\r
- * @param configuration\r
- * @param ranges\r
- * @param forIndices\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- static public List<SyntaxError> examineArrayRanges(\r
- ReadGraph graph, \r
- Configuration configuration,\r
- HashMap<String, List<List<Token>>> ranges,\r
- HashMap<Token, List<Token>> forIndices) throws DatabaseException {\r
- HashMap<Token, SyntaxError> errors = new HashMap<Token, SyntaxError>();\r
- for(String name : ranges.keySet()) {\r
- if(ranges.get(name) != null) {\r
- for(List<Token> l : ranges.get(name)) {\r
- String[] rangeReferences = new String[l.size()];\r
- for(int i = 0; i < l.size(); i++) {\r
- rangeReferences[i] = l.get(i).image;\r
- }\r
-\r
- Object o = getElement(configuration, name);\r
- if(o != null && o instanceof Variable) {\r
- Map<Integer, SyntaxError> invalidRanges = ArrayVariableUtils.isRangeValid(graph, (Variable)o, rangeReferences);\r
- if(invalidRanges != null && !invalidRanges.isEmpty()) {\r
- for(Integer i : invalidRanges.keySet()) {\r
- SyntaxError error = invalidRanges.get(i);\r
- error.setToken(l.get(i));\r
- errors.put(l.get(i), error);\r
- }\r
- }\r
- }\r
- }\r
- }\r
- } \r
-\r
-\r
- // FOR-INDICES\r
-\r
- HashSet<Token> removes = new HashSet<Token>();\r
- for(Token t : forIndices.keySet()) {\r
-// boolean isFound = false;\r
- for(Token rt : errors.keySet()) {\r
- if(rt.image.equals(t.image)) {\r
-// isFound = true;\r
- // remove range token from invalid ranges\r
- removes.add(rt);\r
- }\r
- }\r
-// Why would this be invalid if the index just is not used anywhere?\r
-// {1+2 for i in range} \r
- \r
-// if(!isFound) {\r
-// SyntaxError error = new SyntaxError(t, "Invalid index"); \r
-// errors.put(t, error);\r
-// }\r
- }\r
- \r
- for(Token t : removes)\r
- errors.remove(t);\r
-\r
- return new ArrayList<SyntaxError>(errors.values());\r
- }\r
-\r
-\r
- /**\r
- * Examine if a given functionKey is a sheet reference and whether all the tokens in the function ( Sheet1(token1, token2) )\r
- * are valid.\r
- * \r
- * @param configuration Configuration where the function is called\r
- * @param functionKey Function name\r
- * @param functionTokens Function parameters (sheet reference, either a cell or cell range)\r
- * @param expression The whole expression where the function reference is\r
- * @param expressionReferences All variable references, including function parameters\r
- * @return A list of possible errors\r
- */\r
- static public List<SyntaxError> examineSheetReferences(\r
- Configuration configuration, \r
- String functionKey, \r
- List<Token> functionTokens,\r
- String expression, \r
- HashMap<String, List<Token>> expressionReferences) {\r
- \r
- List<SyntaxError> result = new ArrayList<SyntaxError>();\r
- \r
- String[] parts = functionKey.split("\\.");\r
- Object current = configuration;\r
- for(int i = 0; i < parts.length && current != null; i++) {\r
- current = getElement(current, parts[i]);\r
- }\r
- \r
- if(current == null && configuration.getModuleType() != null) {\r
- // Sheets are currently located in the model root. Try to find the sheet.\r
- current = configuration.getModuleType().getParent(); // Get module type parent (should be a model)\r
- if(current instanceof Model)\r
- current = getElement(((Model)current).getModelConfiguration(), parts[0]); // Try to get the sheet\r
- }\r
- \r
- if(current != null && current instanceof Sheet) {\r
- Sheet sheet = (Sheet) current;\r
- int start = 0, end = 0, call = 0;\r
- String cellOrRange = null;\r
- while((call = expression.indexOf(functionKey, end)) >= 0) {\r
- start = expression.indexOf("(", call) +1;\r
- end = expression.indexOf(")", start);\r
- if(start < 0 || end < 0 || end < start) {\r
- break;\r
- }\r
- Pattern p = Pattern.compile("[-\\+\\*\\/\\(\\)\\{\\}\\[\\],\\.\\t\\n\\r\\f]");\r
- cellOrRange = expression.substring(start, end);\r
- Matcher m = p.matcher(cellOrRange);\r
- if (m.find() || cellOrRange.split(":").length > 2) {\r
- result.add(new SyntaxError(start, end - start, ExpressionField.SYNTAX_ERROR, "Not a valid cell or range", cellOrRange));\r
- }\r
- }\r
- \r
- \r
- for(Token cell : functionTokens) {\r
- List<Token> refs = expressionReferences.get(cell.image);\r
- if(refs != null)\r
- refs.remove(cell);\r
- if(!sheet.getCells().containsKey(cell.image))\r
- result.add(new SyntaxError(cell.image, "Invalid cell", cell.beginLine, cell.beginColumn, cell.endLine, cell.endColumn)); \r
- }\r
-\r
- }\r
- \r
- return result;\r
- }\r
- \r
- \r
- /**\r
- * Option for a reference. Whether the reference does not exist, \r
- * it can be connected (normal variable) or it cannot be \r
- * connected even though it exists (e.g. enumeration index)\r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
- static public enum ReferenceOption {DOES_NOT_EXIST, CAN_BE_CONNECTED, CANNOT_BE_CONNECTED};\r
- \r
- /**\r
- * Get the reference option for a reference (name) in a configuration.\r
- * \r
- * @param conf Configuration\r
- * @param name Referred variable\r
- * @return The result tells does the referred name exist and can it be connected to \r
- */\r
- static public ReferenceOption getReferenceOption(Configuration conf, String name) {\r
- \r
- String[] parts = name.split("\\.");\r
- Object element = conf;\r
- for(int i = 0; i < parts.length && element != null; i++) {\r
- element = getElement(element, parts[i]);\r
- }\r
- if(element == null)\r
- return ReferenceOption.DOES_NOT_EXIST;\r
- else if(Boolean.TRUE.equals(element))\r
- return ReferenceOption.CANNOT_BE_CONNECTED;\r
- else if(element instanceof Variable || element instanceof Module) {\r
- if(element instanceof Enumeration || element instanceof Sheet || element instanceof Module || parts.length > 1)\r
- return ReferenceOption.CANNOT_BE_CONNECTED;\r
- else\r
- return ReferenceOption.CAN_BE_CONNECTED;\r
- }\r
- else \r
- return ReferenceOption.DOES_NOT_EXIST;\r
- }\r
-\r
- static private Object getElement(Object parent, String name) {\r
- Configuration c = null;\r
- if(parent instanceof Module) {\r
- Module m = (Module)parent;\r
- c = m.getType().getConfiguration();\r
- } else if (parent instanceof Configuration) {\r
- c = (Configuration)parent;\r
- }\r
-\r
- if(c != null) {\r
- for(IElement e : c.getElements()) {\r
- if(e instanceof Variable && ((Variable)e).getName().equals(name)) {\r
- return e;\r
- } else if(e instanceof Module && ((Module)e).getName().equals(name)) {\r
- return e;\r
- }\r
- }\r
- } else if(parent instanceof Sheet) {\r
- Sheet s = (Sheet)parent;\r
- for(String key : s.getCells().keySet()) {\r
- if(key.equals(name)) {\r
- return Boolean.TRUE;\r
- }\r
- }\r
-\r
- } else if(parent instanceof Enumeration) {\r
- Enumeration e = (Enumeration)parent;\r
- if(name.equals("size") || name.equals("elements"))\r
- return Boolean.TRUE;\r
-\r
- for(EnumerationIndex ei : e.getEnumerationIndexes()) {\r
- if(ei.getName().equals(name)) {\r
- return Boolean.TRUE;\r
- }\r
- }\r
-\r
- }\r
-\r
- return null;\r
- }\r
-\r
- @SuppressWarnings("unchecked")\r
- static private HashMap<ExpressionField ,ArrayList<Position>> getPositionsForVariables(HashMap<ExpressionField, HashMap<String, List<Token>>> references, Set<String> variables) {\r
- HashMap<ExpressionField ,ArrayList<Position>> result = new HashMap<ExpressionField ,ArrayList<Position>>();\r
- for(String s : variables) {\r
- List<Token> tlist = new ArrayList<Token>();\r
- for(ExpressionField ef : references.keySet()) {\r
- ArrayList<Position> positions = new ArrayList<Position>();\r
- tlist = references.get(ef).get(s);\r
- if(tlist != null)\r
- for(Token t : tlist) {\r
- StyledText st = ef.getSourceViewer().getTextWidget();\r
- if (st != null) {\r
- int start = st.getOffsetAtLine(t.beginLine - 1) + t.beginColumn - 1;\r
- int offset = st.getOffsetAtLine(t.endLine - 1) + t.endColumn - start;\r
- positions.add(new Position(\r
- start,\r
- offset));\r
- }\r
- }\r
- if(result.keySet().contains(ef)) {\r
- result.get(ef).addAll((ArrayList<Position>)positions.clone());\r
- } else {\r
- result.put(ef, (ArrayList<Position>)positions.clone());\r
- }\r
- }\r
- }\r
- return result;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.ui.utils;
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.eclipse.jface.resource.ColorDescriptor;
+import org.eclipse.jface.resource.LocalResourceManager;
+import org.eclipse.jface.text.Position;
+import org.eclipse.swt.custom.StyledText;
+import org.eclipse.swt.graphics.Color;
+import org.eclipse.swt.graphics.RGB;
+import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.TableItem;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.expressionParser.ExpressionParser;
+import org.simantics.sysdyn.expressionParser.ParseException;
+import org.simantics.sysdyn.expressionParser.Token;
+import org.simantics.sysdyn.expressionParser.TokenMgrError;
+import org.simantics.sysdyn.manager.SysdynModel;
+import org.simantics.sysdyn.manager.SysdynModelManager;
+import org.simantics.sysdyn.modelica.ModelicaWriter;
+import org.simantics.sysdyn.representation.Configuration;
+import org.simantics.sysdyn.representation.Enumeration;
+import org.simantics.sysdyn.representation.EnumerationIndex;
+import org.simantics.sysdyn.representation.IElement;
+import org.simantics.sysdyn.representation.Model;
+import org.simantics.sysdyn.representation.Module;
+import org.simantics.sysdyn.representation.Sheet;
+import org.simantics.sysdyn.representation.Variable;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.ExpressionField;
+import org.simantics.sysdyn.ui.properties.widgets.expressions.IExpression;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ExpressionUtils {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ExpressionUtils.class);
+
+ /**
+ * Determines if the given expression is a parameter expression. Parameters are numbers.
+ * If the expression contains anything other than numbers, it is not a parameter.
+ *
+ * @param expression The expression to be checked
+ * @return is the expression a parameter
+ */
+ static public boolean isParameter(String expression) {
+ try {
+ /*
+ StringTokenizer st = new StringTokenizer(expression, "{}[],;");
+ while(st.hasMoreTokens()) {
+ Double.parseDouble(st.nextToken().trim());
+ }
+ */
+ Double.parseDouble(expression.trim());
+ return true;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Color for a variable found in an expression field, used in shortcut tab.
+ * This is a bit silly means of communicating the state of a variable using its color.
+ * @param resourceManager LocalResourceManager for which the color is created.
+ * @return Color for such variable.
+ */
+ public static Color variableFoundColor(LocalResourceManager resourceManager) {
+ return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(0,0,0)));
+ }
+
+ /**
+ * Color for a variable not found in an expression field, used in shortcut tab.
+ * This is a bit silly means of communicating the state of a variable using its color.
+ * @param resourceManager LocalResourceManager for which the color is created.
+ * @return Color for such variable.
+ */
+ public static Color variableNotFoundColor(LocalResourceManager resourceManager) {
+ return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(255,125,0)));
+ }
+
+ /**
+ * Color for a variable itself and for the time variable, used in shortcut tab.
+ * This is a bit silly means of communicating the state of a variable using its color.
+ * @param resourceManager LocalResourceManager for which the color is created.
+ * @return Color for such variable.
+ */
+ public static Color variableTimeAndSelfColor(LocalResourceManager resourceManager) {
+ return resourceManager.createColor(ColorDescriptor.createFrom(new RGB(127,127,127)));
+ }
+
+ /**
+ * Validates the expressionfield of a given IExpression
+ *
+ * @param expression The expression whose fields are validated
+ * @param resourceManager
+ * @param connectedVariables Table items from the shortcut widget. (Items needed so that they can be coloured)
+ * @param configuration configuration where the variable is located
+ */
+ static public void validateExpressionFields(final Resource variable,
+ IExpression expression,
+ Table variableTable,
+ LocalResourceManager resourceManager) {
+ if(variable == null || expression == null || variableTable == null)
+ return;
+
+ Resource configuration = null;
+ try {
+ configuration = Simantics.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource configuration = variable;
+ while (configuration != null) {
+ configuration = graph.getPossibleObject(configuration, Layer0.getInstance(graph).PartOf);
+
+ if(configuration == null || graph.isInstanceOf(configuration, sr.Configuration)) {
+ break;
+ }
+ }
+ return configuration;
+ }
+ });
+ } catch (DatabaseException e) {
+ LOGGER.error("Database exception whilst validatingExpressionField", e);
+ return;
+ }
+
+ if(configuration == null)
+ return;
+
+ ExpressionParser parser = new ExpressionParser(new StringReader(""));
+ Set<String> variables = new HashSet<String>();
+ HashMap<ExpressionField, HashMap<String, List<Token>>> references = new HashMap<ExpressionField, HashMap<String, List<Token>>>();
+ final HashMap<ExpressionField, HashMap<String, List<List<Token>>>> ranges = new HashMap<ExpressionField, HashMap<String, List<List<Token>>>>();
+ HashMap<ExpressionField, HashMap<Token, List<Token>>> forIndices = new HashMap<ExpressionField, HashMap<Token, List<Token>>>();
+ HashMap<ExpressionField, HashMap<String, List<Token>>> enumerationReferences = new HashMap<ExpressionField, HashMap<String, List<Token>>>();
+ HashMap<ExpressionField, HashMap<String, List<Token>>> functionReferences = new HashMap<ExpressionField, HashMap<String, List<Token>>>();
+
+ // Build references and variable array
+ boolean parsingSucceeded = false;
+ for(ExpressionField ef : expression.getExpressionFields()) {
+ ef.resetAnnotations();
+ String textString = ef.getExpression();
+ parser.ReInit(new StringReader(textString));
+ try {
+ parser.expr();
+ HashMap<String, List<Token>> refs = parser.getReferences();
+ references.put(ef, refs);
+ variables.addAll(refs.keySet());
+
+ ranges.put(ef, parser.getRanges());
+
+ forIndices.put(ef, parser.getForIndices());
+
+ enumerationReferences.put(ef, parser.getEnumerationReferences());
+
+ functionReferences.put(ef, parser.getFunctionCallReferences());
+
+ parsingSucceeded = true;
+ } catch (ParseException e1) {
+ ef.setSyntaxError(new SyntaxError(e1.currentToken, "Syntax Error"));
+
+ /*
+ * If the equation is empty, set the parsingSucceeded = true
+ * to allow the coloring of the variables succeed.
+ */
+ if (textString.equals("")) {
+ parsingSucceeded = true;
+ }
+ } catch (TokenMgrError err) {
+ ef.setSyntaxError(new SyntaxError(0, textString.length(), ExpressionField.SYNTAX_ERROR, "Expression contains unsupported characters"));
+ }
+ }
+
+
+ // Get model configuration
+ SysdynModelManager sdm = SysdynModelManager.getInstance(Simantics.getSession());
+ SysdynModel model = null;
+ try {
+ model = sdm.getModel(configuration);
+ } catch (DatabaseException e) {
+ LOGGER.error("Failed to find model from SysdynModelManager", e);
+ return;
+ }
+
+ Configuration conf = model.getConfiguration();
+
+ // Check variable references
+ final HashMap<String, Variable> modelVariables = new HashMap<String, Variable>();
+ HashSet<String> ignoreVariables = new HashSet<String>();
+ if(!variables.isEmpty() || !functionReferences.isEmpty()) {
+ Set<String> noSuchVariables = new HashSet<String>();
+ ArrayList<IElement> elements = conf.getElements();
+ for(IElement e : elements) {
+ if(e instanceof Variable) {
+ Variable v = (Variable) e;
+ modelVariables.put(v.getName(), v);
+ } else if(e instanceof Module) {
+ ignoreVariables.add(((Module)e).getName());
+ }
+ }
+
+ // Handle reserved variables later
+ variables.remove(ModelicaWriter.VAR_TIME);
+ variables.remove(ModelicaWriter.VAR_START);
+ variables.remove(ModelicaWriter.VAR_STOP);
+ variables.remove(ModelicaWriter.VAR_STEP);
+
+ // Remove variable references to for indices
+ for(ExpressionField ef : forIndices.keySet()) {
+ for(Token t : forIndices.get(ef).keySet()) {
+ if(variables.contains(t.image))
+ variables.remove(t.image);
+ }
+ }
+
+ // Examine sheets
+ for(ExpressionField ef : functionReferences.keySet()) {
+ for(String key : functionReferences.get(ef).keySet()) {
+
+ List<SyntaxError> errors = examineSheetReferences(conf, key, functionReferences.get(ef).get(key), ef.getExpression(), references.get(ef));
+ if(errors != null) {
+ for(SyntaxError error : errors)
+ ef.setSyntaxError(error);
+ }
+ }
+ }
+
+ // Examine variable references
+ for(String v : variables) {
+ ReferenceOption option = getReferenceOption(conf, v);
+ switch(option) {
+ case DOES_NOT_EXIST:
+ noSuchVariables.add(v);
+ break;
+ case CANNOT_BE_CONNECTED:
+ ignoreVariables.add(v);
+ break;
+ case CAN_BE_CONNECTED:
+ }
+ }
+
+ if(!noSuchVariables.isEmpty()) {
+ noSuchVariables.removeAll(ignoreVariables);
+ // remove no such variables from variable list
+ for(String s : noSuchVariables)
+ variables.remove(s);
+ // create annotations
+ HashMap<ExpressionField ,ArrayList<Position>> positions = getPositionsForVariables(references, noSuchVariables);
+ for(ExpressionField ef : positions.keySet()) {
+ ef.setNoSuchVariableAnnotations(positions.get(ef));
+ }
+ }
+ }
+
+ // Check that the variables that exist have connections and the connected variables have references in the expressions
+ // If there are syntax errors, keep the previous coloring.
+ String selfName = null;
+ if(variableTable != null && !variableTable.isDisposed()) {
+
+ // Get the name of the variable itself
+ try {
+ selfName = Simantics.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ Object selfName = graph.getPossibleRelatedValue(variable, l0.HasName);
+ if(selfName != null) {
+ return (String)selfName;
+ }
+ return null;
+ }
+ });
+ } catch (DatabaseException e) {
+ LOGGER.error("Failed to check variables", e);
+ }
+
+ // Color the items in the table
+ TableItem[] connectedVariables = variableTable.getItems();
+ for(TableItem ti : connectedVariables) {
+ String text = ti.getText();
+ if (text.equals(ModelicaWriter.VAR_TIME) ||
+ text.equals(ModelicaWriter.VAR_START) ||
+ text.equals(ModelicaWriter.VAR_STOP) ||
+ text.equals(ModelicaWriter.VAR_STEP) ||
+ text.equals(selfName)) {
+ ti.setForeground(variableTimeAndSelfColor(resourceManager));
+ } else if (parsingSucceeded && !variables.contains(text)) {
+ ti.setForeground(variableNotFoundColor(resourceManager));
+ } else if (parsingSucceeded) {
+ ti.setForeground(variableFoundColor(resourceManager));
+ variables.remove(text);
+ }
+ }
+
+ // Remove all enumerations and sheets, they cannot have connections
+ variables.removeAll(ignoreVariables);
+
+ // Always remove self
+ variables.remove(selfName);
+
+ if(!variables.isEmpty()) {
+ HashMap<ExpressionField ,ArrayList<Position>> positions = getPositionsForVariables(references, variables);
+ for(ExpressionField ef : positions.keySet()) {
+ ef.setMissingLinkAnnotations(positions.get(ef));
+ }
+
+ }
+ }
+
+ for(final ExpressionField ef : ranges.keySet()) {
+ List<SyntaxError> errors = new ArrayList<SyntaxError>();
+ // RANGES
+ errors.addAll(examineArrayRanges(conf, ranges.get(ef), forIndices.get(ef)));
+
+ // ENUMERATION REFERENCES IN FOR-LOOPS
+ errors.addAll(examineEnumerationReferences(conf, enumerationReferences.get(ef)));
+
+ for(SyntaxError error : errors) {
+ ef.setSyntaxError(error);
+ }
+ }
+ }
+
+
+ static public List<SyntaxError> examineArrayRanges(
+ final Configuration configuration,
+ final HashMap<String, List<List<Token>>> ranges,
+ final HashMap<Token, List<Token>> forIndices) {
+
+ List<SyntaxError> result = Collections.emptyList();
+ try {
+ result = Simantics.getSession().syncRequest(new Read<List<SyntaxError>>() {
+
+ @Override
+ public List<SyntaxError> perform(ReadGraph graph) throws DatabaseException {
+ return examineArrayRanges(graph, configuration, ranges, forIndices);
+ }
+ });
+ } catch (DatabaseException e) {
+ LOGGER.error("Failure in examineArrayRanges", e);
+ }
+ return result;
+ }
+
+ static public List<SyntaxError> examineEnumerationReferences(Configuration configuration, HashMap<String, List<Token>> enumRefList) {
+ ArrayList<SyntaxError> result = new ArrayList<SyntaxError>();
+ for(String enumeration : enumRefList.keySet()) {
+ for(Token et : enumRefList.get(enumeration)) {
+ Object o = getElement(configuration, enumeration);
+ if(o != null && o instanceof Enumeration) {
+ boolean isFound = false;
+ Enumeration e = (Enumeration)o;
+
+ if(enumeration.equals(et.image) ||
+ "size".equals(et.image) ||
+ "elements".equals(et.image)){
+ // The full enumeration
+ isFound = true;
+ } else {
+ for(EnumerationIndex ei : e.getEnumerationIndexes()) {
+ if(ei.getName().equals(et.image)) {
+ isFound = true;
+ break;
+ }
+ }
+ }
+
+ if(!isFound) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Enumeration ");
+ sb.append(enumeration);
+ sb.append(" has no such index.\nAvailable indexes are: ");
+ Iterator<EnumerationIndex> iterator = e.getEnumerationIndexes().iterator();
+ while(iterator.hasNext()) {
+ sb.append(iterator.next().getName());
+ if(iterator.hasNext())
+ sb.append(", ");
+ }
+ result.add(new SyntaxError(et, sb.toString()));
+ }
+
+
+ } else {
+ result.add(new SyntaxError(et, "No such enumeration (" + enumeration + ")"));
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ *
+ * @param graph
+ * @param configuration
+ * @param ranges
+ * @param forIndices
+ * @return
+ * @throws DatabaseException
+ */
+ static public List<SyntaxError> examineArrayRanges(
+ ReadGraph graph,
+ Configuration configuration,
+ HashMap<String, List<List<Token>>> ranges,
+ HashMap<Token, List<Token>> forIndices) throws DatabaseException {
+ HashMap<Token, SyntaxError> errors = new HashMap<Token, SyntaxError>();
+ for(String name : ranges.keySet()) {
+ if(ranges.get(name) != null) {
+ for(List<Token> l : ranges.get(name)) {
+ String[] rangeReferences = new String[l.size()];
+ for(int i = 0; i < l.size(); i++) {
+ rangeReferences[i] = l.get(i).image;
+ }
+
+ Object o = getElement(configuration, name);
+ if(o != null && o instanceof Variable) {
+ Map<Integer, SyntaxError> invalidRanges = ArrayVariableUtils.isRangeValid(graph, (Variable)o, rangeReferences);
+ if(invalidRanges != null && !invalidRanges.isEmpty()) {
+ for(Integer i : invalidRanges.keySet()) {
+ SyntaxError error = invalidRanges.get(i);
+ error.setToken(l.get(i));
+ errors.put(l.get(i), error);
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ // FOR-INDICES
+
+ HashSet<Token> removes = new HashSet<Token>();
+ for(Token t : forIndices.keySet()) {
+// boolean isFound = false;
+ for(Token rt : errors.keySet()) {
+ if(rt.image.equals(t.image)) {
+// isFound = true;
+ // remove range token from invalid ranges
+ removes.add(rt);
+ }
+ }
+// Why would this be invalid if the index just is not used anywhere?
+// {1+2 for i in range}
+
+// if(!isFound) {
+// SyntaxError error = new SyntaxError(t, "Invalid index");
+// errors.put(t, error);
+// }
+ }
+
+ for(Token t : removes)
+ errors.remove(t);
+
+ return new ArrayList<SyntaxError>(errors.values());
+ }
+
+
+ /**
+ * Examine if a given functionKey is a sheet reference and whether all the tokens in the function ( Sheet1(token1, token2) )
+ * are valid.
+ *
+ * @param configuration Configuration where the function is called
+ * @param functionKey Function name
+ * @param functionTokens Function parameters (sheet reference, either a cell or cell range)
+ * @param expression The whole expression where the function reference is
+ * @param expressionReferences All variable references, including function parameters
+ * @return A list of possible errors
+ */
+ static public List<SyntaxError> examineSheetReferences(
+ Configuration configuration,
+ String functionKey,
+ List<Token> functionTokens,
+ String expression,
+ HashMap<String, List<Token>> expressionReferences) {
+
+ List<SyntaxError> result = new ArrayList<SyntaxError>();
+
+ String[] parts = functionKey.split("\\.");
+ Object current = configuration;
+ for(int i = 0; i < parts.length && current != null; i++) {
+ current = getElement(current, parts[i]);
+ }
+
+ if(current == null && configuration.getModuleType() != null) {
+ // Sheets are currently located in the model root. Try to find the sheet.
+ current = configuration.getModuleType().getParent(); // Get module type parent (should be a model)
+ if(current instanceof Model)
+ current = getElement(((Model)current).getModelConfiguration(), parts[0]); // Try to get the sheet
+ }
+
+ if(current != null && current instanceof Sheet) {
+ Sheet sheet = (Sheet) current;
+ int start = 0, end = 0, call = 0;
+ String cellOrRange = null;
+ while((call = expression.indexOf(functionKey, end)) >= 0) {
+ start = expression.indexOf("(", call) +1;
+ end = expression.indexOf(")", start);
+ if(start < 0 || end < 0 || end < start) {
+ break;
+ }
+ Pattern p = Pattern.compile("[-\\+\\*\\/\\(\\)\\{\\}\\[\\],\\.\\t\\n\\r\\f]");
+ cellOrRange = expression.substring(start, end);
+ Matcher m = p.matcher(cellOrRange);
+ if (m.find() || cellOrRange.split(":").length > 2) {
+ result.add(new SyntaxError(start, end - start, ExpressionField.SYNTAX_ERROR, "Not a valid cell or range", cellOrRange));
+ }
+ }
+
+
+ for(Token cell : functionTokens) {
+ List<Token> refs = expressionReferences.get(cell.image);
+ if(refs != null)
+ refs.remove(cell);
+ if(!sheet.getCells().containsKey(cell.image))
+ result.add(new SyntaxError(cell.image, "Invalid cell", cell.beginLine, cell.beginColumn, cell.endLine, cell.endColumn));
+ }
+
+ }
+
+ return result;
+ }
+
+
+ /**
+ * Option for a reference. Whether the reference does not exist,
+ * it can be connected (normal variable) or it cannot be
+ * connected even though it exists (e.g. enumeration index)
+ *
+ * @author Teemu Lempinen
+ *
+ */
+ static public enum ReferenceOption {DOES_NOT_EXIST, CAN_BE_CONNECTED, CANNOT_BE_CONNECTED};
+
+ /**
+ * Get the reference option for a reference (name) in a configuration.
+ *
+ * @param conf Configuration
+ * @param name Referred variable
+ * @return The result tells does the referred name exist and can it be connected to
+ */
+ static public ReferenceOption getReferenceOption(Configuration conf, String name) {
+
+ String[] parts = name.split("\\.");
+ Object element = conf;
+ for(int i = 0; i < parts.length && element != null; i++) {
+ element = getElement(element, parts[i]);
+ }
+ if(element == null)
+ return ReferenceOption.DOES_NOT_EXIST;
+ else if(Boolean.TRUE.equals(element))
+ return ReferenceOption.CANNOT_BE_CONNECTED;
+ else if(element instanceof Variable || element instanceof Module) {
+ if(element instanceof Enumeration || element instanceof Sheet || element instanceof Module || parts.length > 1)
+ return ReferenceOption.CANNOT_BE_CONNECTED;
+ else
+ return ReferenceOption.CAN_BE_CONNECTED;
+ }
+ else
+ return ReferenceOption.DOES_NOT_EXIST;
+ }
+
+ static private Object getElement(Object parent, String name) {
+ Configuration c = null;
+ if(parent instanceof Module) {
+ Module m = (Module)parent;
+ c = m.getType().getConfiguration();
+ } else if (parent instanceof Configuration) {
+ c = (Configuration)parent;
+ }
+
+ if(c != null) {
+ for(IElement e : c.getElements()) {
+ if(e instanceof Variable && ((Variable)e).getName().equals(name)) {
+ return e;
+ } else if(e instanceof Module && ((Module)e).getName().equals(name)) {
+ return e;
+ }
+ }
+ } else if(parent instanceof Sheet) {
+ Sheet s = (Sheet)parent;
+ for(String key : s.getCells().keySet()) {
+ if(key.equals(name)) {
+ return Boolean.TRUE;
+ }
+ }
+
+ } else if(parent instanceof Enumeration) {
+ Enumeration e = (Enumeration)parent;
+ if(name.equals("size") || name.equals("elements"))
+ return Boolean.TRUE;
+
+ for(EnumerationIndex ei : e.getEnumerationIndexes()) {
+ if(ei.getName().equals(name)) {
+ return Boolean.TRUE;
+ }
+ }
+
+ }
+
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ static private HashMap<ExpressionField ,ArrayList<Position>> getPositionsForVariables(HashMap<ExpressionField, HashMap<String, List<Token>>> references, Set<String> variables) {
+ HashMap<ExpressionField ,ArrayList<Position>> result = new HashMap<ExpressionField ,ArrayList<Position>>();
+ for(String s : variables) {
+ List<Token> tlist = new ArrayList<Token>();
+ for(ExpressionField ef : references.keySet()) {
+ ArrayList<Position> positions = new ArrayList<Position>();
+ tlist = references.get(ef).get(s);
+ if(tlist != null)
+ for(Token t : tlist) {
+ StyledText st = ef.getSourceViewer().getTextWidget();
+ if (st != null) {
+ int start = st.getOffsetAtLine(t.beginLine - 1) + t.beginColumn - 1;
+ int offset = st.getOffsetAtLine(t.endLine - 1) + t.endColumn - start;
+ positions.add(new Position(
+ start,
+ offset));
+ }
+ }
+ if(result.keySet().contains(ef)) {
+ result.get(ef).addAll((ArrayList<Position>)positions.clone());
+ } else {
+ result.put(ef, (ArrayList<Position>)positions.clone());
+ }
+ }
+ }
+ return result;
+ }
+
+}
-package org.simantics.sysdyn.ui.utils;\r
-\r
-import java.util.Collection;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ServiceException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynModel;\r
-import org.simantics.sysdyn.representation.Configuration;\r
-import org.simantics.sysdyn.representation.IElement;\r
-import org.simantics.sysdyn.representation.Module;\r
-import org.simantics.sysdyn.representation.Shadow;\r
-import org.simantics.sysdyn.representation.Sheet;\r
-import org.simantics.sysdyn.representation.Variable;\r
-import org.simantics.sysdyn.ui.modelica.ModelicaSourceViewerConfiguration;\r
-import org.simantics.sysdyn.utils.Function;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-\r
-/**\r
- * This class is used when renaming an element to check that there\r
- * are no elements in the database that would cause a conflict. There\r
- * are two kinds of different conflicts:\r
- * 1) There is an element in the database which has the same URI.\r
- * Adding another causes damage or even a fatal corruption in the \r
- * database.\r
- * 2) Multiple different elements in the database are accessed with\r
- * identical identifiers in the generated Modelica model. This will\r
- * prevent the simulation from running. \r
- * \r
- * @author Tuomas Miettinen\r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public abstract class NameValidator {\r
-\r
- /**\r
- * This method tells the validator whether the proposed name is taken. To be more precise,\r
- * it tells if the proposed name should not be used for any reason. E.g. similarly named\r
- * resources cause problems in some occasions and are fine in others. In addition, there\r
- * (at least )are two reasons to decline a name proposition: firstly, the data base might\r
- * have a similarly named entity, and secondly, accepting a proposed name would lead in\r
- * naming conflicts in the generated OpenModelica model.\r
- * \r
- * @param graph\r
- * @param resource the Resource which is being renamed\r
- * @param name the proposed name\r
- * @return true iff the name proposition is denied\r
- * @throws DatabaseException\r
- */\r
- protected abstract boolean nameIsTaken(ReadGraph graph, Resource resource, String name) throws DatabaseException;\r
-\r
- /**\r
- * Replaces variable names in all the expressions in the defined configuration. \r
- * Replace doesn't have to replace words in other configurations than the configuration where the renamed variable is\r
- * because input variables handle the transitions between configurations (modules).\r
- * \r
- * @param graph WriteGraph\r
- * @param configuration The configuration where the renamed variable is located\r
- * @param originalName The original name of the variable\r
- * @param newName New name of the variable\r
- */\r
- public abstract void renameInEquations(WriteGraph graph, Resource resource, String originalName, String newName) throws DatabaseException;\r
-\r
- public abstract void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName) throws DatabaseException;\r
-\r
- /**\r
- * Checks that the syntax of the given name is valid and there \r
- * are no other functions that have the same name in neither the \r
- * configuration nor among built in functions\r
- * \r
- * @param graph ReadGraph\r
- * @param resource The variable that is being renamed\r
- * @param name The new name of the variable\r
- * @return true iff the new name is valid\r
- * @throws DatabaseException\r
- */\r
- public boolean isValid(ReadGraph graph, Resource resource, String name) throws DatabaseException {\r
- // Decline empty string\r
- if(name.length() < 1) return false;\r
- \r
- // Decline names based on the type of the resource\r
- if(nameIsTaken(graph, resource, name)) return false;\r
- \r
- // Decline names which are against Modelica naming rules\r
- boolean allowSpaces = doesResourceAllowSpacedName(graph, resource);\r
- if(!isValidModelica(name, allowSpaces)) return false;\r
- return true;\r
- }\r
-\r
- /**\r
- * Determine whether a Sysdyn Variable can have whitespace in its name (based on its type).\r
- * @param graph\r
- * @param resource Resource of the variable\r
- * @return true iff spaces are allowed in the name\r
- */\r
- protected boolean doesResourceAllowSpacedName(ReadGraph graph,\r
- Resource resource) {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- SpreadsheetResource sheet = SpreadsheetResource.getInstance(graph);\r
- try {\r
- if (resource == null)\r
- return false;\r
- // Function, FunctionLibrary, and SharedFunctionLibrary are not\r
- // allowed to have whitespace.\r
- if (graph.isInstanceOf(resource, sr.Variable)\r
- || graph.isInstanceOf(resource, sr.Module)\r
- || graph.isInheritedFrom(resource, sr.ModuleSymbol)\r
- || graph.isInstanceOf(resource, sr.Enumeration)\r
- || graph.isInstanceOf(resource, sr.EnumerationIndex)\r
- || graph.isInstanceOf(resource, sheet.Spreadsheet)\r
- || graph.isInstanceOf(resource, sr.SysdynModel)) {\r
- return true;\r
- }\r
- } catch (ServiceException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- return false;\r
- }\r
-\r
- /**\r
- * Checks that the syntax of the given name is valid and there \r
- * are no other variables that have the same name in the configuration\r
- * \r
- * @param variable The variable that is being renamed\r
- * @param name The new name of the variable\r
- * @return true iff the new name is valid\r
- * @throws DatabaseException\r
- */\r
- public boolean isValid(final Resource resource, final String name) {\r
- boolean result = false;\r
-\r
- try {\r
- result = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- return isValid(graph, resource, name);\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return result;\r
- }\r
-\r
- /**\r
- * Checks that the syntax of the given name is valid \r
- * and that it is not a keyword in Modelica.\r
- * \r
- * @param name name that is validated\r
- * @return true iff the syntax of the name is valid\r
- */\r
- public boolean isValidModelica(String name, boolean allowSpaces) {\r
- String lowerCase = name.toLowerCase();\r
- String pattern = "[a-zA-Z][a-zA-Z0-9]*" + (allowSpaces ? "( [a-zA-Z][a-zA-Z0-9]*)*" : "");\r
- Pattern p = Pattern.compile(pattern);\r
- Matcher m = p.matcher(lowerCase);\r
- if (!m.matches()) {\r
- return false;\r
- } else {\r
- String[] splitNames= name.split("\\s+");\r
- for (String splitName : splitNames) {\r
- // Do not allow Modelica keywords to be a part of a whitespaced name\r
- if (ModelicaSourceViewerConfiguration.keywords.contains(splitName)) {\r
- return false;\r
- }\r
- }\r
- }\r
- return true;\r
- }\r
-\r
- /**\r
- * Checks that there is no similarly named spread sheet in the top level model.\r
- * \r
- * @param graph ReadGraph\r
- * @param configurationResource Resource of the configuration of the model\r
- * @param resource Resource being validated\r
- * @param name proposed new name for resource\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- protected boolean nameTakenBySheet(\r
- ReadGraph graph, \r
- Resource configurationResource, \r
- Resource resource, \r
- String name) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
- for (Resource r : graph.getObjects(configurationResource, l0.ConsistsOf)) {\r
- if (graph.isInstanceOf(r, SHEET.Book)) {\r
- for (Resource s : graph.getObjects(r, l0.ConsistsOf)) {\r
- if (NameUtils.getSafeName(graph, s).equals(name) && !s.equals(resource)) {\r
- return true;\r
- }\r
- }\r
- // Assume only one book\r
- break;\r
- }\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * Checks that there is no similarly named spread sheet in the top level model.\r
- * \r
- * @param sysdynModel the model\r
- * @param name proposed new name for resource\r
- * @return\r
- */\r
- public boolean nameTakenBySheet(\r
- SysdynModel sysdynModel, \r
- String name) {\r
- Configuration configuration = sysdynModel.getConfiguration();\r
- if (configuration == null)\r
- return true;\r
- for (IElement e : configuration.getElements()) {\r
- if (e instanceof Sheet) {\r
- if (((Sheet)e).getName().equals(name)) {\r
- return true;\r
- }\r
- }\r
- }\r
- return false;\r
- }\r
-\r
- /**\r
- * Check that there are no similarly named functions, module types, or any\r
- * other items in the same library. There are actually plenty of items that have\r
- * to be avoided, probably all of them, they are all included in this test. \r
- * \r
- * @param graph ReadGraph\r
- * @param library Resource which is studied\r
- * @param resource Resource being validated\r
- * @param name proposed new name for resource\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- protected boolean nameTakenByItemUnderLibrary(\r
- ReadGraph graph,\r
- Resource library,\r
- Resource resource,\r
- String name) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- for (Resource r : graph.getObjects(library, l0.ConsistsOf)) {\r
- if (NameUtils.getSafeName(graph, r).equals(name) && !r.equals(resource)) {\r
- return true;\r
- }\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * Check that there is no similarly named function library among shared function libraries.\r
- * \r
- * @param graph ReadGraph\r
- * @param model resource of the top level model under which the resource is\r
- * @param resource Resource being validated\r
- * @param name proposed new name for resource\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- protected boolean nameTakenBySharedFunctionLibrary(\r
- ReadGraph graph,\r
- Resource model, \r
- Resource resource,\r
- String name) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Collection<Resource> linkedResources = graph.getObjects(model, l0.IsLinkedTo);\r
- for (Resource r : linkedResources) {\r
- // Find the "Shared functions" library \r
- if (graph.isInstanceOf(r, sr.SharedFunctionOntology)) {\r
- if (NameUtils.getSafeName(graph, r).equals(name) && !r.equals(resource)) {\r
- return true;\r
- }\r
- }\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * Check that there is no similarly named function among built-in functions\r
- * \r
- * @param graph ReadGraph\r
- * @param name name that is checked\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- protected boolean nameTakenByBuiltInFunction(\r
- ReadGraph graph, \r
- String name) throws DatabaseException {\r
- for (Function f : Function.getAllBuiltInFunctions(graph)) {\r
- if (f.getName().equals(name)) {\r
- return true;\r
- }\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * Check that the top level of the model doesn't contain \r
- * a variable or module with the same name.\r
- * \r
- * @param graph ReadGraph\r
- * @param sysdynModel the model\r
- * @param resource Resource being validated\r
- * @param name proposed new name for resource\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- protected boolean nameTakenByTopLevelVariableOrModule(\r
- ReadGraph graph,\r
- SysdynModel sysdynModel,\r
- Resource resource,\r
- String name) throws DatabaseException {\r
- Configuration configuration = sysdynModel.getConfiguration();\r
- if(configuration == null)\r
- return true;\r
- IElement current = sysdynModel.getElement(resource);\r
- for(IElement e : configuration.getElements()) {\r
- if(e instanceof Variable && !(e instanceof Shadow)) {\r
- Variable v = (Variable) e;\r
- if(!v.equals(current) && v.getName() != null && v.getName().equals(name)) {\r
- return true;\r
- }\r
- } else if (e instanceof Module) {\r
- Module m = (Module)e;\r
- if(!m.equals(current) && m.getName() != null && m.getName().equals(name)) {\r
- return true;\r
- }\r
- }\r
- }\r
- return false;\r
- }\r
- \r
- /**\r
- * Check that there is no similarly named function, function library,\r
- * or module type directly under a library\r
- * \r
- * This function should not be used by functions, function libraries, or module types\r
- *\r
- * @param graph ReadGraph\r
- * @param library Resource which is studied\r
- * @param name proposed new name for resource\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- protected boolean nameTakenByFunctionFunctionLibraryOrModuleType(\r
- ReadGraph graph,\r
- Resource library,\r
- String name) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for (Resource r : graph.getObjects(library, l0.ConsistsOf)) {\r
- if (graph.isInstanceOf(r, sr.SysdynModelicaFunctionLibrary)\r
- || graph.isInstanceOf(r, sr.SysdynModelicaFunction)\r
- || graph.isInheritedFrom(r, sr.Module)) {\r
- if (NameUtils.getSafeName(graph, r).equals(name)) {\r
- return true;\r
- }\r
- }\r
- }\r
- return false;\r
- }\r
- \r
-}\r
+package org.simantics.sysdyn.ui.utils;
+
+import java.util.Collection;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.ServiceException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.spreadsheet.resource.SpreadsheetResource;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynModel;
+import org.simantics.sysdyn.representation.Configuration;
+import org.simantics.sysdyn.representation.IElement;
+import org.simantics.sysdyn.representation.Module;
+import org.simantics.sysdyn.representation.Shadow;
+import org.simantics.sysdyn.representation.Sheet;
+import org.simantics.sysdyn.representation.Variable;
+import org.simantics.sysdyn.ui.modelica.ModelicaSourceViewerConfiguration;
+import org.simantics.sysdyn.utils.Function;
+
+
+/**
+ * This class is used when renaming an element to check that there
+ * are no elements in the database that would cause a conflict. There
+ * are two kinds of different conflicts:
+ * 1) There is an element in the database which has the same URI.
+ * Adding another causes damage or even a fatal corruption in the
+ * database.
+ * 2) Multiple different elements in the database are accessed with
+ * identical identifiers in the generated Modelica model. This will
+ * prevent the simulation from running.
+ *
+ * @author Tuomas Miettinen
+ * @author Teemu Lempinen
+ *
+ */
+public abstract class NameValidator {
+
+ /**
+ * This method tells the validator whether the proposed name is taken. To be more precise,
+ * it tells if the proposed name should not be used for any reason. E.g. similarly named
+ * resources cause problems in some occasions and are fine in others. In addition, there
+ * (at least )are two reasons to decline a name proposition: firstly, the data base might
+ * have a similarly named entity, and secondly, accepting a proposed name would lead in
+ * naming conflicts in the generated OpenModelica model.
+ *
+ * @param graph
+ * @param resource the Resource which is being renamed
+ * @param name the proposed name
+ * @return true iff the name proposition is denied
+ * @throws DatabaseException
+ */
+ protected abstract boolean nameIsTaken(ReadGraph graph, Resource resource, String name) throws DatabaseException;
+
+ /**
+ * Replaces variable names in all the expressions in the defined configuration.
+ * Replace doesn't have to replace words in other configurations than the configuration where the renamed variable is
+ * because input variables handle the transitions between configurations (modules).
+ *
+ * @param graph WriteGraph
+ * @param configuration The configuration where the renamed variable is located
+ * @param originalName The original name of the variable
+ * @param newName New name of the variable
+ */
+ public abstract void renameInEquations(WriteGraph graph, Resource resource, String originalName, String newName) throws DatabaseException;
+
+ public abstract void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName) throws DatabaseException;
+
+ /**
+ * Checks that the syntax of the given name is valid and there
+ * are no other functions that have the same name in neither the
+ * configuration nor among built in functions
+ *
+ * @param graph ReadGraph
+ * @param resource The variable that is being renamed
+ * @param name The new name of the variable
+ * @return true iff the new name is valid
+ * @throws DatabaseException
+ */
+ public boolean isValid(ReadGraph graph, Resource resource, String name) throws DatabaseException {
+ // Decline empty string
+ if(name.length() < 1) return false;
+
+ // Decline names based on the type of the resource
+ if(nameIsTaken(graph, resource, name)) return false;
+
+ // Decline names which are against Modelica naming rules
+ boolean allowSpaces = doesResourceAllowSpacedName(graph, resource);
+ if(!isValidModelica(name, allowSpaces)) return false;
+ return true;
+ }
+
+ /**
+ * Determine whether a Sysdyn Variable can have whitespace in its name (based on its type).
+ * @param graph
+ * @param resource Resource of the variable
+ * @return true iff spaces are allowed in the name
+ */
+ protected boolean doesResourceAllowSpacedName(ReadGraph graph,
+ Resource resource) {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ SpreadsheetResource sheet = SpreadsheetResource.getInstance(graph);
+ try {
+ if (resource == null)
+ return false;
+ // Function, FunctionLibrary, and SharedFunctionLibrary are not
+ // allowed to have whitespace.
+ if (graph.isInstanceOf(resource, sr.Variable)
+ || graph.isInstanceOf(resource, sr.Module)
+ || graph.isInheritedFrom(resource, sr.ModuleSymbol)
+ || graph.isInstanceOf(resource, sr.Enumeration)
+ || graph.isInstanceOf(resource, sr.EnumerationIndex)
+ || graph.isInstanceOf(resource, sheet.Spreadsheet)
+ || graph.isInstanceOf(resource, sr.SysdynModel)) {
+ return true;
+ }
+ } catch (ServiceException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return false;
+ }
+
+ /**
+ * Checks that the syntax of the given name is valid and there
+ * are no other variables that have the same name in the configuration
+ *
+ * @param variable The variable that is being renamed
+ * @param name The new name of the variable
+ * @return true iff the new name is valid
+ * @throws DatabaseException
+ */
+ public boolean isValid(final Resource resource, final String name) {
+ boolean result = false;
+
+ try {
+ result = Simantics.getSession().syncRequest(new Read<Boolean>() {
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ return isValid(graph, resource, name);
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return result;
+ }
+
+ /**
+ * Checks that the syntax of the given name is valid
+ * and that it is not a keyword in Modelica.
+ *
+ * @param name name that is validated
+ * @return true iff the syntax of the name is valid
+ */
+ public boolean isValidModelica(String name, boolean allowSpaces) {
+ String lowerCase = name.toLowerCase();
+ String pattern = "[a-zA-Z][a-zA-Z0-9_]*" + (allowSpaces ? "( [a-zA-Z][a-zA-Z0-9_]*)*" : "");
+ Pattern p = Pattern.compile(pattern);
+ Matcher m = p.matcher(lowerCase);
+ if (!m.matches()) {
+ return false;
+ } else {
+ String[] splitNames= name.split("\\s+");
+ for (String splitName : splitNames) {
+ // Do not allow Modelica keywords to be a part of a whitespaced name
+ if (ModelicaSourceViewerConfiguration.keywords.contains(splitName)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Checks that there is no similarly named spread sheet in the top level model.
+ *
+ * @param graph ReadGraph
+ * @param configurationResource Resource of the configuration of the model
+ * @param resource Resource being validated
+ * @param name proposed new name for resource
+ * @return
+ * @throws DatabaseException
+ */
+ protected boolean nameTakenBySheet(
+ ReadGraph graph,
+ Resource configurationResource,
+ Resource resource,
+ String name) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);
+ for (Resource r : graph.getObjects(configurationResource, l0.ConsistsOf)) {
+ if (graph.isInstanceOf(r, SHEET.Book)) {
+ for (Resource s : graph.getObjects(r, l0.ConsistsOf)) {
+ if (NameUtils.getSafeName(graph, s).equals(name) && !s.equals(resource)) {
+ return true;
+ }
+ }
+ // Assume only one book
+ break;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks that there is no similarly named spread sheet in the top level model.
+ *
+ * @param sysdynModel the model
+ * @param name proposed new name for resource
+ * @return
+ */
+ public boolean nameTakenBySheet(
+ SysdynModel sysdynModel,
+ String name) {
+ Configuration configuration = sysdynModel.getConfiguration();
+ if (configuration == null)
+ return true;
+ for (IElement e : configuration.getElements()) {
+ if (e instanceof Sheet) {
+ if (((Sheet)e).getName().equals(name)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check that there are no similarly named functions, module types, or any
+ * other items in the same library. There are actually plenty of items that have
+ * to be avoided, probably all of them, they are all included in this test.
+ *
+ * @param graph ReadGraph
+ * @param library Resource which is studied
+ * @param resource Resource being validated
+ * @param name proposed new name for resource
+ * @return
+ * @throws DatabaseException
+ */
+ protected boolean nameTakenByItemUnderLibrary(
+ ReadGraph graph,
+ Resource library,
+ Resource resource,
+ String name) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ for (Resource r : graph.getObjects(library, l0.ConsistsOf)) {
+ if (NameUtils.getSafeName(graph, r).equals(name) && !r.equals(resource)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check that there is no similarly named function library among shared function libraries.
+ *
+ * @param graph ReadGraph
+ * @param model resource of the top level model under which the resource is
+ * @param resource Resource being validated
+ * @param name proposed new name for resource
+ * @return
+ * @throws DatabaseException
+ */
+ protected boolean nameTakenBySharedFunctionLibrary(
+ ReadGraph graph,
+ Resource model,
+ Resource resource,
+ String name) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Collection<Resource> linkedResources = graph.getObjects(model, l0.IsLinkedTo);
+ for (Resource r : linkedResources) {
+ // Find the "Shared functions" library
+ if (graph.isInstanceOf(r, sr.SharedFunctionOntology)) {
+ if (NameUtils.getSafeName(graph, r).equals(name) && !r.equals(resource)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check that there is no similarly named function among built-in functions
+ *
+ * @param graph ReadGraph
+ * @param name name that is checked
+ * @return
+ * @throws DatabaseException
+ */
+ protected boolean nameTakenByBuiltInFunction(
+ ReadGraph graph,
+ String name) throws DatabaseException {
+ for (Function f : Function.getAllBuiltInFunctions(graph)) {
+ if (f.getName().equals(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check that the top level of the model doesn't contain
+ * a variable or module with the same name.
+ *
+ * @param graph ReadGraph
+ * @param sysdynModel the model
+ * @param resource Resource being validated
+ * @param name proposed new name for resource
+ * @return
+ * @throws DatabaseException
+ */
+ protected boolean nameTakenByTopLevelVariableOrModule(
+ ReadGraph graph,
+ SysdynModel sysdynModel,
+ Resource resource,
+ String name) throws DatabaseException {
+ Configuration configuration = sysdynModel.getConfiguration();
+ if(configuration == null)
+ return true;
+ IElement current = sysdynModel.getElement(resource);
+ for(IElement e : configuration.getElements()) {
+ if(e instanceof Variable && !(e instanceof Shadow)) {
+ Variable v = (Variable) e;
+ if(!v.equals(current) && v.getName() != null && v.getName().equals(name)) {
+ return true;
+ }
+ } else if (e instanceof Module) {
+ Module m = (Module)e;
+ if(!m.equals(current) && m.getName() != null && m.getName().equals(name)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check that there is no similarly named function, function library,
+ * or module type directly under a library
+ *
+ * This function should not be used by functions, function libraries, or module types
+ *
+ * @param graph ReadGraph
+ * @param library Resource which is studied
+ * @param name proposed new name for resource
+ * @return
+ * @throws DatabaseException
+ */
+ protected boolean nameTakenByFunctionFunctionLibraryOrModuleType(
+ ReadGraph graph,
+ Resource library,
+ String name) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for (Resource r : graph.getObjects(library, l0.ConsistsOf)) {
+ if (graph.isInstanceOf(r, sr.SysdynModelicaFunctionLibrary)
+ || graph.isInstanceOf(r, sr.SysdynModelicaFunction)
+ || graph.isInheritedFrom(r, sr.Module)) {
+ if (NameUtils.getSafeName(graph, r).equals(name)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.utils;\r
-\r
-import java.io.StringReader;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.StringTokenizer;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
-import org.simantics.sysdyn.expressionParser.ParseException;\r
-import org.simantics.sysdyn.expressionParser.Token;\r
-import org.simantics.sysdyn.manager.SysdynModel;\r
-import org.simantics.sysdyn.representation.Configuration;\r
-import org.simantics.sysdyn.representation.Model;\r
-import org.simantics.sysdyn.representation.ModuleType;\r
-import org.simantics.sysdyn.utils.ModelUtils;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Name validator for variables, modules, and enumerations.\r
- * @author Teemu Lempinen\r
- * @author Tuomas Miettinen\r
- * \r
- */\r
-public class VariableNameValidator extends NameValidator {\r
-\r
- @Override\r
- public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName) throws DatabaseException {\r
- /*FIXME: \r
- * How this works when range used in equations has the same string as\r
- * the renamed variable? Should it be possible? \r
- */ \r
- if(originalName.equals(newName))\r
- return; // Do nothing\r
- \r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- \r
- Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);\r
- if(expressions != null) {\r
- List<Resource> expressionList = ListUtils.toList(graph, expressions);\r
- for(Resource s : expressionList) {\r
- for(Resource p : graph.getPredicates(s)) {\r
- Resource o = graph.getPossibleObject(s, p);\r
- if(o != null && graph.isInstanceOf(o, l0.String) && !p.equals(sr.Expression_arrayRange)) {\r
- String string = graph.getRelatedValue(s, p);\r
- String replaced = replaceAllWords(string, originalName, newName);\r
- if(!string.equals(replaced))\r
- graph.claimLiteral(s, p, replaced);\r
- }\r
- }\r
- }\r
- }\r
- }\r
- \r
- @Override\r
- public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName) throws DatabaseException {\r
- if(originalName.equals(newName))\r
- return; // Do nothing\r
-\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for(Resource r : graph.getObjects(configuration, l0.ConsistsOf)) {\r
- if(graph.isInstanceOf(r, sr.IndependentVariable)) {\r
- renameInEquations(graph, r, originalName, newName);\r
- }\r
- }\r
- }\r
-\r
- private static String replaceAllWords(String original, String find, String replacement) {\r
- // Test if the new name (String find) is found in the original \r
- // string in some format.\r
- String pattern = "(.|\r|\n)*" + find.replace(" ", "\\s+") + "(.|\r|\n)*";\r
- if(!original.matches(pattern)) return original;\r
- if (find.equals(replacement)) return original;\r
-\r
- ExpressionParser parser = new ExpressionParser(new StringReader(original));\r
- try {\r
- parser.expr();\r
- } catch (ParseException e) {\r
- // Best effort; if there are syntax errors, the replace may fail.\r
- }\r
- \r
- // Collect all references\r
- HashMap<String, List<Token>> allReferences = new HashMap<String, List<Token>>();\r
- allReferences.putAll(parser.getReferences());\r
- allReferences.putAll(parser.getFunctionCallReferences());\r
- allReferences.putAll(parser.getEnumerationReferences());\r
- \r
- List<Token> replacedTokens = allReferences.get(find);\r
- if (replacedTokens == null)\r
- return original;\r
- \r
- // Sort the tokens so that they are in the reversed order based on\r
- // their location in the expression.\r
- Collections.sort(replacedTokens);\r
- Collections.reverse(replacedTokens);\r
- \r
- // Go through the tokens in the reversed order\r
- String result = new String(original);\r
- for (Token token : replacedTokens) {\r
- // Find the place where the last token points to in the original string\r
- // First find where the correct line starts:\r
- int startingPoint = 0;\r
- for (int i = 0; i < token.beginLine - 1; ++i)\r
- startingPoint = result.indexOf('\n', startingPoint) + 1;\r
- // Then where the replaced string starts: \r
- startingPoint += token.beginColumn - 1;\r
- \r
- // Cut the string\r
- String begin = result.substring(0, startingPoint);\r
- String end = result.substring(startingPoint);\r
- \r
- // Replace the string\r
- String regex = find.replaceAll(" ", "\\\\s+");\r
- end = end.replaceFirst(regex, replacement);\r
- result = begin + end;\r
- }\r
- \r
- return result;\r
- }\r
-\r
-\r
- @Override\r
- protected boolean nameIsTaken(ReadGraph graph, Resource variable, String name) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- if(variable == null)\r
- return false;\r
- \r
- SysdynModel sysdynModel = ModelUtils.getModel(graph, variable);\r
- if(sysdynModel == null)\r
- return true;\r
- sysdynModel.update(graph);\r
- \r
- Configuration configuration = sysdynModel.getConfiguration();\r
- if(configuration == null)\r
- return true;\r
- \r
- // Get the top level model\r
- Model rootModel = null;\r
- ModuleType moduleType = configuration.getModuleType();\r
- if (moduleType != null) {\r
- Object o = moduleType.getParent();\r
- if (o instanceof Model) {\r
- rootModel = (Model)o;\r
- }\r
- } else {\r
- rootModel = configuration.getModel();\r
- }\r
- \r
- // Get the top level model (SysdynModel)\r
- // Resource library should be used with care if it is not instance of sr.SysdynModel\r
- Resource library = graph.getPossibleObject(variable, l0.PartOf);\r
- if(library == null) {\r
- return true;\r
- } else {\r
- library = graph.getPossibleObject(library, l0.PartOf);\r
- if(library == null) {\r
- return true;\r
- }\r
- }\r
-\r
- // Check if the function is right under the model.\r
- if (graph.isInstanceOf(library, sr.SysdynModel)) {\r
- // Check that the function name != model name (== library name)\r
- if (NameUtils.getSafeName(graph, library).equals(name)) return true;\r
- \r
- if (nameTakenByBuiltInFunction(graph, name)) return true;\r
-\r
- if (nameTakenBySharedFunctionLibrary(graph, library, null, name)) return true;\r
- \r
- if (nameTakenBySheet(sysdynModel, name)) return true;\r
- }\r
-\r
- if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, variable, name)) return true;\r
-\r
- if (rootModel != null) {\r
- // Browse through all ModuleTypes within the whole model\r
- if (rootModel.containsModuleType(name))\r
- return true;\r
- }\r
- \r
- if (nameTakenByFunctionFunctionLibraryOrModuleType(graph, library, name)) return true;\r
- \r
- return false;\r
- }\r
-\r
- /**\r
- * Checks that the syntax of the given name is valid and there \r
- * are no other variables that have the same name in the configuration\r
- * \r
- * @param graph ReadGraph\r
- * @param variable The variable that is being renamed\r
- * @param name The new name of the variable\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- public boolean isValid(ReadGraph graph, Resource variable, String name, boolean hasRange) throws DatabaseException {\r
- if(hasRange) {\r
- String range = null;\r
- if(name.contains("[")) {\r
- StringTokenizer st = new StringTokenizer(name, "[]", true);\r
- if(st.countTokens() != 4)\r
- return false;\r
- name = st.nextToken();\r
- if(!st.nextToken().equals("[")) return false;\r
- range = st.nextToken();\r
- if(!st.nextToken().equals("]")) return false;\r
- }\r
- if(range != null && !ArrayVariableUtils.isRangeValid(graph, variable, range)) return false;\r
- }\r
- return isValid(graph, variable, name);\r
- }\r
-\r
- \r
- /**\r
- * Checks that the syntax of the given name is valid and there \r
- * are no other variables that have the same name in the configuration\r
- * \r
- * @param variable The variable that is being renamed\r
- * @param name The new name of the variable\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- public boolean isValid(final Resource variable, final String name, final boolean hasRange) {\r
- if (variable == null || name == null)\r
- return false;\r
- \r
- boolean result = false;\r
- try {\r
- result = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- return isValid(graph, variable, name, hasRange);\r
- }\r
-\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return result;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.utils;
+
+import java.io.StringReader;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.expressionParser.ExpressionParser;
+import org.simantics.sysdyn.expressionParser.ParseException;
+import org.simantics.sysdyn.expressionParser.Token;
+import org.simantics.sysdyn.manager.SysdynModel;
+import org.simantics.sysdyn.representation.Configuration;
+import org.simantics.sysdyn.representation.Model;
+import org.simantics.sysdyn.representation.ModuleType;
+import org.simantics.sysdyn.utils.ModelUtils;
+
+/**
+ * Name validator for variables, modules, and enumerations.
+ * @author Teemu Lempinen
+ * @author Tuomas Miettinen
+ *
+ */
+public class VariableNameValidator extends NameValidator {
+
+ @Override
+ public void renameInEquations(WriteGraph graph, Resource variable, String originalName, String newName) throws DatabaseException {
+ /*FIXME:
+ * How this works when range used in equations has the same string as
+ * the renamed variable? Should it be possible?
+ */
+ if(originalName.equals(newName))
+ return; // Do nothing
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList);
+ if(expressions != null) {
+ List<Resource> expressionList = ListUtils.toList(graph, expressions);
+ for(Resource s : expressionList) {
+ for(Resource p : graph.getPredicates(s)) {
+ Resource o = graph.getPossibleObject(s, p);
+ if(o != null && graph.isInstanceOf(o, l0.String) && !p.equals(sr.Expression_arrayRange)) {
+ String string = graph.getRelatedValue(s, p);
+ String replaced = replaceAllWords(string, originalName, newName);
+ if(!string.equals(replaced))
+ graph.claimLiteral(s, p, replaced);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public void renameInAllEquations(WriteGraph graph, Resource configuration, String originalName, String newName) throws DatabaseException {
+ if(originalName.equals(newName))
+ return; // Do nothing
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for(Resource r : graph.getObjects(configuration, l0.ConsistsOf)) {
+ if(graph.isInstanceOf(r, sr.IndependentVariable)) {
+ renameInEquations(graph, r, originalName, newName);
+ }
+ }
+ }
+
+ private static String replaceAllWords(String original, String find, String replacement) {
+ // Test if the new name (String find) is found in the original
+ // string in some format.
+ String pattern = "(.|\r|\n)*" + find.replace(" ", "\\s+") + "(.|\r|\n)*";
+ if(!original.matches(pattern)) return original;
+ if (find.equals(replacement)) return original;
+
+ ExpressionParser parser = new ExpressionParser(new StringReader(original));
+ try {
+ parser.expr();
+ } catch (ParseException e) {
+ // Best effort; if there are syntax errors, the replace may fail.
+ }
+
+ // Collect all references
+ HashMap<String, List<Token>> allReferences = new HashMap<String, List<Token>>();
+ allReferences.putAll(parser.getReferences());
+ allReferences.putAll(parser.getFunctionCallReferences());
+ allReferences.putAll(parser.getEnumerationReferences());
+
+ List<Token> replacedTokens = allReferences.get(find);
+ if (replacedTokens == null)
+ return original;
+
+ // Sort the tokens so that they are in the reversed order based on
+ // their location in the expression.
+ Collections.sort(replacedTokens);
+ Collections.reverse(replacedTokens);
+
+ // Go through the tokens in the reversed order
+ String result = new String(original);
+ for (Token token : replacedTokens) {
+ // Find the place where the last token points to in the original string
+ // First find where the correct line starts:
+ int startingPoint = 0;
+ for (int i = 0; i < token.beginLine - 1; ++i)
+ startingPoint = result.indexOf('\n', startingPoint) + 1;
+ // Then where the replaced string starts:
+ startingPoint += token.beginColumn - 1;
+
+ // Cut the string
+ String begin = result.substring(0, startingPoint);
+ String end = result.substring(startingPoint);
+
+ // Replace the string
+ String regex = find.replaceAll(" ", "\\\\s+");
+ end = end.replaceFirst(regex, replacement);
+ result = begin + end;
+ }
+
+ return result;
+ }
+
+
+ @Override
+ protected boolean nameIsTaken(ReadGraph graph, Resource variable, String name) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ if(variable == null)
+ return false;
+
+ SysdynModel sysdynModel = ModelUtils.getModel(graph, variable);
+ if(sysdynModel == null)
+ return true;
+ sysdynModel.update(graph);
+
+ Configuration configuration = sysdynModel.getConfiguration();
+ if(configuration == null)
+ return true;
+
+ // Get the top level model
+ Model rootModel = null;
+ ModuleType moduleType = configuration.getModuleType();
+ if (moduleType != null) {
+ Object o = moduleType.getParent();
+ if (o instanceof Model) {
+ rootModel = (Model)o;
+ }
+ } else {
+ rootModel = configuration.getModel();
+ }
+
+ // Get the top level model (SysdynModel)
+ // Resource library should be used with care if it is not instance of sr.SysdynModel
+ Resource library = graph.getPossibleObject(variable, l0.PartOf);
+ if(library == null) {
+ return true;
+ } else {
+ library = graph.getPossibleObject(library, l0.PartOf);
+ if(library == null) {
+ return true;
+ }
+ }
+
+ // Check if the function is right under the model.
+ if (graph.isInstanceOf(library, sr.SysdynModel)) {
+ // Check that the function name != model name (== library name)
+ if (NameUtils.getSafeName(graph, library).equals(name)) return true;
+
+ if (nameTakenByBuiltInFunction(graph, name)) return true;
+
+ if (nameTakenBySharedFunctionLibrary(graph, library, null, name)) return true;
+
+ if (nameTakenBySheet(sysdynModel, name)) return true;
+ }
+
+ if (nameTakenByTopLevelVariableOrModule(graph, sysdynModel, variable, name)) return true;
+
+ if (rootModel != null) {
+ // Browse through all ModuleTypes within the whole model
+ if (rootModel.containsModuleType(name))
+ return true;
+ }
+
+ if (nameTakenByFunctionFunctionLibraryOrModuleType(graph, library, name)) return true;
+
+ return false;
+ }
+
+ /**
+ * Checks that the syntax of the given name is valid and there
+ * are no other variables that have the same name in the configuration
+ *
+ * @param graph ReadGraph
+ * @param variable The variable that is being renamed
+ * @param name The new name of the variable
+ * @return
+ * @throws DatabaseException
+ */
+ public boolean isValid(ReadGraph graph, Resource variable, String name, boolean hasRange) throws DatabaseException {
+ if(hasRange) {
+ String range = null;
+ if(name.contains("[")) {
+ StringTokenizer st = new StringTokenizer(name, "[]", true);
+ if(st.countTokens() != 4)
+ return false;
+ name = st.nextToken();
+ if(!st.nextToken().equals("[")) return false;
+ range = st.nextToken();
+ if(!st.nextToken().equals("]")) return false;
+ }
+ if(range != null && !ArrayVariableUtils.isRangeValid(graph, variable, range)) return false;
+ }
+ return isValid(graph, variable, name);
+ }
+
+
+ /**
+ * Checks that the syntax of the given name is valid and there
+ * are no other variables that have the same name in the configuration
+ *
+ * @param variable The variable that is being renamed
+ * @param name The new name of the variable
+ * @return
+ * @throws DatabaseException
+ */
+ public boolean isValid(final Resource variable, final String name, final boolean hasRange) {
+ if (variable == null || name == null)
+ return false;
+
+ boolean result = false;
+ try {
+ result = Simantics.getSession().syncRequest(new Read<Boolean>() {
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ return isValid(graph, variable, name, hasRange);
+ }
+
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return result;
+ }
+
+}
-package org.simantics.sysdyn.ui.validation;\r
-\r
-import java.util.Collection;\r
-\r
-import org.simantics.browsing.ui.swt.widgets.TrackedText;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.jfreechart.chart.properties.AllVariablesOfModel;\r
-import org.simantics.jfreechart.chart.properties.ChartVariable;\r
-import org.simantics.jfreechart.chart.properties.VariableExistsValidator;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class ParameterExistsValidator extends VariableExistsValidator {\r
-\r
- public ParameterExistsValidator(WidgetSupport support, TrackedText text) {\r
- super(support, text);\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- if(resource == null)\r
- return;\r
- \r
- SimanticsUI.getSession().asyncRequest(\r
- new AllVariablesOfModel(resource)\r
- , new Listener<Collection<ChartVariable>>() {\r
-\r
- @Override\r
- public void execute(Collection<ChartVariable> variables) {\r
- ParameterExistsValidator.this.variables = variables;\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return ParameterExistsValidator.this.text.isDisposed();\r
- }\r
-\r
- }); \r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.validation;
+
+import java.util.Collection;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.swt.widgets.TrackedText;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+import org.simantics.db.Resource;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.db.procedure.Listener;
+import org.simantics.jfreechart.chart.properties.AllVariablesOfModel;
+import org.simantics.jfreechart.chart.properties.ChartVariable;
+import org.simantics.jfreechart.chart.properties.VariableExistsValidator;
+import org.simantics.utils.ui.AdaptionUtils;
+
+public class ParameterExistsValidator extends VariableExistsValidator {
+
+ public ParameterExistsValidator(WidgetSupport support, TrackedText text) {
+ super(support, text);
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ final Resource resource = AdaptionUtils.adaptToSingle(input, Resource.class);
+ if(resource == null)
+ return;
+
+ Simantics.getSession().asyncRequest(
+ new AllVariablesOfModel(resource)
+ , new Listener<Collection<ChartVariable>>() {
+
+ @Override
+ public void execute(Collection<ChartVariable> variables) {
+ ParameterExistsValidator.this.variables = variables;
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return ParameterExistsValidator.this.text.isDisposed();
+ }
+
+ });
+ }
+
+}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.viewUtils;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.List;\r
-import java.util.Set;\r
-\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.ui.ISelectionListener;\r
-import org.eclipse.ui.IWorkbenchPart;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.common.procedure.adapter.DisposableListener;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.SelectionHints;\r
-import org.simantics.db.layer0.exception.MissingVariableException;\r
-import org.simantics.db.layer0.request.PossibleActiveVariableFromVariable;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.diagram.stubs.DiagramResource;\r
-import org.simantics.modeling.ModelingUtils;\r
-import org.simantics.sysdyn.Functions;\r
-import org.simantics.sysdyn.JFreeChartResource;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynDataSet;\r
-import org.simantics.sysdyn.ui.trend.PinTrend;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-\r
-/**\r
- * Selection listener for listening datasets of the selected variables. Selections can come \r
- * from both diagram and model browser. Listener provides the active datasets\r
- * of the selected variable(s) or the JFreeChart of a selected chart definition. \r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public abstract class SysdynDatasetSelectionListener implements ISelectionListener {\r
-\r
- /**\r
- * Triggered after a variable is selected from diagram or model browser\r
- * Subclasses implement.\r
- * @param activeDatasets Active dataset(s) of the selected variable(s)\r
- */\r
- protected abstract void selectionChanged(Collection<SysdynDataSet> activeDatasets);\r
-\r
- /**\r
- * Triggered after a chart definition is selected from model browser\r
- * Subclasses implement\r
- * \r
- * @param graph ReadGraph\r
- * @param resource Chart definition resource\r
- */\r
- protected abstract void selectionChanged(ReadGraph graph, Resource resource);\r
-\r
-\r
-\r
- public void dispose() {\r
- if(listener != null)\r
- listener.dispose();\r
- }\r
- \r
- DisposableListener<ArrayList<SysdynDataSet>> listener;\r
-\r
- @Override\r
- public void selectionChanged(IWorkbenchPart part, final ISelection selection) {\r
- // Empty selection or pinned trend -> Do nothing\r
- if(selection.isEmpty() || Boolean.TRUE.equals(PinTrend.getState()))\r
- return;\r
-\r
- if(selection instanceof IStructuredSelection) {\r
- Session session = SimanticsUI.peekSession();\r
- if (session == null)\r
- return;\r
- \r
- if(listener != null)\r
- listener.dispose();\r
- \r
- listener = new DisposableListener<ArrayList<SysdynDataSet>>() {\r
-\r
- @Override\r
- public void execute(ArrayList<SysdynDataSet> vars) {\r
- if(vars != null)\r
- selectionChanged(vars);\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
- };\r
-\r
- try {\r
- session.syncRequest(new Read<ArrayList<SysdynDataSet>>() {\r
- @Override\r
- public ArrayList<SysdynDataSet> perform(ReadGraph graph) throws DatabaseException {\r
-\r
- // Model browser provides variables\r
- Collection<Variable> vars = ISelectionUtils.filterSetSelection(selection, Variable.class);\r
-\r
- if(vars.isEmpty()) {\r
- // Selection did not contain variables\r
- Set<Resource> ress = ISelectionUtils.filterSetSelection(selection, Resource.class);\r
- List<Resource> runtimes = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_VARIABLE_RESOURCE, Resource.class);\r
- if(!runtimes.isEmpty()) {\r
- // Selection is most probably in a diagram\r
- Resource runtime = runtimes.get(0);\r
-\r
- // Get variables for selected resources\r
- for(Resource resource : ress) {\r
- Variable variable = getVariable(graph, resource, runtime);\r
- if(variable != null)\r
- vars.add(variable);\r
- }\r
-\r
- // If there is no vars and only one selection, it can be a chart\r
- if(vars.isEmpty() && ress.size() == 1) {\r
- Resource r = ress.iterator().next();\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- if(graph.isInstanceOf(r, jfree.ChartElement)) {\r
- if(graph.hasStatement(r, jfree.ChartElement_component)) {\r
- r = graph.getSingleObject(r, jfree.ChartElement_component);\r
- selectionChanged(graph, r);\r
- return null;\r
- }\r
- }\r
- }\r
-\r
- } else {\r
- // Selection is a jfreechart\r
- if(ress.size() == 1) {\r
- Resource r = ress.iterator().next();\r
- JFreeChartResource jfree = JFreeChartResource.getInstance(graph);\r
- if(graph.isInstanceOf(r, jfree.Chart)) {\r
- selectionChanged(graph, r);\r
- return null;\r
- }\r
- }\r
- }\r
- }\r
-\r
- // Update datasets and add result listeners to models\r
- return getDatasets(graph, vars);\r
-\r
- }\r
- }, listener);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace(); \r
- }\r
- }\r
- }\r
-\r
-\r
-\r
- /**\r
- * Updates datasets for the selected variables\r
- * @param graph ReadGraph\r
- * @param variables Selected variables\r
- * @throws DatabaseException\r
- */\r
- private ArrayList<SysdynDataSet> getDatasets(ReadGraph graph, Collection<Variable> variables) throws DatabaseException {\r
-\r
- ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();\r
- for(Variable variable : variables) {\r
- Variable v = graph.syncRequest(new PossibleActiveVariableFromVariable(variable));\r
- if(v == null)\r
- continue;\r
- // Get all active datasets for the variable and add them to the result\r
- Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");\r
- Object object = null;\r
- if(dsVariable != null)\r
- object = dsVariable.getValue(graph);\r
-\r
- if(object != null && object instanceof ArrayList<?>)\r
- for(Object o : (ArrayList<?>)object) {\r
- if(o instanceof SysdynDataSet)\r
- datasets.add((SysdynDataSet)o);\r
- }\r
- }\r
-\r
- return datasets;\r
- }\r
-\r
-\r
- /**\r
- * Find a variable representing element\r
- * \r
- * @param g ReadGraph\r
- * @param element Element resource\r
- * @param runtime runtime resource\r
- * @return Variable representing element\r
- * @throws DatabaseException\r
- */\r
- private Variable getVariable(ReadGraph g, Resource element, Resource runtime) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- DiagramResource dr = DiagramResource.getInstance(g);\r
- if(runtime == null) return null;\r
- Resource resource = ModelingUtils.getPossibleElementCorrespondendence(g, element);\r
- if(resource != null && g.isInstanceOf(resource, sr.Shadow)) resource = g.getPossibleObject(resource, sr.Shadow_original);\r
- if(resource == null || !g.isInstanceOf(resource, sr.Variable)) return null;\r
- String variableURI = g.getPossibleRelatedValue(runtime, dr.RuntimeDiagram_HasVariable);\r
- if(variableURI != null) {\r
- try {\r
- Variable compositeVariable = Variables.getVariable(g, variableURI);\r
- return compositeVariable.browsePossible(g, resource);\r
- } catch (MissingVariableException e) {}\r
- }\r
- return null;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.ui.viewUtils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.ui.ISelectionListener;
+import org.eclipse.ui.IWorkbenchPart;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.common.procedure.adapter.DisposableListener;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.SelectionHints;
+import org.simantics.db.layer0.exception.MissingVariableException;
+import org.simantics.db.layer0.request.PossibleActiveVariableFromVariable;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.request.Read;
+import org.simantics.diagram.stubs.DiagramResource;
+import org.simantics.modeling.ModelingUtils;
+import org.simantics.sysdyn.Functions;
+import org.simantics.sysdyn.JFreeChartResource;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynDataSet;
+import org.simantics.sysdyn.ui.trend.PinTrend;
+import org.simantics.utils.ui.ISelectionUtils;
+
+/**
+ * Selection listener for listening datasets of the selected variables. Selections can come
+ * from both diagram and model browser. Listener provides the active datasets
+ * of the selected variable(s) or the JFreeChart of a selected chart definition.
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public abstract class SysdynDatasetSelectionListener implements ISelectionListener {
+
+ /**
+ * Triggered after a variable is selected from diagram or model browser
+ * Subclasses implement.
+ * @param activeDatasets Active dataset(s) of the selected variable(s)
+ */
+ protected abstract void selectionChanged(Collection<SysdynDataSet> activeDatasets);
+
+ /**
+ * Triggered after a chart definition is selected from model browser
+ * Subclasses implement
+ *
+ * @param graph ReadGraph
+ * @param resource Chart definition resource
+ */
+ protected abstract void selectionChanged(ReadGraph graph, Resource resource);
+
+
+
+ public void dispose() {
+ if(listener != null)
+ listener.dispose();
+ }
+
+ DisposableListener<ArrayList<SysdynDataSet>> listener;
+
+ @Override
+ public void selectionChanged(IWorkbenchPart part, final ISelection selection) {
+ // Empty selection or pinned trend -> Do nothing
+ if(selection.isEmpty() || Boolean.TRUE.equals(PinTrend.getState()))
+ return;
+
+ if(selection instanceof IStructuredSelection) {
+ Session session = Simantics.peekSession();
+ if (session == null)
+ return;
+
+ if(listener != null)
+ listener.dispose();
+
+ listener = new DisposableListener<ArrayList<SysdynDataSet>>() {
+
+ @Override
+ public void execute(ArrayList<SysdynDataSet> vars) {
+ if(vars != null)
+ selectionChanged(vars);
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+ };
+
+ try {
+ session.syncRequest(new Read<ArrayList<SysdynDataSet>>() {
+ @Override
+ public ArrayList<SysdynDataSet> perform(ReadGraph graph) throws DatabaseException {
+
+ // Model browser provides variables
+ Collection<Variable> vars = ISelectionUtils.filterSetSelection(selection, Variable.class);
+
+ if(vars.isEmpty()) {
+ // Selection did not contain variables
+ Set<Resource> ress = ISelectionUtils.filterSetSelection(selection, Resource.class);
+ List<Resource> runtimes = ISelectionUtils.getPossibleKeys(selection, SelectionHints.KEY_VARIABLE_RESOURCE, Resource.class);
+ if(!runtimes.isEmpty()) {
+ // Selection is most probably in a diagram
+ Resource runtime = runtimes.get(0);
+
+ // Get variables for selected resources
+ for(Resource resource : ress) {
+ Variable variable = getVariable(graph, resource, runtime);
+ if(variable != null)
+ vars.add(variable);
+ }
+
+ // If there is no vars and only one selection, it can be a chart
+ if(vars.isEmpty() && ress.size() == 1) {
+ Resource r = ress.iterator().next();
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ if(graph.isInstanceOf(r, jfree.ChartElement)) {
+ if(graph.hasStatement(r, jfree.ChartElement_component)) {
+ r = graph.getSingleObject(r, jfree.ChartElement_component);
+ selectionChanged(graph, r);
+ return null;
+ }
+ }
+ }
+
+ } else {
+ // Selection is a jfreechart
+ if(ress.size() == 1) {
+ Resource r = ress.iterator().next();
+ JFreeChartResource jfree = JFreeChartResource.getInstance(graph);
+ if(graph.isInstanceOf(r, jfree.Chart)) {
+ selectionChanged(graph, r);
+ return null;
+ }
+ }
+ }
+ }
+
+ // Update datasets and add result listeners to models
+ return getDatasets(graph, vars);
+
+ }
+ }, listener);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+
+
+ /**
+ * Updates datasets for the selected variables
+ * @param graph ReadGraph
+ * @param variables Selected variables
+ * @throws DatabaseException
+ */
+ private ArrayList<SysdynDataSet> getDatasets(ReadGraph graph, Collection<Variable> variables) throws DatabaseException {
+
+ ArrayList<SysdynDataSet> datasets = new ArrayList<SysdynDataSet>();
+ for(Variable variable : variables) {
+ Variable v = graph.syncRequest(new PossibleActiveVariableFromVariable(variable));
+ if(v == null)
+ continue;
+ // Get all active datasets for the variable and add them to the result
+ Variable dsVariable = v.browsePossible(graph, "#" + Functions.ACTIVE_DATASETS + "#");
+ Object object = null;
+ if(dsVariable != null)
+ object = dsVariable.getValue(graph);
+
+ if(object != null && object instanceof ArrayList<?>)
+ for(Object o : (ArrayList<?>)object) {
+ if(o instanceof SysdynDataSet)
+ datasets.add((SysdynDataSet)o);
+ }
+ }
+
+ return datasets;
+ }
+
+
+ /**
+ * Find a variable representing element
+ *
+ * @param g ReadGraph
+ * @param element Element resource
+ * @param runtime runtime resource
+ * @return Variable representing element
+ * @throws DatabaseException
+ */
+ private Variable getVariable(ReadGraph g, Resource element, Resource runtime) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(g);
+ DiagramResource dr = DiagramResource.getInstance(g);
+ if(runtime == null) return null;
+ Resource resource = ModelingUtils.getPossibleElementCorrespondendence(g, element);
+ if(resource != null && g.isInstanceOf(resource, sr.Shadow)) resource = g.getPossibleObject(resource, sr.Shadow_original);
+ if(resource == null || !g.isInstanceOf(resource, sr.Variable)) return null;
+ String variableURI = g.getPossibleRelatedValue(runtime, dr.RuntimeDiagram_HasVariable);
+ if(variableURI != null) {
+ try {
+ Variable compositeVariable = Variables.getVariable(g, variableURI);
+ return compositeVariable.browsePossible(g, resource);
+ } catch (MissingVariableException e) {}
+ }
+ return null;
+ }
+
+}
-package org.simantics.sysdyn.ui.wizards.functions;\r
-\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDropTargetNode;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-\r
-public class SharedFunctionsFolderNode extends FunctionLibraryNode<Resource> implements IDropTargetNode {\r
-\r
- public SharedFunctionsFolderNode(Resource resource) {\r
- super(resource);\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- graph.deny(data, l0.PartOf);\r
- graph.deny(data, l0.IsLinkedTo_Inverse);\r
-\r
- // TODO: remove file\r
- }\r
- });\r
- }\r
- \r
- @Override\r
- public void drop(Object data) {\r
- final Resource[] resources = ResourceAdaptionUtils.toResources(data);\r
- final Resource library = this.data;\r
- if(resources.length > 0) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- for(Resource tobeMoved : resources) {\r
- if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||\r
- graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {\r
- graph.deny(tobeMoved, l0.PartOf);\r
- graph.claim(tobeMoved, l0.PartOf, library);\r
- }\r
- }\r
- }\r
- });\r
- }\r
- }\r
-\r
-}\r
+package org.simantics.sysdyn.ui.wizards.functions;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDropTargetNode;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.browser.nodes.FunctionLibraryNode;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+
+public class SharedFunctionsFolderNode extends FunctionLibraryNode<Resource> implements IDropTargetNode {
+
+ public SharedFunctionsFolderNode(Resource resource) {
+ super(resource);
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ graph.deny(data, l0.PartOf);
+ graph.deny(data, l0.IsLinkedTo_Inverse);
+
+ // TODO: remove file
+ }
+ });
+ }
+
+ @Override
+ public void drop(Object data) {
+ final Resource[] resources = ResourceAdaptionUtils.toResources(data);
+ final Resource library = this.data;
+ if(resources.length > 0) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ for(Resource tobeMoved : resources) {
+ if(graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunction) ||
+ graph.isInstanceOf(tobeMoved, sr.SysdynModelicaFunctionLibrary)) {
+ graph.deny(tobeMoved, l0.PartOf);
+ graph.claim(tobeMoved, l0.PartOf, library);
+ }
+ }
+ }
+ });
+ }
+ }
+
+}
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
+import org.simantics.Simantics;
import org.simantics.browsing.ui.common.AdaptableHintContext;
import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
import org.simantics.databoard.Bindings;
import org.simantics.layer0.Layer0;
import org.simantics.sysdyn.SysdynResource;
import org.simantics.sysdyn.ui.Activator;
-import org.simantics.ui.SimanticsUI;
import org.simantics.utils.datastructures.ArrayMap;
public class WizardFunctionsExportPage extends WizardPage {
Label title = new Label(workArea, SWT.NONE);
title.setText("Select Function Library to export:");
- Resource input = SimanticsUI.getProject().get();
+ Resource input = Simantics.getProject().get();
functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(
"displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
String name = null;
try {
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {
+ name = Simantics.getSession().syncRequest(new Read<String>() {
@Override
public String perform(ReadGraph graph) throws DatabaseException {
}
if(name == null) return false;
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {
+ Simantics.getSession().asyncRequest(new ReadRequest() {
@Override
public void run(ReadGraph graph) throws DatabaseException {
TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, functionLibrary);
String root = null;
try {
- root = SimanticsUI.getSession().syncRequest(new Read<String>() {
+ root = Simantics.getSession().syncRequest(new Read<String>() {
@Override
public String perform(ReadGraph graph) throws DatabaseException {
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
+import org.simantics.Simantics;
import org.simantics.browsing.ui.common.AdaptableHintContext;
import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
import org.simantics.db.ReadGraph;
import org.simantics.db.request.Read;
import org.simantics.sysdyn.SysdynResource;
import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
-import org.simantics.ui.SimanticsUI;
import org.simantics.utils.datastructures.ArrayMap;
public class WizardFunctionsImportPage extends WizardPage{
title.setText("Select import location:");
try {
- Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {
+ Resource input = Simantics.getSession().syncRequest(new Read<Resource>() {
@Override
public Resource perform(ReadGraph graph)
throws DatabaseException {
- Resource model = SimanticsUI.getProject().get();
+ Resource model = Simantics.getProject().get();
return model;
}
try {
Boolean hasSharedOntologies;
- hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {
+ hasSharedOntologies = Simantics.getSession().syncRequest(new Read<Boolean>() {
@Override
public Boolean perform(ReadGraph graph) throws DatabaseException {
});
if(!hasSharedOntologies) {
- SimanticsUI.getSession().syncRequest(new WriteRequest() {
+ Simantics.getSession().syncRequest(new WriteRequest() {
@Override
public void perform(WriteGraph graph) throws DatabaseException {
final Resource root = ia.getRoot();
try {
- SimanticsUI.getSession().syncRequest(new WriteRequest() {
+ Simantics.getSession().syncRequest(new WriteRequest() {
@Override
public void perform(WriteGraph graph) throws DatabaseException {
-package org.simantics.sysdyn.ui.wizards.mdl;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.runtime.Path;\r
-import org.eclipse.jface.layout.PixelConverter;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.modelImport.MdlParser;\r
-import org.simantics.sysdyn.modelImport.model.Model;\r
-import org.simantics.sysdyn.modelImport.model.WriteContext;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class WizardMdlImportPage extends WizardPage{\r
- \r
- // dialog store id constants\r
- private Text filePathField;\r
- \r
- // Keep track of the archive that we browsed to last time\r
- // the wizard was invoked.\r
- private static String previouslyBrowsedFile = "";\r
-\r
- private Button browseDirectoriesButton;\r
- \r
- /**\r
- * Creates a new project creation wizard page.\r
- * \r
- */\r
- public WizardMdlImportPage() {\r
- this("wizardMdlImportPage", null, null); //$NON-NLS-1$\r
- }\r
-\r
- /**\r
- * Create a new instance of the receiver.\r
- * \r
- * @param pageName\r
- */\r
- public WizardMdlImportPage(String pageName) {\r
- this(pageName,null, null);\r
- }\r
- \r
- /**\r
- * More (many more) parameters.\r
- * \r
- * @param pageName\r
- * @param initialPath\r
- * @param currentSelection\r
- * @since 3.5\r
- */\r
- public WizardMdlImportPage(String pageName,String initialPath,\r
- IStructuredSelection currentSelection) {\r
- super(pageName);\r
- setPageComplete(false);\r
- setTitle("Import Vensim model");\r
- setDescription("Choose the Vensim model file (.mdl), then press Finish.");\r
- }\r
-\r
- public void createControl(Composite parent) {\r
- \r
- initializeDialogUnits(parent);\r
-\r
- Composite workArea = new Composite(parent, SWT.NONE);\r
- setControl(workArea);\r
-\r
- workArea.setLayout(new GridLayout());\r
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
-\r
- createProjectsRoot(workArea); \r
- }\r
- \r
- private void createProjectsRoot(Composite workArea) {\r
-\r
- // set label for field\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select Vensim model source:");\r
- \r
- Composite projectGroup = new Composite(workArea, SWT.NONE);\r
- GridLayout layout = new GridLayout();\r
- layout.numColumns = 2;\r
- layout.makeColumnsEqualWidth = false;\r
- layout.marginWidth = 0;\r
-\r
- projectGroup.setLayout(layout);\r
- projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
-\r
- // model location entry field\r
- this.filePathField = new Text(projectGroup, SWT.BORDER);\r
- \r
- GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
- directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
- filePathField.setLayoutData(directoryPathData);\r
- filePathField.addModifyListener(new ModifyListener(){\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- previouslyBrowsedFile = filePathField.getText(); \r
- }\r
- });\r
- if (previouslyBrowsedFile != null){\r
- filePathField.setText(previouslyBrowsedFile);\r
- validatePage();\r
- }\r
- \r
- // browse button\r
- browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
- browseDirectoriesButton.setText("Browse");\r
- setButtonLayoutData(browseDirectoriesButton);\r
- \r
- browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
- * elected(org.eclipse.swt.events.SelectionEvent)\r
- */\r
- public void widgetSelected(SelectionEvent e) {\r
- handleLocationDirectoryButtonPressed();\r
- }\r
- });\r
- \r
- }\r
- \r
- //Set filePathField active\r
- public void setVisible(boolean visible) {\r
- super.setVisible(visible);\r
- this.filePathField.setFocus();\r
- }\r
- \r
- //Open dialog for choosing the file\r
- protected void handleLocationDirectoryButtonPressed() {\r
- \r
- final Shell shell = filePathField.getShell();\r
-\r
- FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
- String[] ext = {"*.mdl"};\r
- dialog.setFilterExtensions(ext);\r
- dialog.setText("Import Vensim model (.mdl)");\r
-\r
- String dirName = filePathField.getText().trim();\r
- \r
- File path = new File(dirName);\r
- if (path.exists()) {\r
- dialog.setFilterPath(new Path(dirName).toOSString()); \r
- }\r
- \r
- String selectedFile = dialog.open();\r
- if (selectedFile != null) {\r
- filePathField.setText(selectedFile);\r
- validatePage();\r
- }\r
-\r
- }\r
- \r
- //Create project after finish is pressed.\r
- public boolean createProjects() {\r
- \r
- final Resource project = SimanticsUI.getProject().get();\r
- if(project == null) return false;\r
-\r
- String selected = previouslyBrowsedFile;\r
- if(selected == null) return false;\r
- \r
- File file = new File(selected);\r
- \r
- // TODO: is this wizard actually used anywhere?\r
- final Model model;\r
- \r
- try {\r
- model = new MdlParser().parse(file);\r
- }\r
- catch (Exception e) {\r
- e.printStackTrace();\r
- return false;\r
- }\r
- \r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- model.write(graph, project, new WriteContext());\r
- }\r
- });\r
- \r
- return true;\r
- \r
- }\r
- void validatePage(){\r
- \r
- if (previouslyBrowsedFile.isEmpty()){\r
- setPageComplete(false);\r
- return;\r
- }\r
- \r
- setPageComplete(true);\r
- }\r
-}\r
+package org.simantics.sysdyn.ui.wizards.mdl;
+
+import java.io.File;
+
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.layout.PixelConverter;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.modelImport.MdlParser;
+import org.simantics.sysdyn.modelImport.model.Model;
+import org.simantics.sysdyn.modelImport.model.WriteContext;
+
+public class WizardMdlImportPage extends WizardPage{
+
+ // dialog store id constants
+ private Text filePathField;
+
+ // Keep track of the archive that we browsed to last time
+ // the wizard was invoked.
+ private static String previouslyBrowsedFile = "";
+
+ private Button browseDirectoriesButton;
+
+ /**
+ * Creates a new project creation wizard page.
+ *
+ */
+ public WizardMdlImportPage() {
+ this("wizardMdlImportPage", null, null); //$NON-NLS-1$
+ }
+
+ /**
+ * Create a new instance of the receiver.
+ *
+ * @param pageName
+ */
+ public WizardMdlImportPage(String pageName) {
+ this(pageName,null, null);
+ }
+
+ /**
+ * More (many more) parameters.
+ *
+ * @param pageName
+ * @param initialPath
+ * @param currentSelection
+ * @since 3.5
+ */
+ public WizardMdlImportPage(String pageName,String initialPath,
+ IStructuredSelection currentSelection) {
+ super(pageName);
+ setPageComplete(false);
+ setTitle("Import Vensim model");
+ setDescription("Choose the Vensim model file (.mdl), then press Finish.");
+ }
+
+ public void createControl(Composite parent) {
+
+ initializeDialogUnits(parent);
+
+ Composite workArea = new Composite(parent, SWT.NONE);
+ setControl(workArea);
+
+ workArea.setLayout(new GridLayout());
+ workArea.setLayoutData(new GridData(GridData.FILL_BOTH
+ | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
+
+ createProjectsRoot(workArea);
+ }
+
+ private void createProjectsRoot(Composite workArea) {
+
+ // set label for field
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select Vensim model source:");
+
+ Composite projectGroup = new Composite(workArea, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ layout.makeColumnsEqualWidth = false;
+ layout.marginWidth = 0;
+
+ projectGroup.setLayout(layout);
+ projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ // model location entry field
+ this.filePathField = new Text(projectGroup, SWT.BORDER);
+
+ GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);
+ directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);
+ filePathField.setLayoutData(directoryPathData);
+ filePathField.addModifyListener(new ModifyListener(){
+ @Override
+ public void modifyText(ModifyEvent e) {
+ previouslyBrowsedFile = filePathField.getText();
+ }
+ });
+ if (previouslyBrowsedFile != null){
+ filePathField.setText(previouslyBrowsedFile);
+ validatePage();
+ }
+
+ // browse button
+ browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);
+ browseDirectoriesButton.setText("Browse");
+ setButtonLayoutData(browseDirectoriesButton);
+
+ browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetS
+ * elected(org.eclipse.swt.events.SelectionEvent)
+ */
+ public void widgetSelected(SelectionEvent e) {
+ handleLocationDirectoryButtonPressed();
+ }
+ });
+
+ }
+
+ //Set filePathField active
+ public void setVisible(boolean visible) {
+ super.setVisible(visible);
+ this.filePathField.setFocus();
+ }
+
+ //Open dialog for choosing the file
+ protected void handleLocationDirectoryButtonPressed() {
+
+ final Shell shell = filePathField.getShell();
+
+ FileDialog dialog = new FileDialog(shell, SWT.OPEN);
+ String[] ext = {"*.mdl"};
+ dialog.setFilterExtensions(ext);
+ dialog.setText("Import Vensim model (.mdl)");
+
+ String dirName = filePathField.getText().trim();
+
+ File path = new File(dirName);
+ if (path.exists()) {
+ dialog.setFilterPath(new Path(dirName).toOSString());
+ }
+
+ String selectedFile = dialog.open();
+ if (selectedFile != null) {
+ filePathField.setText(selectedFile);
+ validatePage();
+ }
+
+ }
+
+ //Create project after finish is pressed.
+ public boolean createProjects() {
+
+ final Resource project = Simantics.getProject().get();
+ if(project == null) return false;
+
+ String selected = previouslyBrowsedFile;
+ if(selected == null) return false;
+
+ File file = new File(selected);
+
+ // TODO: is this wizard actually used anywhere?
+ final Model model;
+
+ try {
+ model = new MdlParser().parse(file);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ model.write(graph, project, new WriteContext());
+ }
+ });
+
+ return true;
+
+ }
+ void validatePage(){
+
+ if (previouslyBrowsedFile.isEmpty()){
+ setPageComplete(false);
+ return;
+ }
+
+ setPageComplete(true);
+ }
+}
\ No newline at end of file
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
+import org.simantics.Simantics;
import org.simantics.browsing.ui.common.AdaptableHintContext;
import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
import org.simantics.db.ReadGraph;
import org.simantics.graph.db.TransferableGraphs;
import org.simantics.sysdyn.SysdynResource;
import org.simantics.sysdyn.ui.Activator;
-import org.simantics.ui.SimanticsUI;
import org.simantics.utils.datastructures.ArrayMap;
public class WizardModelsExportPage extends WizardPage {
Label title = new Label(workArea, SWT.NONE);
title.setText("Select Model to export:");
- Resource input = SimanticsUI.getProject().get();
+ Resource input = Simantics.getProject().get();
modelExplorer = new GraphExplorerComposite(ArrayMap.keys(
"displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
// FIXME: Model browser doesn't change its selection even if the selected object is removed,
// so you can try to export a removed model
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {
+ Simantics.getSession().asyncRequest(new ReadRequest() {
@Override
public void run(ReadGraph graph) throws DatabaseException {
-package org.simantics.sysdyn.ui.wizards.models;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.jface.layout.PixelConverter;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class WizardModelsImportPage extends WizardPage{\r
- \r
- private Text filePathField;\r
- \r
- // Keep track of the archive that we browsed to last time\r
- // the wizard was invoked.\r
- private static String previouslyBrowsedFile = "";\r
-\r
- private Button browseDirectoriesButton;\r
-\r
- private Shell shell;\r
- \r
- /**\r
- * Creates a new project creation wizard page.\r
- * \r
- */\r
- public WizardModelsImportPage() {\r
- this("wizardModelsImportPage", null, null); //$NON-NLS-1$\r
- }\r
-\r
- /**\r
- * Create a new instance of the receiver.\r
- * \r
- * @param pageName\r
- */\r
- public WizardModelsImportPage(String pageName) {\r
- this(pageName,null, null);\r
- }\r
- \r
- /**\r
- * More (many more) parameters.\r
- * \r
- * @param pageName\r
- * @param initialPath\r
- * @param currentSelection\r
- * @since 3.5\r
- */\r
- public WizardModelsImportPage(String pageName,String initialPath,\r
- IStructuredSelection currentSelection) {\r
- super(pageName);\r
- //this.initialPath = initialPath;\r
- //this.currentSelection = currentSelection;\r
- setPageComplete(false);\r
- setTitle("Import Model");\r
- setDescription("Choose the Model file, then press Finish.");\r
- }\r
-\r
- \r
- public void createControl(Composite parent) {\r
-\r
- initializeDialogUnits(parent);\r
-\r
- Composite workArea = new Composite(parent, SWT.NONE);\r
- setControl(workArea);\r
-\r
- workArea.setLayout(new GridLayout());\r
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
-\r
- createProjectsRoot(workArea);\r
- }\r
- \r
- private void createProjectsRoot(Composite workArea) {\r
-\r
- // set label for field\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select Model source:");\r
- \r
- Composite projectGroup = new Composite(workArea, SWT.NONE);\r
- GridLayout layout = new GridLayout();\r
- layout.numColumns = 2;\r
- layout.makeColumnsEqualWidth = false;\r
- layout.marginWidth = 0;\r
-\r
- projectGroup.setLayout(layout);\r
- projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
-\r
- // model location entry field\r
- this.filePathField = new Text(projectGroup, SWT.BORDER);\r
- \r
- GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
- directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
- filePathField.setLayoutData(directoryPathData);\r
- filePathField.addModifyListener(new ModifyListener(){\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- previouslyBrowsedFile = filePathField.getText();\r
- }\r
- });\r
- if (previouslyBrowsedFile != null){\r
- filePathField.setText(previouslyBrowsedFile);\r
- validatePage();\r
- }\r
- \r
- // browse button\r
- browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
- browseDirectoriesButton.setText("Browse");\r
- setButtonLayoutData(browseDirectoriesButton);\r
- \r
- browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
- * elected(org.eclipse.swt.events.SelectionEvent)\r
- */\r
- public void widgetSelected(SelectionEvent e) {\r
- setErrorMessage(null);\r
- handleLocationDirectoryButtonPressed();\r
- }\r
- }); \r
- }\r
-\r
- \r
- //Set filePathField active\r
- public void setVisible(boolean visible) {\r
- super.setVisible(visible);\r
- this.filePathField.setFocus();\r
- }\r
- \r
- \r
- //Open dialog for choosing the file\r
- protected void handleLocationDirectoryButtonPressed() {\r
- \r
- shell = filePathField.getShell();\r
- \r
- FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
- \r
- String[] ext = {"*.sysdyn; *.tg", "*.*"};\r
- dialog.setFilterExtensions(ext);\r
- \r
- dialog.setText("Import Model");\r
-\r
- String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);\r
- if(path.isEmpty() || !(new File(path).exists()))\r
- path = Platform.getLocation().toOSString();\r
- dialog.setFilterPath(path);\r
- \r
- String selectedFile = dialog.open();\r
- if (selectedFile != null) {\r
- filePathField.setText(selectedFile);\r
- validatePage();\r
- }\r
- \r
- }\r
-\r
- //Create project after finish is pressed.\r
- public boolean createProjects() {\r
- \r
- Resource project = SimanticsUI.getProject().get();\r
- if(project == null){\r
- setErrorMessage("Error when retrieving resource");\r
- return false;\r
- }\r
- \r
- final String selected = previouslyBrowsedFile;\r
- if(selected == null){\r
- setErrorMessage("No file selected");\r
- return false;\r
- }\r
-\r
- try {\r
- IStatus status = ImportUtilsUI.importModelFile(selected, null);\r
- if(status == null || !status.equals(Status.OK_STATUS)) {\r
- setErrorMessage(status.getMessage());\r
- return false;\r
- }\r
- return true;\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- return false;\r
- }\r
- \r
- /*\r
- TransferableGraph1 tg = null;\r
- try {\r
- tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
- } catch (RuntimeBindingConstructionException e) {\r
- e.printStackTrace();\r
- } catch (IOException e) { \r
- try {\r
- OldTransferableGraph1 otg = (OldTransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(OldTransferableGraph1.class));\r
- tg = new TransferableGraph1(otg.resourceCount, otg.identities, otg.statements, otg.values);\r
- } catch (RuntimeBindingConstructionException e1) {\r
- e1.printStackTrace();\r
- } catch (IOException e1) {\r
- setErrorMessage("The imported file is not of type: System Dynamics Model");\r
- return false;\r
- }\r
- }\r
- if(tg == null){ \r
- setErrorMessage("The imported file is not of type: System Dynamics Model");\r
- return false;\r
- }\r
- \r
- try {\r
- \r
- DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(project);\r
- DefaultPasteHandler.defaultExecute(tg, SimanticsUI.getProject().get(), ia);\r
- \r
- // Check that imported resource was actually a model \r
- //and fix changes made to old ontology versions\r
- final Resource root = ia.getRoot();\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- \r
- if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModel)) {\r
- Resource instanceOf = graph.getPossibleObject(root, Layer0.getInstance(graph).InstanceOf);\r
- String type = "...";\r
- if(instanceOf != null)\r
- type = NameUtils.getSafeName(graph, instanceOf);\r
- else {\r
- Resource inheritedFrom = graph.getPossibleObject(root, Layer0.getInstance(graph).Inherits);\r
- if(inheritedFrom != null)\r
- type = NameUtils.getSafeName(graph, inheritedFrom);\r
- }\r
- graph.deny(root, Layer0.getInstance(graph).PartOf);\r
- error = type;\r
- } else {\r
- updateOldConfigurationToBaseRealization(graph, root);\r
- addDefaultOntologyLinks(graph, root);\r
- addURIsToDiagrams(graph, root);\r
- addSpreadSheetBook(graph, root);\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- \r
- if (!error.isEmpty()){\r
- setErrorMessage("The imported file is not of type: System Dynamics Model (" + error +")");\r
- error = "";\r
- return false;\r
- }\r
- */\r
-// if(status == null || !status.equals(Status.OK_STATUS)) {\r
-// setErrorMessage(status.getMessage());\r
-// return false;\r
-// }\r
-// return true; \r
- }\r
- \r
- /**\r
- * In old versions base realization was separate. Newer versions use configuration as base realization. \r
- * @param graph WriteGraph\r
- * @param model Imported model\r
- */\r
- /*\r
- private static void updateOldConfigurationToBaseRealization(WriteGraph graph, Resource model) {\r
- Layer0X L0X = Layer0X.getInstance(graph);\r
- try {\r
- Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
- if(configuration != null && !graph.hasStatement(configuration, L0X.IsBaseRealizationOf, model))\r
- graph.claim(configuration, L0X.IsBaseRealizationOf, model);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- }\r
- */\r
- \r
- /**\r
- * Links should be exported and imported automatically. If it has failed, the \r
- * default ontology links sysdyn and layer0 are added.\r
- * \r
- * @param graph WriteGraph\r
- * @param model Imported model\r
- */\r
- /*\r
- private static void addDefaultOntologyLinks(WriteGraph graph, Resource model) {\r
- try {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- // The links should be exported and imported automatically\r
- Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1");\r
- Resource layer0 = graph.getResource("http://www.simantics.org/Layer0-1.1");\r
- if(!graph.hasStatement(model, l0.IsLinkedTo, sysdyn))\r
- graph.claim(model, l0.IsLinkedTo, sysdyn);\r
- if(!graph.hasStatement(model, l0.IsLinkedTo, layer0))\r
- graph.claim(model, l0.IsLinkedTo, layer0);\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- private static void addURIsToDiagrams(WriteGraph graph, Resource model) {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SimulationResource simu = SimulationResource.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
- try {\r
- HashSet<Resource> configurations = new HashSet<Resource>();\r
- \r
- Resource configuration = graph.getPossibleObject(model, simu.HasConfiguration);\r
- if(configuration != null) \r
- configurations.add(configuration);\r
- \r
- for(Resource r : graph.getObjects(model, l0.ConsistsOf)) {\r
- if(graph.isInheritedFrom(r, sr.Module)) {\r
- Resource moduleConfiguration = graph.getPossibleObject(r, sr2.IsDefinedBy);\r
- if(moduleConfiguration != null)\r
- configurations.add(moduleConfiguration);\r
- }\r
- }\r
- \r
- for(Resource conf : configurations) {\r
- Resource configurationDiagram = graph.getPossibleObject(conf, mr.CompositeToDiagram);\r
- if(configurationDiagram != null && !graph.hasStatement(configurationDiagram, l0.PartOf)) {\r
- GraphUtils.create2(graph, l0.Library, \r
- l0.HasName, "__CONTAINER__",\r
- l0.PartOf, conf,\r
- l0.ConsistsOf, configurationDiagram);\r
- }\r
- }\r
- \r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
-*/ \r
- \r
- /**\r
- * Add a missing spreadsheet book to the model\r
- * \r
- * @param graph\r
- * @param model\r
- */\r
- /*\r
- private static void addSpreadSheetBook(WriteGraph graph, Resource model) {\r
- try {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SpreadsheetResource ssr = SpreadsheetResource.getInstance(graph);\r
- SimulationResource simu = SimulationResource.getInstance(graph);\r
- Resource conf = graph.getPossibleObject(model, simu.HasConfiguration);\r
- if(conf != null && graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, ssr.Book)).isEmpty()) {\r
- Resource book = graph.newResource();\r
- graph.claim(book, l0.InstanceOf, null, ssr.Book);\r
- graph.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING);\r
- graph.claim(conf, l0.ConsistsOf, l0.PartOf, book);\r
-\r
- createSheet(graph, book, "Sheet1", new String[] { }, new int[] { 50 });\r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- */\r
- /**\r
- * Create a sheet (Copied from SysdynProject)\r
- * \r
- * @param graph\r
- * @param book\r
- * @param name\r
- * @param colNames\r
- * @param colWidths\r
- * @return\r
- * @throws DatabaseException\r
- */\r
- /*\r
- private static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {\r
-\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- Layer0X L0X = Layer0X.getInstance(graph);\r
- SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);\r
-\r
- Resource result = graph.newResource();\r
- graph.claim(result, L0.InstanceOf, null, sr.Spreadsheet);\r
-\r
- if(name == null) {\r
- name = NameUtils.findFreshEscapedName(graph, "Sheet", book, sr.HasSheet);\r
- }\r
- graph.claimLiteral(result, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);\r
- graph.claim(book, L0.ConsistsOf, L0.PartOf, result);\r
-\r
- {\r
- Resource newCell = graph.newResource();\r
- graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
- graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Dimensions", Bindings.STRING);\r
- graph.addLiteral(newCell, sr.Dimensions_fitColumns, sr.Dimensions_fitColumns_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
- graph.addLiteral(newCell, sr.Dimensions_fitRows, sr.Dimensions_fitRows_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
- graph.addLiteral(newCell, sr.Dimensions_columnCount, sr.Dimensions_columnCount_Inverse, L0.Integer, 128, Bindings.INTEGER);\r
- graph.addLiteral(newCell, sr.Dimensions_rowCount, sr.Dimensions_rowCount_Inverse, L0.Integer, 256, Bindings.INTEGER);\r
- graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
- }\r
-\r
- {\r
- Resource newCell = graph.newResource();\r
- graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
- graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Headers", Bindings.STRING);\r
- graph.addLiteral(newCell, sr.Headers_columnLabels, sr.Headers_columnLabels_Inverse, L0.StringArray, colNames, Bindings.STRING_ARRAY);\r
- graph.addLiteral(newCell, sr.Headers_columnWidths, sr.Headers_columnWidths_Inverse, L0.IntegerArray, colWidths, Bindings.INT_ARRAY);\r
- graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
- }\r
-\r
- {\r
- \r
- double[] doubles = new double[10*2];\r
- for(int i=0;i<10*2;i++) doubles[i] = i;\r
- \r
- Resource newCell = graph.newResource();\r
- graph.claim(newCell, L0.InstanceOf, null, sr.DoubleArrayCell);\r
- graph.addLiteral(newCell, sr.DoubleArrayCell_HasWidth, sr.DoubleArrayCell_HasWidth_Inverse, L0.Integer, 10, Bindings.INTEGER);\r
- graph.addLiteral(newCell, sr.HasLocation, sr.HasLocation_Inverse, L0.String, "B2", Bindings.STRING);\r
- graph.addLiteral(newCell, sr.DoubleArrayCell_HasDoubleArray, sr.DoubleArrayCell_HasDoubleArray_Inverse, L0.DoubleArray, doubles, Bindings.DOUBLE_ARRAY);\r
- graph.claim(result, L0X.HasChildVariables, L0X.HasChildVariables_Inverse, newCell);\r
- \r
- }\r
- \r
- return result;\r
-\r
- }\r
- */\r
- void validatePage(){\r
- \r
- if (previouslyBrowsedFile.isEmpty()){\r
- setPageComplete(false);\r
- return;\r
- }\r
- setErrorMessage(null);\r
- setPageComplete(true);\r
- }\r
+package org.simantics.sysdyn.ui.wizards.models;
+
+import java.io.File;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.layout.PixelConverter;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Text;
+import org.simantics.Simantics;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
+
+public class WizardModelsImportPage extends WizardPage{
+
+ private Text filePathField;
+
+ // Keep track of the archive that we browsed to last time
+ // the wizard was invoked.
+ private static String previouslyBrowsedFile = "";
+
+ private Button browseDirectoriesButton;
+
+ private Shell shell;
+
+ /**
+ * Creates a new project creation wizard page.
+ *
+ */
+ public WizardModelsImportPage() {
+ this("wizardModelsImportPage", null, null); //$NON-NLS-1$
+ }
+
+ /**
+ * Create a new instance of the receiver.
+ *
+ * @param pageName
+ */
+ public WizardModelsImportPage(String pageName) {
+ this(pageName,null, null);
+ }
+
+ /**
+ * More (many more) parameters.
+ *
+ * @param pageName
+ * @param initialPath
+ * @param currentSelection
+ * @since 3.5
+ */
+ public WizardModelsImportPage(String pageName,String initialPath,
+ IStructuredSelection currentSelection) {
+ super(pageName);
+ //this.initialPath = initialPath;
+ //this.currentSelection = currentSelection;
+ setPageComplete(false);
+ setTitle("Import Model");
+ setDescription("Choose the Model file, then press Finish.");
+ }
+
+
+ public void createControl(Composite parent) {
+
+ initializeDialogUnits(parent);
+
+ Composite workArea = new Composite(parent, SWT.NONE);
+ setControl(workArea);
+
+ workArea.setLayout(new GridLayout());
+ workArea.setLayoutData(new GridData(GridData.FILL_BOTH
+ | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
+
+ createProjectsRoot(workArea);
+ }
+
+ private void createProjectsRoot(Composite workArea) {
+
+ // set label for field
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select Model source:");
+
+ Composite projectGroup = new Composite(workArea, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ layout.makeColumnsEqualWidth = false;
+ layout.marginWidth = 0;
+
+ projectGroup.setLayout(layout);
+ projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+
+ // model location entry field
+ this.filePathField = new Text(projectGroup, SWT.BORDER);
+
+ GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);
+ directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);
+ filePathField.setLayoutData(directoryPathData);
+ filePathField.addModifyListener(new ModifyListener(){
+ @Override
+ public void modifyText(ModifyEvent e) {
+ previouslyBrowsedFile = filePathField.getText();
+ }
+ });
+ if (previouslyBrowsedFile != null){
+ filePathField.setText(previouslyBrowsedFile);
+ validatePage();
+ }
+
+ // browse button
+ browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);
+ browseDirectoriesButton.setText("Browse");
+ setButtonLayoutData(browseDirectoriesButton);
+
+ browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.swt.events.SelectionAdapter#widgetS
+ * elected(org.eclipse.swt.events.SelectionEvent)
+ */
+ public void widgetSelected(SelectionEvent e) {
+ setErrorMessage(null);
+ handleLocationDirectoryButtonPressed();
+ }
+ });
+ }
+
+
+ //Set filePathField active
+ public void setVisible(boolean visible) {
+ super.setVisible(visible);
+ this.filePathField.setFocus();
+ }
+
+
+ //Open dialog for choosing the file
+ protected void handleLocationDirectoryButtonPressed() {
+
+ shell = filePathField.getShell();
+
+ FileDialog dialog = new FileDialog(shell, SWT.OPEN);
+
+ String[] ext = {"*.sysdyn; *.tg", "*.*"};
+ dialog.setFilterExtensions(ext);
+
+ dialog.setText("Import Model");
+
+ String path = Activator.getDefault().getPreferenceStore().getString(ImportUtilsUI.IMPORTMODELTPATH);
+ if(path.isEmpty() || !(new File(path).exists()))
+ path = Platform.getLocation().toOSString();
+ dialog.setFilterPath(path);
+
+ String selectedFile = dialog.open();
+ if (selectedFile != null) {
+ filePathField.setText(selectedFile);
+ validatePage();
+ }
+
+ }
+
+ //Create project after finish is pressed.
+ public boolean createProjects() {
+
+ Resource project = Simantics.getProject().get();
+ if(project == null){
+ setErrorMessage("Error when retrieving resource");
+ return false;
+ }
+
+ final String selected = previouslyBrowsedFile;
+ if(selected == null){
+ setErrorMessage("No file selected");
+ return false;
+ }
+
+ try {
+ IStatus status = ImportUtilsUI.importModelFile(selected, null);
+ if(status == null || !status.equals(Status.OK_STATUS)) {
+ setErrorMessage(status.getMessage());
+ return false;
+ }
+ return true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+
+ /*
+ TransferableGraph1 tg = null;
+ try {
+ tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));
+ } catch (RuntimeBindingConstructionException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ try {
+ OldTransferableGraph1 otg = (OldTransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(OldTransferableGraph1.class));
+ tg = new TransferableGraph1(otg.resourceCount, otg.identities, otg.statements, otg.values);
+ } catch (RuntimeBindingConstructionException e1) {
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ setErrorMessage("The imported file is not of type: System Dynamics Model");
+ return false;
+ }
+ }
+ if(tg == null){
+ setErrorMessage("The imported file is not of type: System Dynamics Model");
+ return false;
+ }
+
+ try {
+
+ DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(project);
+ DefaultPasteHandler.defaultExecute(tg, Simantics.getProject().get(), ia);
+
+ // Check that imported resource was actually a model
+ //and fix changes made to old ontology versions
+ final Resource root = ia.getRoot();
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+
+ if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModel)) {
+ Resource instanceOf = graph.getPossibleObject(root, Layer0.getInstance(graph).InstanceOf);
+ String type = "...";
+ if(instanceOf != null)
+ type = NameUtils.getSafeName(graph, instanceOf);
+ else {
+ Resource inheritedFrom = graph.getPossibleObject(root, Layer0.getInstance(graph).Inherits);
+ if(inheritedFrom != null)
+ type = NameUtils.getSafeName(graph, inheritedFrom);
+ }
+ graph.deny(root, Layer0.getInstance(graph).PartOf);
+ error = type;
+ } else {
+ updateOldConfigurationToBaseRealization(graph, root);
+ addDefaultOntologyLinks(graph, root);
+ addURIsToDiagrams(graph, root);
+ addSpreadSheetBook(graph, root);
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ if (!error.isEmpty()){
+ setErrorMessage("The imported file is not of type: System Dynamics Model (" + error +")");
+ error = "";
+ return false;
+ }
+ */
+// if(status == null || !status.equals(Status.OK_STATUS)) {
+// setErrorMessage(status.getMessage());
+// return false;
+// }
+// return true;
+ }
+
+ /**
+ * In old versions base realization was separate. Newer versions use configuration as base realization.
+ * @param graph WriteGraph
+ * @param model Imported model
+ */
+ /*
+ private static void updateOldConfigurationToBaseRealization(WriteGraph graph, Resource model) {
+ Layer0X L0X = Layer0X.getInstance(graph);
+ try {
+ Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);
+ if(configuration != null && !graph.hasStatement(configuration, L0X.IsBaseRealizationOf, model))
+ graph.claim(configuration, L0X.IsBaseRealizationOf, model);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ }
+ */
+
+ /**
+ * Links should be exported and imported automatically. If it has failed, the
+ * default ontology links sysdyn and layer0 are added.
+ *
+ * @param graph WriteGraph
+ * @param model Imported model
+ */
+ /*
+ private static void addDefaultOntologyLinks(WriteGraph graph, Resource model) {
+ try {
+ Layer0 l0 = Layer0.getInstance(graph);
+ // The links should be exported and imported automatically
+ Resource sysdyn = graph.getResource("http://www.simantics.org/Sysdyn-1.1");
+ Resource layer0 = graph.getResource("http://www.simantics.org/Layer0-1.1");
+ if(!graph.hasStatement(model, l0.IsLinkedTo, sysdyn))
+ graph.claim(model, l0.IsLinkedTo, sysdyn);
+ if(!graph.hasStatement(model, l0.IsLinkedTo, layer0))
+ graph.claim(model, l0.IsLinkedTo, layer0);
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void addURIsToDiagrams(WriteGraph graph, Resource model) {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SimulationResource simu = SimulationResource.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+ try {
+ HashSet<Resource> configurations = new HashSet<Resource>();
+
+ Resource configuration = graph.getPossibleObject(model, simu.HasConfiguration);
+ if(configuration != null)
+ configurations.add(configuration);
+
+ for(Resource r : graph.getObjects(model, l0.ConsistsOf)) {
+ if(graph.isInheritedFrom(r, sr.Module)) {
+ Resource moduleConfiguration = graph.getPossibleObject(r, sr2.IsDefinedBy);
+ if(moduleConfiguration != null)
+ configurations.add(moduleConfiguration);
+ }
+ }
+
+ for(Resource conf : configurations) {
+ Resource configurationDiagram = graph.getPossibleObject(conf, mr.CompositeToDiagram);
+ if(configurationDiagram != null && !graph.hasStatement(configurationDiagram, l0.PartOf)) {
+ GraphUtils.create2(graph, l0.Library,
+ l0.HasName, "__CONTAINER__",
+ l0.PartOf, conf,
+ l0.ConsistsOf, configurationDiagram);
+ }
+ }
+
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+*/
+
+ /**
+ * Add a missing spreadsheet book to the model
+ *
+ * @param graph
+ * @param model
+ */
+ /*
+ private static void addSpreadSheetBook(WriteGraph graph, Resource model) {
+ try {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SpreadsheetResource ssr = SpreadsheetResource.getInstance(graph);
+ SimulationResource simu = SimulationResource.getInstance(graph);
+ Resource conf = graph.getPossibleObject(model, simu.HasConfiguration);
+ if(conf != null && graph.syncRequest(new ObjectsWithType(conf, l0.ConsistsOf, ssr.Book)).isEmpty()) {
+ Resource book = graph.newResource();
+ graph.claim(book, l0.InstanceOf, null, ssr.Book);
+ graph.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING);
+ graph.claim(conf, l0.ConsistsOf, l0.PartOf, book);
+
+ createSheet(graph, book, "Sheet1", new String[] { }, new int[] { 50 });
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+ */
+ /**
+ * Create a sheet (Copied from SysdynProject)
+ *
+ * @param graph
+ * @param book
+ * @param name
+ * @param colNames
+ * @param colWidths
+ * @return
+ * @throws DatabaseException
+ */
+ /*
+ private static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {
+
+ Layer0 L0 = Layer0.getInstance(graph);
+ Layer0X L0X = Layer0X.getInstance(graph);
+ SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);
+
+ Resource result = graph.newResource();
+ graph.claim(result, L0.InstanceOf, null, sr.Spreadsheet);
+
+ if(name == null) {
+ name = NameUtils.findFreshEscapedName(graph, "Sheet", book, sr.HasSheet);
+ }
+ graph.claimLiteral(result, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);
+ graph.claim(book, L0.ConsistsOf, L0.PartOf, result);
+
+ {
+ Resource newCell = graph.newResource();
+ graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);
+ graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Dimensions", Bindings.STRING);
+ graph.addLiteral(newCell, sr.Dimensions_fitColumns, sr.Dimensions_fitColumns_Inverse, L0.Boolean, false, Bindings.BOOLEAN);
+ graph.addLiteral(newCell, sr.Dimensions_fitRows, sr.Dimensions_fitRows_Inverse, L0.Boolean, false, Bindings.BOOLEAN);
+ graph.addLiteral(newCell, sr.Dimensions_columnCount, sr.Dimensions_columnCount_Inverse, L0.Integer, 128, Bindings.INTEGER);
+ graph.addLiteral(newCell, sr.Dimensions_rowCount, sr.Dimensions_rowCount_Inverse, L0.Integer, 256, Bindings.INTEGER);
+ graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);
+ }
+
+ {
+ Resource newCell = graph.newResource();
+ graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);
+ graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Headers", Bindings.STRING);
+ graph.addLiteral(newCell, sr.Headers_columnLabels, sr.Headers_columnLabels_Inverse, L0.StringArray, colNames, Bindings.STRING_ARRAY);
+ graph.addLiteral(newCell, sr.Headers_columnWidths, sr.Headers_columnWidths_Inverse, L0.IntegerArray, colWidths, Bindings.INT_ARRAY);
+ graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);
+ }
+
+ {
+
+ double[] doubles = new double[10*2];
+ for(int i=0;i<10*2;i++) doubles[i] = i;
+
+ Resource newCell = graph.newResource();
+ graph.claim(newCell, L0.InstanceOf, null, sr.DoubleArrayCell);
+ graph.addLiteral(newCell, sr.DoubleArrayCell_HasWidth, sr.DoubleArrayCell_HasWidth_Inverse, L0.Integer, 10, Bindings.INTEGER);
+ graph.addLiteral(newCell, sr.HasLocation, sr.HasLocation_Inverse, L0.String, "B2", Bindings.STRING);
+ graph.addLiteral(newCell, sr.DoubleArrayCell_HasDoubleArray, sr.DoubleArrayCell_HasDoubleArray_Inverse, L0.DoubleArray, doubles, Bindings.DOUBLE_ARRAY);
+ graph.claim(result, L0X.HasChildVariables, L0X.HasChildVariables_Inverse, newCell);
+
+ }
+
+ return result;
+
+ }
+ */
+ void validatePage(){
+
+ if (previouslyBrowsedFile.isEmpty()){
+ setPageComplete(false);
+ return;
+ }
+ setErrorMessage(null);
+ setPageComplete(true);
+ }
}
\ No newline at end of file
-package org.simantics.sysdyn.ui.wizards.modules;\r
-\r
-import java.util.Collection;\r
-\r
-import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.browsing.ui.common.node.DeleteException;\r
-import org.simantics.browsing.ui.common.node.IDeletableNode;\r
-import org.simantics.browsing.ui.common.node.IModifiableNode;\r
-import org.simantics.browsing.ui.content.Labeler.Modifier;\r
-import org.simantics.browsing.ui.graph.impl.LabelModifier;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;\r
-import org.simantics.db.exception.ServiceException;\r
-import org.simantics.db.layer0.adapter.PasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class ModuleComponentTypeNode extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {\r
-\r
- \r
- Listener<String> configurationNameSynchronizer;\r
- private boolean disposed = false;\r
- private Resource configuration;\r
- \r
- public ModuleComponentTypeNode(Resource resource) {\r
- super(resource);\r
-\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
- configuration = graph.getPossibleObject(data, sr2.IsDefinedBy); \r
- }\r
- });\r
- \r
- // Not the best solution for name sync\r
- configurationNameSynchronizer = new Listener<String>() {\r
-\r
- @Override\r
- public void execute(final String result) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- if(configuration != null)\r
- graph.claimLiteral(configuration, Layer0.getInstance(graph).HasLabel, result);\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void exception(Throwable t) {\r
- t.printStackTrace();\r
- }\r
-\r
- @Override\r
- public boolean isDisposed() {\r
- return disposed;\r
- }\r
- };\r
- \r
- SimanticsUI.getSession().asyncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- return graph.getRelatedValue(data, l0.HasName);\r
- }\r
- \r
- }, configurationNameSynchronizer);\r
- \r
- }\r
-\r
- @Override\r
- public Modifier getModifier(String columnId) {\r
- Modifier modifier = null;\r
- try {\r
- modifier = SimanticsUI.getSession().syncRequest(new Read<Modifier>() {\r
-\r
- @Override\r
- public Modifier perform(ReadGraph graph) throws ManyObjectsForFunctionalRelationException, ServiceException {\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);\r
-\r
- LabelModifier modifier = new LabelModifier(SimanticsUI.getSession(), type, l0.HasName) {\r
- @Override\r
- public String isValid(String label) {\r
- if (label.isEmpty())\r
- return "Empty name not allowed";\r
- return null;\r
- }\r
- };\r
-\r
-\r
- return modifier;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- return modifier;\r
- }\r
-\r
- @Override\r
- public void delete() throws DeleteException {\r
- disposed = true;\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- StructuralResource2 st = StructuralResource2.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
-\r
- Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);\r
- Resource model = graph.getSingleObject(type, l0.PartOf);\r
- Resource modelConfiguration = graph.getSingleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
- if (!graph.syncRequest(new ObjectsWithType(modelConfiguration, l0.ConsistsOf, type)).isEmpty()) {\r
- System.out.println("The module is used at the model configuration");\r
- return;\r
- }\r
- Collection<Resource> moduleTypes = graph.syncRequest(new ObjectsWithType(model, l0.ConsistsOf, st.ComponentType));\r
- for(Resource r : moduleTypes) {\r
- Resource configuration = graph.getSingleObject(r, st.IsDefinedBy);\r
- if(!graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, type)).isEmpty()) {\r
- System.out.println("The module is used at another module: " + graph.getRelatedValue(r, l0.HasName));\r
- return;\r
- }\r
- }\r
- graph.deny(model, l0.ConsistsOf, type);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- \r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public Object getAdapter(Class adapter) {\r
- if(PasteHandler.class == adapter && configuration != null) \r
- return new DefaultPasteHandler(configuration);\r
- return super.getAdapter(adapter);\r
- }\r
+package org.simantics.sysdyn.ui.wizards.modules;
+
+import java.util.Collection;
+
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.common.node.AbstractNode;
+import org.simantics.browsing.ui.common.node.DeleteException;
+import org.simantics.browsing.ui.common.node.IDeletableNode;
+import org.simantics.browsing.ui.common.node.IModifiableNode;
+import org.simantics.browsing.ui.content.Labeler.Modifier;
+import org.simantics.browsing.ui.graph.impl.LabelModifier;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
+import org.simantics.db.exception.ServiceException;
+import org.simantics.db.layer0.adapter.PasteHandler;
+import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.structural.stubs.StructuralResource2;
+
+public class ModuleComponentTypeNode extends AbstractNode<Resource> implements IDeletableNode, IModifiableNode {
+
+
+ Listener<String> configurationNameSynchronizer;
+ private boolean disposed = false;
+ private Resource configuration;
+
+ public ModuleComponentTypeNode(Resource resource) {
+ super(resource);
+
+ Simantics.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+ configuration = graph.getPossibleObject(data, sr2.IsDefinedBy);
+ }
+ });
+
+ // Not the best solution for name sync
+ configurationNameSynchronizer = new Listener<String>() {
+
+ @Override
+ public void execute(final String result) {
+ Simantics.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ if(configuration != null)
+ graph.claimLiteral(configuration, Layer0.getInstance(graph).HasLabel, result);
+ }
+ });
+ }
+
+ @Override
+ public void exception(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public boolean isDisposed() {
+ return disposed;
+ }
+ };
+
+ Simantics.getSession().asyncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ return graph.getRelatedValue(data, l0.HasName);
+ }
+
+ }, configurationNameSynchronizer);
+
+ }
+
+ @Override
+ public Modifier getModifier(String columnId) {
+ Modifier modifier = null;
+ try {
+ modifier = Simantics.getSession().syncRequest(new Read<Modifier>() {
+
+ @Override
+ public Modifier perform(ReadGraph graph) throws ManyObjectsForFunctionalRelationException, ServiceException {
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);
+
+ LabelModifier modifier = new LabelModifier(Simantics.getSession(), type, l0.HasName) {
+ @Override
+ public String isValid(String label) {
+ if (label.isEmpty())
+ return "Empty name not allowed";
+ return null;
+ }
+ };
+
+
+ return modifier;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ return modifier;
+ }
+
+ @Override
+ public void delete() throws DeleteException {
+ disposed = true;
+ try {
+ Simantics.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ StructuralResource2 st = StructuralResource2.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+
+ Resource type = graph.getPossibleObject(data, mr.SymbolToComponentType);
+ Resource model = graph.getSingleObject(type, l0.PartOf);
+ Resource modelConfiguration = graph.getSingleObject(model, SimulationResource.getInstance(graph).HasConfiguration);
+ if (!graph.syncRequest(new ObjectsWithType(modelConfiguration, l0.ConsistsOf, type)).isEmpty()) {
+ System.out.println("The module is used at the model configuration");
+ return;
+ }
+ Collection<Resource> moduleTypes = graph.syncRequest(new ObjectsWithType(model, l0.ConsistsOf, st.ComponentType));
+ for(Resource r : moduleTypes) {
+ Resource configuration = graph.getSingleObject(r, st.IsDefinedBy);
+ if(!graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, type)).isEmpty()) {
+ System.out.println("The module is used at another module: " + graph.getRelatedValue(r, l0.HasName));
+ return;
+ }
+ }
+ graph.deny(model, l0.ConsistsOf, type);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public Object getAdapter(Class adapter) {
+ if(PasteHandler.class == adapter && configuration != null)
+ return new DefaultPasteHandler(configuration);
+ return super.getAdapter(adapter);
+ }
}
\ No newline at end of file
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
+import org.simantics.Simantics;
import org.simantics.browsing.ui.common.AdaptableHintContext;
import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
import org.simantics.databoard.Bindings;
import org.simantics.structural.stubs.StructuralResource2;
import org.simantics.sysdyn.SysdynResource;
import org.simantics.sysdyn.ui.Activator;
-import org.simantics.ui.SimanticsUI;
import org.simantics.utils.datastructures.ArrayMap;
import org.simantics.utils.datastructures.Pair;
Label title = new Label(workArea, SWT.NONE);
title.setText("Select Module to export:");
- Resource input = SimanticsUI.getProject().get();
+ Resource input = Simantics.getProject().get();
modelExplorer = new GraphExplorerComposite(ArrayMap.keys(
"displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
String name = null;
try {
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {
+ name = Simantics.getSession().syncRequest(new Read<String>() {
@Override
public String perform(ReadGraph graph) throws DatabaseException {
}
if(name == null) return false;
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {
+ Simantics.getSession().asyncRequest(new ReadRequest() {
@Override
public void run(ReadGraph graph) throws DatabaseException {
String root = null;
try {
- root = SimanticsUI.getSession().syncRequest(new Read<String>() {
+ root = Simantics.getSession().syncRequest(new Read<String>() {
@Override
public String perform(ReadGraph graph) throws DatabaseException {
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
+import org.simantics.Simantics;
import org.simantics.browsing.ui.common.AdaptableHintContext;
import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
import org.simantics.db.ReadGraph;
import org.simantics.db.request.Read;
import org.simantics.sysdyn.SysdynResource;
import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;
-import org.simantics.ui.SimanticsUI;
import org.simantics.utils.datastructures.ArrayMap;
title.setText("Select import location:");
try {
- Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {
+ Resource input = Simantics.getSession().syncRequest(new Read<Resource>() {
@Override
public Resource perform(ReadGraph graph)
throws DatabaseException {
- Resource model = SimanticsUI.getProject().get();
+ Resource model = Simantics.getProject().get();
return model;
}
final Resource root = ia.getRoot();
try {
- SimanticsUI.getSession().syncRequest(new WriteRequest() {
+ Simantics.getSession().syncRequest(new WriteRequest() {
@Override
public void perform(WriteGraph graph) throws DatabaseException {
org.simantics.spreadsheet.graph;bundle-version="1.1.0",
fi.semantum.sysdyn.solver;bundle-version="0.1.0",
org.simantics.fileimport,
- org.simantics.document.server
+ org.simantics.document.server,
+ org.slf4j.api;bundle-version="1.7.25"
Export-Package: org.simantics.sysdyn,
org.simantics.sysdyn.adapter,
org.simantics.sysdyn.elementaryCycles,
-/*******************************************************************************\r
- * Copyright (c) 2010, 2013, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- * Semantum Oy - Bug #4180\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.manager;\r
-\r
-import gnu.trove.set.hash.THashSet;\r
-\r
-import java.io.File;\r
-import java.io.FileNotFoundException;\r
-import java.io.IOException;\r
-import java.util.ArrayList;\r
-import java.util.Arrays;\r
-import java.util.Collection;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.concurrent.locks.Lock;\r
-\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.preferences.DefaultScope;\r
-import org.eclipse.core.runtime.preferences.IScopeContext;\r
-import org.osgi.service.prefs.Preferences;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.RequestProcessor;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.VirtualGraph;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ParametrizedPrimitiveRead;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.Logger;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.RuntimeDatabaseException;\r
-import org.simantics.db.procedure.Listener;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.db.service.VirtualGraphSupport;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modelica.IModelicaMonitor;\r
-import org.simantics.modelica.ModelicaException;\r
-import org.simantics.modelica.ModelicaKeys;\r
-import org.simantics.modelica.ModelicaManager;\r
-import org.simantics.modelica.SimulationLocation;\r
-import org.simantics.modelica.data.CSVSimulationResult;\r
-import org.simantics.modelica.data.MatSimulationResult;\r
-import org.simantics.modelica.data.SimulationResult;\r
-import org.simantics.modelica.preferences.OpenModelicaPreferences;\r
-import org.simantics.simulation.data.Datasource;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IExperimentListener;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.sysdyn.Activator;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.adapter.VariableValueSubscription;\r
-import org.simantics.sysdyn.modelica.ModelicaWriter;\r
-import org.simantics.sysdyn.representation.Configuration;\r
-import org.simantics.sysdyn.representation.Model;\r
-import org.simantics.sysdyn.simulation.SimulationScheduler;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-public class OldSysdynExperiment extends SysdynExperiment {\r
-\r
- protected Session session;\r
- protected Runnable modificationListener;\r
- protected SysdynModel sysdynModel;\r
- protected boolean toggled = false;\r
- @SuppressWarnings("rawtypes")\r
- protected THashSet<VariableValueSubscription> variableValueSubscriptions = new THashSet<VariableValueSubscription>();\r
- @SuppressWarnings("rawtypes")\r
- protected volatile VariableValueSubscription[] variableValueSubscriptionsSnapshot = null;\r
-\r
- protected HashMap<String, String> defaultParameters;\r
- protected Process process;\r
- protected boolean canceled = false;\r
- protected ExperimentState sysdynExperimentState;\r
-\r
- private SysdynResult result;\r
- private File simulationDir;\r
-\r
- protected String experimentName;\r
- protected static String omcVersion = null;\r
- protected static String omcHome = null;\r
-\r
- public static OldSysdynExperiment INSTANCE;\r
- \r
- boolean publishResults = true;\r
-\r
- public OldSysdynExperiment(Resource experiment, Resource model) {\r
- super(experiment, model);\r
- INSTANCE = this;\r
- }\r
-\r
- public static OldSysdynExperiment getInstance() {\r
- return INSTANCE;\r
- }\r
- \r
- public class PublishExternalRead extends ParametrizedPrimitiveRead<OldSysdynExperiment,Integer> {\r
-\r
- private int value = 0;\r
- private Listener<Integer> listener = null;\r
- \r
- public PublishExternalRead(OldSysdynExperiment parameter) {\r
- super(parameter);\r
- }\r
-\r
- @Override\r
- public void register(ReadGraph graph, Listener<Integer> procedure) {\r
- procedure.execute(value);\r
- if(procedure.isDisposed()) return;\r
- if(listener != null) throw new RuntimeDatabaseException("Internal error");\r
- listener = procedure;\r
- }\r
- \r
- @Override\r
- public void unregistered() {\r
- listener = null;\r
- }\r
- \r
- public void fire() {\r
- value++;\r
- if(listener != null)\r
- listener.execute(value);\r
- }\r
- \r
- }\r
- \r
- private PublishExternalRead publishRead = new PublishExternalRead(this);\r
- \r
- public int getPublishCounter(ReadGraph graph) throws DatabaseException {\r
- return graph.syncRequest(publishRead);\r
- }\r
-\r
- public SysdynResult getCurrentResult() {\r
- if(this.result == null)\r
- this.result = new MemoryResult(null, null);\r
- return this.result;\r
- }\r
-\r
- public Collection<SysdynResult> getActiveResults() {\r
- ArrayList<SysdynResult> result = new ArrayList<SysdynResult>();\r
- if(getCurrentResult() != null)\r
- result.add(getCurrentResult());\r
- result.addAll(sysdynModel.getDisplayedResults());\r
- return result;\r
- }\r
-\r
- /**\r
- * Initialize this experiment\r
- * @param g ReadGraph\r
- */\r
- public void init(ReadGraph g) {\r
- try {\r
- this.experimentName = NameUtils.getSafeName(g, experiment);\r
- } catch (DatabaseException e) {\r
- this.experimentName = "Experiment";\r
- }\r
-\r
- this.session = g.getSession();\r
- state = ExperimentState.STOPPED;\r
- for(IExperimentListener listener : listeners.getListeners())\r
- listener.stateChanged(state);\r
-\r
- try {\r
- g.syncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
- sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration);\r
- toggleActivation(graph, true);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- Logger.defaultLogError(e);\r
- }\r
-\r
- setSysdynExperimentState(ExperimentState.INITIALIZING);\r
- }\r
-\r
- @Override\r
- public void saveState() {\r
- if(result == null || !(result instanceof MemoryResult)) \r
- return;\r
- // TODO: temporary fix\r
- SaveResultJob saveResultJob = new SaveResultJob(OldSysdynExperiment.this, session, (MemoryResult)result);\r
- saveResultJob.schedule();\r
- }\r
-\r
- protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) {\r
- return new Thread() {\r
- @Override\r
- public void run() {\r
- if(!canceled) {\r
- // Get and store results\r result.saveToFile(file, progressMonitor);\r
- }\r }\r
- };\r
- }\r
- \r
- /**\r
- * Starts a simulation job. Use this method to start a simulation.\r
- */\r
- @Override\r
- public void simulate(boolean enabled) {\r
- if(enabled && sysdynModel != null) {\r
- if(!ExperimentState.RUNNING.equals(getState())) {\r
- changeState(ExperimentState.RUNNING);\r
- startSimulationJob();\r
- }\r
- } else if (!toggled){\r
- changeState(ExperimentState.STOPPED);\r
- }\r
- }\r
-\r
- /**\r
- * Starts a simulation job\r
- */\r
- protected void startSimulationJob() {\r
- session.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this);\r
- }\r
- });\r
- }\r
-\r
-\r
- /**\r
- * Write model configuration to a single Modelica code\r
- * @param monitor\r
- * @param isGame is the experiment a "game experiment". This is needed for modifying the code to work with FMU simulation\r
- * @return Modelica code\r
- */\r
- protected String getModelicaCode(IModelicaMonitor monitor, boolean isGame, String modelicaVersion) {\r
- String modelText = null;\r
- try {\r
- // Write all configurations once\r
- Model representation = sysdynModel.getConfiguration().getModel();\r
- double start = representation.getStartTime();\r
- double stop = representation.getStopTime();\r
- double step = representation.getSimulationStepLength();\r
- modelText = ModelicaWriter.write(sysdynModel.getModules(), start, stop, step, isGame, modelicaVersion);\r
- } catch (Exception e) {\r
- // Stop experiment and show console\r
- /*setExperimentStopped(experiment); =>*/ simulate(false);\r
- monitor.showConsole();\r
- monitor.message("Error when writing Modelica code.");\r
- }\r
- return modelText;\r
- }\r
-\r
- /**\r
- * Get all inits and parameter values required for the inits -file\r
- * @param monitor\r
- * @return All inits in a map\r
- */\r
- protected HashMap<String, String> getExperimentParameters(IModelicaMonitor monitor) {\r
- Configuration configuration = sysdynModel.getConfiguration();\r
- HashMap<String, String> parameters = new HashMap<String, String>();\r
- Model model = configuration.getModel();\r
- Double startTime = model.getStartTime();\r
- Double stopTime = model.getStopTime();\r
- parameters.put(ModelicaKeys.START_VALUE, startTime.toString());\r
- parameters.put(ModelicaKeys.STOP_VALUE, stopTime.toString());\r
- String outputFormat = "mat";\r
- parameters.put(ModelicaKeys.OUTPUT_FORMAT, outputFormat);\r
-\r
- Double simulationStepLength = model.getSimulationStepLength();\r
- parameters.put(ModelicaKeys.STEP_VALUE, simulationStepLength.toString());\r
- parameters.put(ModelicaKeys.NUMBER_OF_INTERVALS, Integer.toString((int)((stopTime - startTime) / simulationStepLength)));\r
-\r
- Double outputInterval = model.getOutputInterval();\r
- parameters.put(ModelicaKeys.OUTPUT_INTERVAL, outputInterval.toString());\r
-\r
- String method = "\"" + model.getSolver() + "\"";\r
- parameters.put(ModelicaKeys.METHOD, method);\r
- if(model.getTolerance() != null)\r
- parameters.put(ModelicaKeys.TOLERANCE, model.getTolerance().toString());\r
- String variableFilter = model.getVariableFilter();\r
- if(variableFilter != null && !variableFilter.isEmpty())\r
- parameters.put(ModelicaKeys.VARIABLE_FILTER, variableFilter);\r
- return parameters;\r
- }\r
-\r
- /**\r
- * Builds a model\r
- * @param simulationLocation\r
- * @param inits\r
- * @param modelText\r
- * @param monitor\r
- */\r
- protected void buildModel(SimulationLocation simulationLocation, IModelicaMonitor monitor) {\r
-\r
- try {\r
- simulationLocation.executableFile.delete();\r
- ModelicaManager.buildModel(simulationLocation, monitor);\r
- } catch (ModelicaException e) {\r
- if(e.getMessage() != null)\r
- monitor.message(e.getMessage());\r
- monitor.showConsole();\r
- canceled = true;\r
- defaultParameters = null;\r
- }\r
- }\r
-\r
- /**\r
- * Run a built model\r
- * @param structureChanged \r
- * @throws IOException\r
- */\r
- protected void runModelica(SimulationLocation simulationLocation, IModelicaMonitor monitor, IProgressMonitor progressMonitor, HashMap<String, String> experimentParameters, HashMap<String, String> parameterChanges) throws IOException {\r
- progressMonitor.subTask("Simulate model");\r
- process = ModelicaManager.runModelica(\r
- simulationLocation,\r
- monitor,\r
- experimentParameters, \r
- parameterChanges\r
- );\r
- ModelicaManager.printProcessOutput(process, monitor);\r
-\r
- Thread resultThread = getResultThread(simulationLocation, experimentParameters, monitor, progressMonitor);\r
- resultThread.run();\r
-\r
- process = null;\r
- }\r
-\r
- /**\r
- * Get a thread for reading and saving reuslts from a normal simulation\r
- * @param simulationLocation\r
- * @param inits\r
- * @param monitor\r
- * @param progressMonitor\r
- * @return\r
- */\r
- protected Thread getResultThread(final SimulationLocation simulationLocation, final HashMap<String, String> experimentParameters, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) {\r
- return new Thread() {\r
- @Override\r
- public void run() {\r
- try {\r
- process.waitFor();\r
-\r
- if(!canceled) {\r
- // Get and store results\r
- progressMonitor.worked(1);\r
- progressMonitor.subTask("Read results");\r
- SimulationResult result;\r
- if(simulationLocation.resultFile.getName().endsWith(".csv"))\r
- result = new CSVSimulationResult();\r
- else if(simulationLocation.resultFile.getName().endsWith(".plt"))\r
- result = new SimulationResult();\r
- else\r
- result = new MatSimulationResult(); // The latest format\r
-\r
- String startTime = experimentParameters.get(ModelicaKeys.START_VALUE);\r
- String stopTime = experimentParameters.get(ModelicaKeys.STOP_VALUE);\r
- String stepTime = experimentParameters.get(ModelicaKeys.STEP_VALUE);\r
- \r
- Double start = Double.parseDouble(startTime);\r
- Double stop = Double.parseDouble(stopTime);\r
- Double step = Double.parseDouble(stepTime);\r
- \r
- // The interval of results saved. Every result? Every other result? etc...\r
- int outIntervalInt = 1;\r
- String outputInterval = experimentParameters.get(ModelicaKeys.OUTPUT_INTERVAL);\r
- if(outputInterval != null) {\r
- Double outInterval = Double.parseDouble(outputInterval);\r
-\r
- outIntervalInt = (int)getInterval(outInterval, step);\r
- // Actually you might be able to use an outInterval one or two longer. \r
- int maxIntervalInt = (int)Math.round((stop - start) / step);\r
- if (outIntervalInt > maxIntervalInt)\r
- outIntervalInt = maxIntervalInt;\r
- }\r
-\r
- result.initRead(simulationLocation.resultFile);\r
- result.readTime(simulationLocation.resultFile, outIntervalInt);\r
- //result.readInits(simulationLocation.initFile); // Parameter values are read from .mat\r
- result.filter();\r
- ((MemoryResult)getCurrentResult()).setResult(result);\r
- ((MemoryResult)getCurrentResult()).setResultFile(simulationLocation.resultFile);\r
- ((MemoryResult)getCurrentResult()).setFilter(start, stop, step);\r
- progressMonitor.worked(1);\r
- resultsChanged();\r
-\r
- simulate(false);\r
-\r
- String errorString = result.getResultReadErrors();\r
- if(errorString != null && !errorString.isEmpty())\r
- monitor.message(errorString);\r
- }\r
- } catch (FileNotFoundException e) {\r
- e.printStackTrace();\r
- } catch (IOException e) {\r
- e.printStackTrace();\r
- } catch (InterruptedException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- };\r
- }\r
-\r
- protected static long getInterval(double outputLength, double stepLength) {\r
- double interval = outputLength / stepLength;\r
- if (interval <= 1)\r
- return 1;\r
- return Math.round(interval);\r
- }\r
-\r
-\r
- /**\r
- * \r
- * @param sysdynModel\r
- * @param modelText\r
- * @param inits\r
- * @param additionalScript\r
- * @return\r
- * @throws IOException\r
- */\r
- protected SimulationLocation createSimulationFiles(SysdynModel sysdynModel, String modelText, HashMap<String, String> inits, String additionalScript, boolean fmu) throws IOException {\r
- File simulationDir = getExperimentDir();\r
-\r
- // update all function files. both the model's and built-in\r
- FunctionUtils.updateFunctionFilesForExperiment(this);\r
-\r
-\r
- SimulationLocation location = ModelicaManager.createSimulationLocation(simulationDir, sysdynModel.getConfiguration().getLabel(), modelText);\r
- if (fmu) {\r
- ModelicaManager.createFMUSimulationScripts(location, inits, additionalScript);\r
- }\r
- else {\r
- ModelicaManager.createSimulationScripts(location, inits, additionalScript);\r
- }\r
- return location;\r
- }\r
-\r
- /**\r
- * Get a simulation directory for this model\r
- * @return File directory\r
- */\r
- public File getExperimentDir() {\r
- if(simulationDir == null) {\r
- File modelsDir = Activator.getBundleContext().getDataFile("models");\r
- String experimentName = this.experimentName;\r
- List<String> files = Arrays.asList(modelsDir.list());\r
- if (files.contains(experimentName)) {\r
- int i = 2;\r
- while (files.contains(experimentName + "_" + i)){\r
- i++;\r
- }\r
- experimentName += "_" + i;\r
- }\r
-\r
- simulationDir = Activator.getBundleContext().getDataFile("models/" + experimentName);\r
- if (!simulationDir.exists()) {\r
- simulationDir.mkdir();\r
- }\r
- }\r
- return simulationDir;\r
- }\r
-\r
- /**\r
- * \r
- * @return\r
- */\r
- protected String getAdditionalScripts() {\r
- StringBuilder functionscript = new StringBuilder();\r
- \r
- boolean useModelicaLibraries = false;\r
- try {\r
- useModelicaLibraries = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- SysdynResource SR = SysdynResource.getInstance(graph);\r
- SimulationResource SIM = SimulationResource.getInstance(graph);\r
- Resource configuration = graph.getPossibleObject(OldSysdynExperiment.this.model, SIM.HasConfiguration);\r
- return graph.hasStatement(configuration, SR.SysdynModel_useModelicaLibraries);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- if (useModelicaLibraries)\r
- functionscript.append("loadModel(Modelica);\n");\r
- \r
- for(String path : FunctionUtils.getLibraryPathsForModelica(this)) {\r
- functionscript.append("loadFile(\"" + path + "\");\n");\r
- }\r
- return functionscript.toString();\r
- }\r
-\r
- /**\r
- * Starts simulating a model. Call only from inside simulation job! Start simulation using simulate(true).\r
- * @param monitor\r
- * @param progressMonitor\r
- * @throws IOException\r
- */\r
- public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException {\r
- canceled = false;\r
- progressMonitor.subTask("Write modelica classes");\r
-\r
- omcVersion = ModelicaManager.getDefaultOMVersion();\r
- \r
- monitor.message("Simulate " + modelName + " using OpenModelica " + omcVersion);\r
- \r
- // Get Modelica code\r
- String modelText = getModelicaCode(monitor, false, omcVersion);\r
- if(modelText == null)\r
- return;\r
- progressMonitor.worked(1);\r
-\r
- // Write initial files and add init-parameters\r
- progressMonitor.subTask("Write simulation files");\r
- HashMap<String, String> experimentParameters = getExperimentParameters(monitor);\r
- \r
- // add loadFile script to load all related functions and function libraries\r
- String additionalScript = getAdditionalScripts();\r
- \r
- // Create simulation files\r
- SimulationLocation simulationLocation = createSimulationFiles(sysdynModel, modelText, experimentParameters, additionalScript, false);\r
- progressMonitor.worked(1);\r
- \r
- // Build the model and store previous model structure and inits that affect the building\r
- // If there is no exe file OR the model structure has not changed, no need to build\r
- String flatModelText = ModelicaManager.getFlatModelText(simulationLocation, monitor, FunctionUtils.getLibraryPathsForModelica(this));\r
- \r
- boolean structureChanged = sysdynModel.isStructureModified();\r
- \r
- if (!simulationLocation.executableFile.isFile() || structureChanged) {\r
- progressMonitor.subTask("Build model");\r
- defaultParameters = ModelicaManager.getModelParameters(flatModelText);\r
- \r
- buildModel(simulationLocation, monitor);\r
- }\r
- \r
- // Add changed parameters in case that structure has not changed\r
- HashMap<String, String> parameterChanges = new HashMap<String, String>();\r
- if(!structureChanged && defaultParameters != null) {\r
- HashMap<String, String> currentParameters = ModelicaManager.getModelParameters(flatModelText);\r
- for(String key : defaultParameters.keySet()) {\r
- if(!defaultParameters.get(key).equals(currentParameters.get(key))) {\r
- parameterChanges.put(key, currentParameters.get(key));\r
- }\r
- }\r
- }\r
- progressMonitor.worked(1);\r
- \r
- if(simulationLocation != null && !canceled) {\r
- // Simulate the model\r
- runModelica(simulationLocation, monitor, progressMonitor, experimentParameters, parameterChanges);\r
- }\r
- \r
- if(canceled)\r
- simulate(false);\r
- process = null;\r
- }\r
-\r
- /**\r
- * Get the version of the OpenModelica compiler that is defined to be used\r
- * in Preferences\r
- * @return OpenModelica version\r
- */\r
- protected String getOpenModelicaVersion() {\r
- String omVersion = null;\r
-\r
- IScopeContext context = DefaultScope.INSTANCE;\r
- Preferences node = context.getNode(org.simantics.modelica.Activator.PLUGIN_ID);\r
- String omHome = node.get(OpenModelicaPreferences.OM_HOME, null);\r
- if(omHome != null) {\r
- File omHomeDir = new File(omHome);\r
- if(omHomeDir != null && omHomeDir.isDirectory())\r
- omVersion = ModelicaManager.getOMVersion(omHomeDir);\r
- }\r
-\r
- if(omVersion == null) {\r
- omVersion = ModelicaManager.getDefaultOMVersion();\r
- }\r
- \r
- return omVersion;\r
- }\r
-\r
- /**\r
- * Destroy an ongoing simulation process\r
- */\r
- public void cancelSimulation() {\r
- canceled = true;\r
- if(process != null) {\r
- process.destroy();\r
- }\r
- }\r
-\r
- /**\r
- * Toggle simulation state\r
- * @param enabled true == RUNNING, false == STOPPED\r
- */\r
- public void toggleSimulation(boolean enabled) {\r
- if(enabled) {\r
- this.toggled = true;\r
- changeState(ExperimentState.RUNNING);\r
- if(modificationListener == null) {\r
-\r
- modificationListener = new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- session.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- if(getState() == ExperimentState.RUNNING) {\r
- SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this);\r
- }\r
-\r
- }\r
- });\r
-\r
- };\r
- };\r
- sysdynModel.addModificationListener(modificationListener);\r
- }\r
- }\r
- else {\r
- changeState(ExperimentState.STOPPED);\r
- this.toggled = false;\r
- }\r
-\r
- }\r
-\r
- @Override\r
- public void refresh(RequestProcessor session) {\r
- session.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- init(graph);\r
- }\r
-\r
- });\r
- }\r
- \r
- @Override\r
- public void refresh(Session session) {\r
- refresh((RequestProcessor)session);\r
- }\r
-\r
- @Override\r
- protected void localStateChange() {\r
- setSysdynExperimentState(getState());\r
- switch(state) {\r
- case DISPOSED:\r
- onExperimentDisposed();\r
- break;\r
- default:\r
- break;\r
- }\r
-\r
- }\r
-\r
- /**\r
- * Returns sysdyn experiment state. It is usually the same as ordinary experiment state.\r
- * Initializing phase takes longer than normally in game experiments.\r
- * @return\r
- */\r
- public ExperimentState getSysdynExperimentState() {\r
- return sysdynExperimentState;\r
- }\r
-\r
- protected void setSysdynExperimentState(final ExperimentState state) {\r
- sysdynExperimentState = state;\r
- VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);\r
- session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- SimulationResource SR = SimulationResource.getInstance(graph);\r
- graph.deny(model, SR.HasExperimentState);\r
- graph.deny(experiment, SR.HasExperimentState);\r
-\r
- Resource st = graph.newResource();\r
- switch(state) {\r
- case INITIALIZING:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing);\r
- break;\r
- case RUNNING:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running);\r
- break;\r
- case STOPPED:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped);\r
- break;\r
- case DISPOSED:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed);\r
- break;\r
- }\r
-\r
- graph.claim(model, SR.HasExperimentState, st);\r
- graph.claim(experiment, SR.HasExperimentState, st);\r
- }});\r
- }\r
-\r
- /**\r
- * Actions performed when experiment is disposed\r
- * @param graph\r
- */\r
- protected void onExperimentDisposed() {\r
- cancelSimulation();\r
- sysdynModel.removeModificationListener(modificationListener);\r
- modificationListener = null;\r
-\r
- session.asyncRequest(new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- toggleActivation(graph, false);\r
- }\r
- });\r
- }\r
-\r
-\r
- /**\r
- * Toggles the active-state of this experiment on or off\r
- * @param graph ReadGraph\r
- * @param activate The active-state of this experiment\r
- */\r
- protected void toggleActivation(ReadGraph graph, final boolean activate) {\r
- VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
- final Session session = graph.getSession();\r
- session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
-\r
- session.asyncRequest(new WriteRequest(runtime) {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SimulationResource SIMU = SimulationResource.getInstance(graph);\r
- if(activate)\r
- graph.claim(experiment, SIMU.IsActive, experiment);\r
- else\r
- graph.denyStatement(experiment, SIMU.IsActive, experiment);\r
- }\r
-\r
- });\r
- }\r
- });\r
- }\r
-\r
-\r
- /* Result subscriptions */\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Copy from AprosExperiment\r
- * @param subscription\r
- */\r
- @Override\r
- public void addVariableValueSubscription(VariableValueSubscription subscription) {\r
- assert subscription != null;\r
- synchronized (variableValueSubscriptions) {\r
- //System.out.println("ADD listener " + subscription);\r
- variableValueSubscriptions.add(subscription);\r
- variableValueSubscriptionsSnapshot = null;\r
- }\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Copy from AprosExperiment\r
- * @param subscription\r
- */\r
- @Override\r
- public void removeVariableValueSubscription(VariableValueSubscription subscription) {\r
- assert subscription != null;\r
- synchronized (variableValueSubscriptions) {\r
- //System.out.println("REMOVE listener " + subscription);\r
- variableValueSubscriptions.remove(subscription);\r
- variableValueSubscriptionsSnapshot = null;\r
- }\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Copy from AprosExperiment\r
- * @return\r
- */\r
- @Override\r
- public VariableValueSubscription[] getListenerSnapshot() {\r
- VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot;\r
- if (snapshot == null) {\r
- synchronized (variableValueSubscriptions) {\r
- snapshot = variableValueSubscriptionsSnapshot;\r
- if (snapshot == null) {\r
- snapshot = variableValueSubscriptionsSnapshot = variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]);\r
- }\r
- }\r
- //System.out.println("listener count: " + snapshot.length);\r
- }\r
- return snapshot;\r
- }\r
-\r
- volatile long previousVariableUpdateTime = 0;\r
- volatile boolean skippedVariableUpdate = true;\r
-\r
-\r
- /**\r
- * Modified copy from AprosExperiment\r
- */\r
- public void resultsChanged() {\r
- resultsChanged(false);\r
- }\r
-\r
- protected void onPublishResults() {\r
- resultsChanged(true);\r
- }\r
- \r
- public void setPublishResults(boolean value) {\r
- publishResults = value;\r
- if(publishResults) {\r
- onPublishResults();\r
- }\r
- }\r
-\r
- public void resultsChanged(boolean force) {\r
- long time = System.nanoTime();\r
- long sinceLast = time - previousVariableUpdateTime;\r
-// System.err.println("sinceLast " + 1e-9*sinceLast);\r
- if(sinceLast > 100000000 || force) {\r
- updateSubscriptions();\r
- previousVariableUpdateTime = time;\r
- }\r
- else\r
- skippedVariableUpdate = true;\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Modified copy from AporsExperiment\r
- */\r
- @Override\r
- public void updateSubscriptions() {\r
- if(publishResults) publishRead.fire();\r
- for(VariableValueSubscription subscription : getListenerSnapshot())\r
- subscription.update();\r
- skippedVariableUpdate = false;\r
- }\r
- \r
- public int numberOfSimulationRunSteps() {\r
- /*\r
- * 1. Write modelica files\r
- * 2. Write other simulation files\r
- * 3. Build model OR update parameters\r
- * 4. Run modelica\r
- * 5. Read results \r
- */\r
- return 5; \r
- }\r
-\r
-\r
- /* Experiment methods that are not used in this experiment */\r
-\r
- @Override\r
- public Lock getDatasourceLock() {\r
- return null;\r
- }\r
-\r
- @Override\r
- public Datasource getDatasource() {\r
- return null;\r
- }\r
-\r
- @Override\r
- public void simulateDuration(double duration) {\r
-\r
- }\r
-\r
-\r
- @Override\r
- public void rewindTo(double time) {\r
-\r
- }\r
-\r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2013, 2014 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 - Bug #4180
+ *******************************************************************************/
+package org.simantics.sysdyn.manager;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.locks.Lock;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.preferences.DefaultScope;
+import org.eclipse.core.runtime.preferences.IScopeContext;
+import org.osgi.service.prefs.Preferences;
+import org.simantics.Simantics;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.VirtualGraph;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ParametrizedPrimitiveRead;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.Logger;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.RuntimeDatabaseException;
+import org.simantics.db.procedure.Listener;
+import org.simantics.db.request.Read;
+import org.simantics.db.service.VirtualGraphSupport;
+import org.simantics.layer0.Layer0;
+import org.simantics.modelica.IModelicaMonitor;
+import org.simantics.modelica.ModelicaException;
+import org.simantics.modelica.ModelicaKeys;
+import org.simantics.modelica.ModelicaManager;
+import org.simantics.modelica.SimulationLocation;
+import org.simantics.modelica.data.CSVSimulationResult;
+import org.simantics.modelica.data.MatSimulationResult;
+import org.simantics.modelica.data.SimulationResult;
+import org.simantics.modelica.preferences.OpenModelicaPreferences;
+import org.simantics.simulation.data.Datasource;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IExperimentListener;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.sysdyn.Activator;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.adapter.VariableValueSubscription;
+import org.simantics.sysdyn.modelica.ModelicaWriter;
+import org.simantics.sysdyn.representation.Configuration;
+import org.simantics.sysdyn.representation.Model;
+import org.simantics.sysdyn.simulation.SimulationScheduler;
+
+import gnu.trove.set.hash.THashSet;
+
+public class OldSysdynExperiment extends SysdynExperiment {
+
+ protected Session session;
+ protected Runnable modificationListener;
+ protected SysdynModel sysdynModel;
+ protected boolean toggled = false;
+ @SuppressWarnings("rawtypes")
+ protected THashSet<VariableValueSubscription> variableValueSubscriptions = new THashSet<VariableValueSubscription>();
+ @SuppressWarnings("rawtypes")
+ protected volatile VariableValueSubscription[] variableValueSubscriptionsSnapshot = null;
+
+ protected HashMap<String, String> defaultParameters;
+ protected Process process;
+ protected boolean canceled = false;
+ protected ExperimentState sysdynExperimentState;
+
+ private SysdynResult result;
+ private File simulationDir;
+
+ protected String experimentName;
+ protected static String omcVersion = null;
+ protected static String omcHome = null;
+
+ public static OldSysdynExperiment INSTANCE;
+
+ boolean publishResults = true;
+
+ public OldSysdynExperiment(Resource experiment, Resource model) {
+ super(experiment, model);
+ INSTANCE = this;
+ }
+
+ public static OldSysdynExperiment getInstance() {
+ return INSTANCE;
+ }
+
+ public class PublishExternalRead extends ParametrizedPrimitiveRead<OldSysdynExperiment,Integer> {
+
+ private int value = 0;
+ private Listener<Integer> listener = null;
+
+ public PublishExternalRead(OldSysdynExperiment parameter) {
+ super(parameter);
+ }
+
+ @Override
+ public void register(ReadGraph graph, Listener<Integer> procedure) {
+ procedure.execute(value);
+ if(procedure.isDisposed()) return;
+ if(listener != null) throw new RuntimeDatabaseException("Internal error");
+ listener = procedure;
+ }
+
+ @Override
+ public void unregistered() {
+ listener = null;
+ }
+
+ public void fire() {
+ value++;
+ if(listener != null)
+ listener.execute(value);
+ }
+
+ }
+
+ private PublishExternalRead publishRead = new PublishExternalRead(this);
+
+ public int getPublishCounter(ReadGraph graph) throws DatabaseException {
+ return graph.syncRequest(publishRead);
+ }
+
+ public SysdynResult getCurrentResult() {
+ if(this.result == null)
+ this.result = new MemoryResult(null, null);
+ return this.result;
+ }
+
+ public Collection<SysdynResult> getActiveResults() {
+ ArrayList<SysdynResult> result = new ArrayList<SysdynResult>();
+ if(getCurrentResult() != null)
+ result.add(getCurrentResult());
+ result.addAll(sysdynModel.getDisplayedResults());
+ return result;
+ }
+
+ /**
+ * Initialize this experiment
+ * @param g ReadGraph
+ */
+ public void init(ReadGraph g) {
+ try {
+ this.experimentName = NameUtils.getSafeName(g, experiment);
+ } catch (DatabaseException e) {
+ this.experimentName = "Experiment";
+ }
+
+ this.session = g.getSession();
+ state = ExperimentState.STOPPED;
+ for(IExperimentListener listener : listeners.getListeners())
+ listener.stateChanged(state);
+
+ try {
+ g.syncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);
+ sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration);
+ toggleActivation(graph, true);
+ }
+ });
+ } catch (DatabaseException e) {
+ Logger.defaultLogError(e);
+ }
+
+ setSysdynExperimentState(ExperimentState.INITIALIZING);
+ }
+
+ @Override
+ public void saveState() {
+ if(result == null || !(result instanceof MemoryResult))
+ return;
+ // TODO: temporary fix
+ SaveResultJob saveResultJob = new SaveResultJob(OldSysdynExperiment.this, session, (MemoryResult)result);
+ saveResultJob.schedule();
+ }
+
+ protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) {
+ return new Thread() {
+ @Override
+ public void run() {
+ if(!canceled) {
+ // Get and store results\r result.saveToFile(file, progressMonitor);
+ }\r }
+ };
+ }
+
+ /**
+ * Starts a simulation job. Use this method to start a simulation.
+ */
+ @Override
+ public void simulate(boolean enabled) {
+ if(enabled && sysdynModel != null) {
+ if(!ExperimentState.RUNNING.equals(getState())) {
+ changeState(ExperimentState.RUNNING);
+ startSimulationJob();
+ }
+ } else if (!toggled){
+ changeState(ExperimentState.STOPPED);
+ }
+ }
+
+ /**
+ * Starts a simulation job
+ */
+ protected void startSimulationJob() {
+ session.asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this);
+ }
+ });
+ }
+
+
+ /**
+ * Write model configuration to a single Modelica code
+ * @param monitor
+ * @param isGame is the experiment a "game experiment". This is needed for modifying the code to work with FMU simulation
+ * @return Modelica code
+ */
+ protected String getModelicaCode(IModelicaMonitor monitor, boolean isGame, String modelicaVersion) {
+ String modelText = null;
+ try {
+ // Write all configurations once
+ Model representation = sysdynModel.getConfiguration().getModel();
+ double start = representation.getStartTime();
+ double stop = representation.getStopTime();
+ double step = representation.getSimulationStepLength();
+ modelText = ModelicaWriter.write(sysdynModel.getModules(), start, stop, step, isGame, modelicaVersion);
+ } catch (Exception e) {
+ // Stop experiment and show console
+ /*setExperimentStopped(experiment); =>*/ simulate(false);
+ monitor.showConsole();
+ monitor.message("Error when writing Modelica code.");
+ }
+ return modelText;
+ }
+
+ /**
+ * Get all inits and parameter values required for the inits -file
+ * @param monitor
+ * @return All inits in a map
+ */
+ protected HashMap<String, String> getExperimentParameters(IModelicaMonitor monitor) {
+ Configuration configuration = sysdynModel.getConfiguration();
+ HashMap<String, String> parameters = new HashMap<String, String>();
+ Model model = configuration.getModel();
+ Double startTime = model.getStartTime();
+ Double stopTime = model.getStopTime();
+ parameters.put(ModelicaKeys.START_VALUE, startTime.toString());
+ parameters.put(ModelicaKeys.STOP_VALUE, stopTime.toString());
+ String outputFormat = "mat";
+ parameters.put(ModelicaKeys.OUTPUT_FORMAT, outputFormat);
+
+ Double simulationStepLength = model.getSimulationStepLength();
+ parameters.put(ModelicaKeys.STEP_VALUE, simulationStepLength.toString());
+ parameters.put(ModelicaKeys.NUMBER_OF_INTERVALS, Integer.toString((int)((stopTime - startTime) / simulationStepLength)));
+
+ Double outputInterval = model.getOutputInterval();
+ parameters.put(ModelicaKeys.OUTPUT_INTERVAL, outputInterval.toString());
+
+ String method = "\"" + model.getSolver() + "\"";
+ parameters.put(ModelicaKeys.METHOD, method);
+ if(model.getTolerance() != null)
+ parameters.put(ModelicaKeys.TOLERANCE, model.getTolerance().toString());
+ String variableFilter = model.getVariableFilter();
+ if(variableFilter != null && !variableFilter.isEmpty())
+ parameters.put(ModelicaKeys.VARIABLE_FILTER, variableFilter);
+ return parameters;
+ }
+
+ /**
+ * Builds a model
+ * @param simulationLocation
+ * @param inits
+ * @param modelText
+ * @param monitor
+ */
+ protected void buildModel(SimulationLocation simulationLocation, IModelicaMonitor monitor) {
+
+ try {
+ simulationLocation.executableFile.delete();
+ ModelicaManager.buildModel(simulationLocation, monitor);
+ } catch (ModelicaException e) {
+ if(e.getMessage() != null)
+ monitor.message(e.getMessage());
+ monitor.showConsole();
+ canceled = true;
+ defaultParameters = null;
+ }
+ }
+
+ /**
+ * Run a built model
+ * @param structureChanged
+ * @throws IOException
+ */
+ protected void runModelica(SimulationLocation simulationLocation, IModelicaMonitor monitor, IProgressMonitor progressMonitor, HashMap<String, String> experimentParameters, HashMap<String, String> parameterChanges) throws IOException {
+ progressMonitor.subTask("Simulate model");
+ process = ModelicaManager.runModelica(
+ simulationLocation,
+ monitor,
+ experimentParameters,
+ parameterChanges
+ );
+ ModelicaManager.printProcessOutput(process, monitor);
+
+ Thread resultThread = getResultThread(simulationLocation, experimentParameters, monitor, progressMonitor);
+ resultThread.run();
+
+ process = null;
+ }
+
+ /**
+ * Get a thread for reading and saving reuslts from a normal simulation
+ * @param simulationLocation
+ * @param inits
+ * @param monitor
+ * @param progressMonitor
+ * @return
+ */
+ protected Thread getResultThread(final SimulationLocation simulationLocation, final HashMap<String, String> experimentParameters, final IModelicaMonitor monitor, final IProgressMonitor progressMonitor) {
+ return new Thread() {
+ @Override
+ public void run() {
+ try {
+ process.waitFor();
+
+ if(!canceled) {
+ // Get and store results
+ progressMonitor.worked(1);
+ progressMonitor.subTask("Read results");
+ SimulationResult result;
+ if(simulationLocation.resultFile.getName().endsWith(".csv"))
+ result = new CSVSimulationResult();
+ else if(simulationLocation.resultFile.getName().endsWith(".plt"))
+ result = new SimulationResult();
+ else
+ result = new MatSimulationResult(); // The latest format
+
+ String startTime = experimentParameters.get(ModelicaKeys.START_VALUE);
+ String stopTime = experimentParameters.get(ModelicaKeys.STOP_VALUE);
+ String stepTime = experimentParameters.get(ModelicaKeys.STEP_VALUE);
+
+ Double start = Double.parseDouble(startTime);
+ Double stop = Double.parseDouble(stopTime);
+ Double step = Double.parseDouble(stepTime);
+
+ // The interval of results saved. Every result? Every other result? etc...
+ int outIntervalInt = 1;
+ String outputInterval = experimentParameters.get(ModelicaKeys.OUTPUT_INTERVAL);
+ if(outputInterval != null) {
+ Double outInterval = Double.parseDouble(outputInterval);
+
+ outIntervalInt = (int)getInterval(outInterval, step);
+ // Actually you might be able to use an outInterval one or two longer.
+ int maxIntervalInt = (int)Math.round((stop - start) / step);
+ if (outIntervalInt > maxIntervalInt)
+ outIntervalInt = maxIntervalInt;
+ }
+
+ result.initRead(simulationLocation.resultFile);
+ result.readTime(simulationLocation.resultFile, outIntervalInt);
+ //result.readInits(simulationLocation.initFile); // Parameter values are read from .mat
+ result.filter();
+ ((MemoryResult)getCurrentResult()).setResult(result);
+ ((MemoryResult)getCurrentResult()).setResultFile(simulationLocation.resultFile);
+ ((MemoryResult)getCurrentResult()).setFilter(start, stop, step);
+ progressMonitor.worked(1);
+ resultsChanged();
+
+ simulate(false);
+
+ String errorString = result.getResultReadErrors();
+ if(errorString != null && !errorString.isEmpty())
+ monitor.message(errorString);
+ }
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ }
+
+ protected static long getInterval(double outputLength, double stepLength) {
+ double interval = outputLength / stepLength;
+ if (interval <= 1)
+ return 1;
+ return Math.round(interval);
+ }
+
+
+ /**
+ *
+ * @param sysdynModel
+ * @param modelText
+ * @param inits
+ * @param additionalScript
+ * @return
+ * @throws IOException
+ */
+ protected SimulationLocation createSimulationFiles(SysdynModel sysdynModel, String modelText, HashMap<String, String> inits, String additionalScript, boolean fmu) throws IOException {
+ File simulationDir = getExperimentDir();
+
+ // update all function files. both the model's and built-in
+ FunctionUtils.updateFunctionFilesForExperiment(this);
+
+
+ SimulationLocation location = ModelicaManager.createSimulationLocation(simulationDir, sysdynModel.getConfiguration().getLabel(), modelText);
+ if (fmu) {
+ ModelicaManager.createFMUSimulationScripts(location, inits, additionalScript);
+ }
+ else {
+ ModelicaManager.createSimulationScripts(location, inits, additionalScript);
+ }
+ return location;
+ }
+
+ /**
+ * Get a simulation directory for this model
+ * @return File directory
+ */
+ public File getExperimentDir() {
+ if(simulationDir == null) {
+ File modelsDir = Activator.getBundleContext().getDataFile("models");
+ String experimentName = this.experimentName;
+ List<String> files = Arrays.asList(modelsDir.list());
+ if (files.contains(experimentName)) {
+ int i = 2;
+ while (files.contains(experimentName + "_" + i)){
+ i++;
+ }
+ experimentName += "_" + i;
+ }
+
+ simulationDir = Activator.getBundleContext().getDataFile("models/" + experimentName);
+ if (!simulationDir.exists()) {
+ simulationDir.mkdir();
+ }
+ }
+ return simulationDir;
+ }
+
+ /**
+ *
+ * @return
+ */
+ protected String getAdditionalScripts() {
+ StringBuilder functionscript = new StringBuilder();
+
+ boolean useModelicaLibraries = false;
+ try {
+ useModelicaLibraries = Simantics.getSession().syncRequest(new Read<Boolean>() {
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ SysdynResource SR = SysdynResource.getInstance(graph);
+ SimulationResource SIM = SimulationResource.getInstance(graph);
+ Resource configuration = graph.getPossibleObject(OldSysdynExperiment.this.model, SIM.HasConfiguration);
+ return graph.hasStatement(configuration, SR.SysdynModel_useModelicaLibraries);
+ }
+ });
+ } catch (DatabaseException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if (useModelicaLibraries)
+ functionscript.append("loadModel(Modelica);\n");
+
+ for(String path : FunctionUtils.getLibraryPathsForModelica(this)) {
+ functionscript.append("loadFile(\"" + path + "\");\n");
+ }
+ return functionscript.toString();
+ }
+
+ /**
+ * Starts simulating a model. Call only from inside simulation job! Start simulation using simulate(true).
+ * @param monitor
+ * @param progressMonitor
+ * @throws IOException
+ */
+ public synchronized void simulate(final IModelicaMonitor monitor, final IProgressMonitor progressMonitor, String modelName) throws IOException {
+ canceled = false;
+ progressMonitor.subTask("Write modelica classes");
+
+ omcVersion = ModelicaManager.getDefaultOMVersion();
+
+ monitor.message("Simulate " + modelName + " using OpenModelica " + omcVersion);
+
+ // Get Modelica code
+ String modelText = getModelicaCode(monitor, false, omcVersion);
+ if(modelText == null)
+ return;
+ progressMonitor.worked(1);
+
+ // Write initial files and add init-parameters
+ progressMonitor.subTask("Write simulation files");
+ HashMap<String, String> experimentParameters = getExperimentParameters(monitor);
+
+ // add loadFile script to load all related functions and function libraries
+ String additionalScript = getAdditionalScripts();
+
+ // Create simulation files
+ SimulationLocation simulationLocation = createSimulationFiles(sysdynModel, modelText, experimentParameters, additionalScript, false);
+ progressMonitor.worked(1);
+
+ // Build the model and store previous model structure and inits that affect the building
+ // If there is no exe file OR the model structure has not changed, no need to build
+ String flatModelText = ModelicaManager.getFlatModelText(simulationLocation, monitor, FunctionUtils.getLibraryPathsForModelica(this));
+
+ boolean structureChanged = sysdynModel.isStructureModified();
+
+ if (!simulationLocation.executableFile.isFile() || structureChanged) {
+ progressMonitor.subTask("Build model");
+ defaultParameters = ModelicaManager.getModelParameters(flatModelText);
+
+ buildModel(simulationLocation, monitor);
+ }
+
+ // Add changed parameters in case that structure has not changed
+ HashMap<String, String> parameterChanges = new HashMap<String, String>();
+ if(!structureChanged && defaultParameters != null) {
+ HashMap<String, String> currentParameters = ModelicaManager.getModelParameters(flatModelText);
+ for(String key : defaultParameters.keySet()) {
+ if(!defaultParameters.get(key).equals(currentParameters.get(key))) {
+ parameterChanges.put(key, currentParameters.get(key));
+ }
+ }
+ }
+ progressMonitor.worked(1);
+
+ if(simulationLocation != null && !canceled) {
+ // Simulate the model
+ runModelica(simulationLocation, monitor, progressMonitor, experimentParameters, parameterChanges);
+ }
+
+ if(canceled)
+ simulate(false);
+ process = null;
+ }
+
+ /**
+ * Get the version of the OpenModelica compiler that is defined to be used
+ * in Preferences
+ * @return OpenModelica version
+ */
+ protected String getOpenModelicaVersion() {
+ String omVersion = null;
+
+ IScopeContext context = DefaultScope.INSTANCE;
+ Preferences node = context.getNode(org.simantics.modelica.Activator.PLUGIN_ID);
+ String omHome = node.get(OpenModelicaPreferences.OM_HOME, null);
+ if(omHome != null) {
+ File omHomeDir = new File(omHome);
+ if(omHomeDir != null && omHomeDir.isDirectory())
+ omVersion = ModelicaManager.getOMVersion(omHomeDir);
+ }
+
+ if(omVersion == null) {
+ omVersion = ModelicaManager.getDefaultOMVersion();
+ }
+
+ return omVersion;
+ }
+
+ /**
+ * Destroy an ongoing simulation process
+ */
+ public void cancelSimulation() {
+ canceled = true;
+ if(process != null) {
+ process.destroy();
+ }
+ }
+
+ /**
+ * Toggle simulation state
+ * @param enabled true == RUNNING, false == STOPPED
+ */
+ public void toggleSimulation(boolean enabled) {
+ if(enabled) {
+ this.toggled = true;
+ changeState(ExperimentState.RUNNING);
+ if(modificationListener == null) {
+
+ modificationListener = new Runnable() {
+
+ @Override
+ public void run() {
+ session.asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ if(getState() == ExperimentState.RUNNING) {
+ SimulationScheduler.start(sysdynModel, OldSysdynExperiment.this);
+ }
+
+ }
+ });
+
+ };
+ };
+ sysdynModel.addModificationListener(modificationListener);
+ }
+ }
+ else {
+ changeState(ExperimentState.STOPPED);
+ this.toggled = false;
+ }
+
+ }
+
+ @Override
+ protected void localStateChange() {
+ setSysdynExperimentState(getState());
+ switch(state) {
+ case DISPOSED:
+ onExperimentDisposed();
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ /**
+ * Returns sysdyn experiment state. It is usually the same as ordinary experiment state.
+ * Initializing phase takes longer than normally in game experiments.
+ * @return
+ */
+ public ExperimentState getSysdynExperimentState() {
+ return sysdynExperimentState;
+ }
+
+ protected void setSysdynExperimentState(final ExperimentState state) {
+ sysdynExperimentState = state;
+ VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
+ session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 L0 = Layer0.getInstance(graph);
+ SimulationResource SR = SimulationResource.getInstance(graph);
+ graph.deny(model, SR.HasExperimentState);
+ graph.deny(experiment, SR.HasExperimentState);
+
+ Resource st = graph.newResource();
+ switch(state) {
+ case INITIALIZING:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing);
+ break;
+ case RUNNING:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running);
+ break;
+ case STOPPED:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped);
+ break;
+ case DISPOSED:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed);
+ break;
+ }
+
+ graph.claim(model, SR.HasExperimentState, st);
+ graph.claim(experiment, SR.HasExperimentState, st);
+ }});
+ }
+
+ /**
+ * Actions performed when experiment is disposed
+ * @param graph
+ */
+ protected void onExperimentDisposed() {
+ cancelSimulation();
+ sysdynModel.removeModificationListener(modificationListener);
+ modificationListener = null;
+
+ session.asyncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ toggleActivation(graph, false);
+ }
+ });
+ }
+
+
+ /**
+ * Toggles the active-state of this experiment on or off
+ * @param graph ReadGraph
+ * @param activate The active-state of this experiment
+ */
+ protected void toggleActivation(ReadGraph graph, final boolean activate) {
+ VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
+ final Session session = graph.getSession();
+ session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ VirtualGraph runtime = graph.getService(VirtualGraph.class);
+
+ session.asyncRequest(new WriteRequest(runtime) {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SimulationResource SIMU = SimulationResource.getInstance(graph);
+ if(activate)
+ graph.claim(experiment, SIMU.IsActive, experiment);
+ else
+ graph.denyStatement(experiment, SIMU.IsActive, experiment);
+ }
+
+ });
+ }
+ });
+ }
+
+
+ /* Result subscriptions */
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Copy from AprosExperiment
+ * @param subscription
+ */
+ @Override
+ public void addVariableValueSubscription(VariableValueSubscription subscription) {
+ assert subscription != null;
+ synchronized (variableValueSubscriptions) {
+ //System.out.println("ADD listener " + subscription);
+ variableValueSubscriptions.add(subscription);
+ variableValueSubscriptionsSnapshot = null;
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Copy from AprosExperiment
+ * @param subscription
+ */
+ @Override
+ public void removeVariableValueSubscription(VariableValueSubscription subscription) {
+ assert subscription != null;
+ synchronized (variableValueSubscriptions) {
+ //System.out.println("REMOVE listener " + subscription);
+ variableValueSubscriptions.remove(subscription);
+ variableValueSubscriptionsSnapshot = null;
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Copy from AprosExperiment
+ * @return
+ */
+ @Override
+ public VariableValueSubscription[] getListenerSnapshot() {
+ VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot;
+ if (snapshot == null) {
+ synchronized (variableValueSubscriptions) {
+ snapshot = variableValueSubscriptionsSnapshot;
+ if (snapshot == null) {
+ snapshot = variableValueSubscriptionsSnapshot = variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]);
+ }
+ }
+ //System.out.println("listener count: " + snapshot.length);
+ }
+ return snapshot;
+ }
+
+ volatile long previousVariableUpdateTime = 0;
+ volatile boolean skippedVariableUpdate = true;
+
+
+ /**
+ * Modified copy from AprosExperiment
+ */
+ public void resultsChanged() {
+ resultsChanged(false);
+ }
+
+ protected void onPublishResults() {
+ resultsChanged(true);
+ }
+
+ public void setPublishResults(boolean value) {
+ publishResults = value;
+ if(publishResults) {
+ onPublishResults();
+ }
+ }
+
+ public void resultsChanged(boolean force) {
+ long time = System.nanoTime();
+ long sinceLast = time - previousVariableUpdateTime;
+// System.err.println("sinceLast " + 1e-9*sinceLast);
+ if(sinceLast > 100000000 || force) {
+ updateSubscriptions();
+ previousVariableUpdateTime = time;
+ }
+ else
+ skippedVariableUpdate = true;
+ }
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Modified copy from AporsExperiment
+ */
+ @Override
+ public void updateSubscriptions() {
+ if(publishResults) publishRead.fire();
+ for(VariableValueSubscription subscription : getListenerSnapshot())
+ subscription.update();
+ skippedVariableUpdate = false;
+ }
+
+ public int numberOfSimulationRunSteps() {
+ /*
+ * 1. Write modelica files
+ * 2. Write other simulation files
+ * 3. Build model OR update parameters
+ * 4. Run modelica
+ * 5. Read results
+ */
+ return 5;
+ }
+
+
+ /* Experiment methods that are not used in this experiment */
+
+ @Override
+ public Lock getDatasourceLock() {
+ return null;
+ }
+
+ @Override
+ public Datasource getDatasource() {
+ return null;
+ }
+
+ @Override
+ public void simulateDuration(double duration) {
+
+ }
+
+
+ @Override
+ public void rewindTo(double time) {
+
+ }
+
+}
+
-/*******************************************************************************\r
- * Copyright (c) 2010, 2013 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- * Semantum Oy - Bug #4180\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.manager;\r
-\r
-import gnu.trove.set.hash.THashSet;\r
-\r
-import java.io.File;\r
-import java.util.ArrayList;\r
-import java.util.Arrays;\r
-import java.util.Collection;\r
-import java.util.List;\r
-import java.util.concurrent.locks.Lock;\r
-\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.RequestProcessor;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.VirtualGraph;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.service.VirtualGraphSupport;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.simulation.data.Datasource;\r
-import org.simantics.simulation.experiment.Experiment;\r
-import org.simantics.simulation.experiment.ExperimentState;\r
-import org.simantics.simulation.experiment.IDynamicExperiment;\r
-import org.simantics.simulation.experiment.IExperimentListener;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.sysdyn.Activator;\r
-import org.simantics.sysdyn.adapter.VariableValueSubscription;\r
-import org.simantics.sysdyn.solver.SysdynSimulationJob;\r
-import org.simantics.sysdyn.solver.SolverSettings;\r
-import org.simantics.sysdyn.solver.SolverSettings.SolverType;\r
-\r
-public class SysdynExperiment extends Experiment implements IDynamicExperiment, VariableSubscriptionManager {\r
- \r
- // TODO: change to protected as necessary when oldSysdynExperiment is removed\r
- \r
- private Session session;\r
- private Runnable modificationListener;\r
- public SysdynModel sysdynModel;\r
- private boolean toggled = false;\r
-\r
- @SuppressWarnings("rawtypes")\r
- private THashSet<VariableValueSubscription> variableValueSubscriptions = new THashSet<VariableValueSubscription>();\r
- @SuppressWarnings("rawtypes")\r
- private VariableValueSubscription[] variableValueSubscriptionsSnapshot = null;\r
-\r
- private Process process;\r
- private boolean canceled = false;\r
- private ExperimentState sysdynExperimentState;\r
-\r
- private SysdynResult result;\r
- \r
- private String experimentName;\r
- private File experimentDir;\r
-\r
- public SysdynExperiment(Resource experiment, Resource model) {\r
- super(experiment, model);\r
- this.experimentName = "Experiment";\r
- this.experimentDir = null;\r
- }\r
-\r
- public SysdynResult getCurrentResult() {\r
- if(this.result == null)\r
- this.result = new MemoryResult(null, null);\r
- return this.result;\r
- }\r
- \r
- public void setCurrentResult(SysdynResult result) {\r
- this.result = result;\r
- }\r
-\r
- public Collection<SysdynResult> getActiveResults() {\r
- ArrayList<SysdynResult> result = new ArrayList<SysdynResult>();\r
- if(getCurrentResult() != null)\r
- result.add(getCurrentResult());\r
- result.addAll(sysdynModel.getDisplayedResults());\r
- return result;\r
- }\r
-\r
- /**\r
- * Initialize this experiment\r
- * @param g ReadGraph\r
- */\r
- public void init(ReadGraph g) throws DatabaseException {\r
- try {\r
- this.experimentName = NameUtils.getSafeName(g, experiment);\r
- } catch (DatabaseException e) {\r
- this.experimentName = "Experiment";\r
- }\r
-\r
- this.session = g.getSession();\r
- state = ExperimentState.STOPPED;\r
- for(IExperimentListener listener : listeners.getListeners())\r
- listener.stateChanged(state);\r
- \r
- final Resource configuration = g.getPossibleObject(model, SimulationResource.getInstance(g).HasConfiguration);\r
- sysdynModel = SysdynModelManager.getInstance(session).getModel(g, configuration);\r
- toggleActivation(g, true);\r
-\r
- setSysdynExperimentState(ExperimentState.INITIALIZING);\r
- }\r
-\r
- @Override\r
- public void saveState() {\r
- if(result == null || !(result instanceof MemoryResult)) \r
- return;\r
- // TODO: fix this\r
- //SaveResultJob saveResultJob = new SaveResultJob(AltSysdynExperiment.this, session, result);\r
- //saveResultJob.schedule();\r
- }\r
-\r
- protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) {\r
- return new Thread() {\r
- @Override\r
- public void run() {\r
- if(!canceled) {\r
- // Get and store results\r result.saveToFile(file, progressMonitor);\r
- }\r }\r
- };\r
- }\r
-\r
- @Override\r
- public void simulate(boolean enabled) {\r
- // TODO: add state checks\r
- if (enabled) {\r
- SysdynSimulationJob job = new SysdynSimulationJob(sysdynModel.getConfiguration().getLabel(), this);\r
- job.schedule();\r
- }\r
- }\r
-\r
- /**\r
- * Destroy an ongoing simulation process\r
- */\r
- public void cancelSimulation() {\r
- canceled = true;\r
- if(process != null) {\r
- process.destroy();\r
- }\r
- }\r
-\r
- /**\r
- * Toggle simulation state\r
- * @param enabled true == RUNNING, false == STOPPED\r
- */\r
- public void toggleSimulation(boolean enabled) {\r
- if(enabled) {\r
- this.toggled = true;\r
- changeState(ExperimentState.RUNNING);\r
- if(modificationListener == null) {\r
-\r
- modificationListener = new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- session.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- if(getState() == ExperimentState.RUNNING) {\r
- // TODO: fix this\r
- //SimulationScheduler.start(sysdynModel, this);\r
- }\r
-\r
- }\r
- });\r
-\r
- };\r
- };\r
- sysdynModel.addModificationListener(modificationListener);\r
- }\r
- }\r
- else {\r
- changeState(ExperimentState.STOPPED);\r
- this.toggled = false;\r
- }\r
-\r
- }\r
-\r
- @Override\r
- public void refresh(RequestProcessor session) {\r
- session.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- init(graph);\r
- }\r
-\r
- });\r
- }\r
-\r
- @Override\r
- public void refresh(Session session) {\r
- refresh((RequestProcessor)session);\r
- }\r
-\r
- @Override\r
- protected void localStateChange() {\r
- setSysdynExperimentState(getState());\r
- switch(state) {\r
- case DISPOSED:\r
- onExperimentDisposed();\r
- break;\r
- default:\r
- break;\r
- }\r
-\r
- }\r
-\r
- /**\r
- * Returns sysdyn experiment state. It is usually the same as ordinary experiment state.\r
- * Initializing phase takes longer than normally in game experiments.\r
- * @return\r
- */\r
- public ExperimentState getSysdynExperimentState() {\r
- return sysdynExperimentState;\r
- }\r
-\r
- protected void setSysdynExperimentState(final ExperimentState state) {\r
- sysdynExperimentState = state;\r
- session.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
- final Session session = graph.getSession();\r
- session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- SimulationResource SR = SimulationResource.getInstance(graph);\r
- graph.deny(model, SR.HasExperimentState);\r
- graph.deny(experiment, SR.HasExperimentState);\r
-\r
- Resource st = graph.newResource();\r
- switch(state) {\r
- case INITIALIZING:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing);\r
- break;\r
- case RUNNING:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running);\r
- break;\r
- case STOPPED:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped);\r
- break;\r
- case DISPOSED:\r
- graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed);\r
- break;\r
- }\r
-\r
- graph.claim(model, SR.HasExperimentState, st);\r
- graph.claim(experiment, SR.HasExperimentState, st);\r
- }});\r
- }\r
- });\r
- }\r
-\r
- /**\r
- * Actions performed when experiment is disposed\r
- * @param graph\r
- */\r
- protected void onExperimentDisposed() {\r
- cancelSimulation();\r
- sysdynModel.removeModificationListener(modificationListener);\r
- modificationListener = null;\r
-\r
- session.asyncRequest(new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- toggleActivation(graph, false);\r
- }\r
- });\r
- }\r
-\r
-\r
- /**\r
- * Toggles the active-state of this experiment on or off\r
- * @param graph ReadGraph\r
- * @param activate The active-state of this experiment\r
- */\r
- protected void toggleActivation(ReadGraph graph, final boolean activate) {\r
- // TODO: does not work correctly, the experiment can appear inactive even when it is actually active\r
- VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);\r
- final Session session = graph.getSession();\r
- session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- VirtualGraph runtime = graph.getService(VirtualGraph.class);\r
-\r
- session.asyncRequest(new WriteRequest(runtime) {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- SimulationResource SIMU = SimulationResource.getInstance(graph);\r
- if(activate)\r
- graph.claim(experiment, SIMU.IsActive, experiment);\r
- else\r
- graph.denyStatement(experiment, SIMU.IsActive, experiment);\r
- }\r
-\r
- });\r
- }\r
- });\r
- }\r
-\r
-\r
- /* Result subscriptions */\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Copy from AprosExperiment\r
- * @param subscription\r
- */\r
- @Override\r
- public void addVariableValueSubscription(VariableValueSubscription subscription) {\r
- assert subscription != null;\r
- synchronized (variableValueSubscriptions) {\r
- variableValueSubscriptions.add(subscription);\r
- variableValueSubscriptionsSnapshot = null;\r
- }\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Copy from AprosExperiment\r
- * @param subscription\r
- */\r
- @Override\r
- public void removeVariableValueSubscription(VariableValueSubscription subscription) {\r
- assert subscription != null;\r
- synchronized (variableValueSubscriptions) {\r
- variableValueSubscriptions.remove(subscription);\r
- variableValueSubscriptionsSnapshot = null;\r
- }\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Copy from AprosExperiment\r
- * @return\r
- */\r
- @Override\r
- public VariableValueSubscription[] getListenerSnapshot() {\r
- VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot;\r
- if (snapshot == null) {\r
- synchronized (variableValueSubscriptions) {\r
- snapshot = variableValueSubscriptionsSnapshot;\r
- if (snapshot == null) {\r
- snapshot = variableValueSubscriptionsSnapshot = \r
- variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]);\r
- }\r
- }\r
- }\r
- return snapshot;\r
- }\r
-\r
- volatile long previousVariableUpdateTime = 0;\r
-\r
- /**\r
- * Modified copy from AprosExperiment\r
- */\r
- public void resultsChanged() {\r
- long time = System.nanoTime();\r
- if (time - previousVariableUpdateTime > 10000000) {\r
- updateSubscriptions();\r
- previousVariableUpdateTime = time;\r
- }\r
- }\r
-\r
- @SuppressWarnings("rawtypes")\r
- /**\r
- * Modified copy from AporsExperiment\r
- */\r
- @Override\r
- public void updateSubscriptions() {\r
- for(VariableValueSubscription subscription : getListenerSnapshot())\r
- subscription.update();\r
- }\r
-\r
- /* Experiment methods that are not used in this experiment */\r
-\r
- @Override\r
- public Lock getDatasourceLock() {\r
- throw new UnsupportedOperationException();\r
- }\r
-\r
- @Override\r
- public Datasource getDatasource() {\r
- throw new UnsupportedOperationException();\r
- }\r
-\r
- @Override\r
- public void simulateDuration(double duration) {\r
- throw new UnsupportedOperationException();\r
- }\r
-\r
- @Override\r
- public void rewindTo(double time) {\r
- throw new UnsupportedOperationException();\r
- }\r
- \r
- \r
- \r
- // TODO: clean this up a bit maybe?\r
- public File getExperimentDir() {\r
- if (experimentDir == null) {\r
- File modelsDir = Activator.getBundleContext().getDataFile("models");\r
- String name = experimentName;\r
- List<String> files = Arrays.asList(modelsDir.list());\r
- if (files.contains(name)) {\r
- int i = 2;\r
- while (files.contains(name + "_" + i)){\r
- i++;\r
- }\r
- name += "_" + i;\r
- }\r
- experimentDir = new File(modelsDir, name);\r
- experimentDir.mkdir();\r
- }\r
- \r
- return experimentDir;\r
- }\r
- \r
- public SolverType getSolverType() {\r
- // should be defined in experiment properties (similarly to other experiment types)\r
- return SolverSettings.getSelectedSolverType();\r
- }\r
-\r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 2010, 2013 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 - Bug #4180
+ *******************************************************************************/
+package org.simantics.sysdyn.manager;
+
+import gnu.trove.set.hash.THashSet;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.locks.Lock;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.RequestProcessor;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.VirtualGraph;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.request.WriteRequest;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.service.VirtualGraphSupport;
+import org.simantics.layer0.Layer0;
+import org.simantics.simulation.data.Datasource;
+import org.simantics.simulation.experiment.Experiment;
+import org.simantics.simulation.experiment.ExperimentState;
+import org.simantics.simulation.experiment.IDynamicExperiment;
+import org.simantics.simulation.experiment.IExperimentListener;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.sysdyn.Activator;
+import org.simantics.sysdyn.adapter.VariableValueSubscription;
+import org.simantics.sysdyn.solver.SysdynSimulationJob;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.simantics.sysdyn.solver.SolverSettings;
+import org.simantics.sysdyn.solver.SolverSettings.SolverType;
+
+public class SysdynExperiment extends Experiment implements IDynamicExperiment, VariableSubscriptionManager {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(SysdynExperiment.class);
+
+ // TODO: change to protected as necessary when oldSysdynExperiment is removed
+
+ private Session session;
+ private Runnable modificationListener;
+ public SysdynModel sysdynModel;
+ private boolean toggled = false;
+
+ @SuppressWarnings("rawtypes")
+ private THashSet<VariableValueSubscription> variableValueSubscriptions = new THashSet<VariableValueSubscription>();
+ @SuppressWarnings("rawtypes")
+ private VariableValueSubscription[] variableValueSubscriptionsSnapshot = null;
+
+ private Process process;
+ private boolean canceled = false;
+ private ExperimentState sysdynExperimentState;
+
+ private SysdynResult result;
+
+ private String experimentName;
+ private File experimentDir;
+
+ public SysdynExperiment(Resource experiment, Resource model) {
+ super(experiment, model);
+ this.experimentName = "Experiment";
+ this.experimentDir = null;
+ }
+
+ public SysdynResult getCurrentResult() {
+ if(this.result == null)
+ this.result = new MemoryResult(null, null);
+ return this.result;
+ }
+
+ public void setCurrentResult(SysdynResult result) {
+ this.result = result;
+ }
+
+ public Collection<SysdynResult> getActiveResults() {
+ ArrayList<SysdynResult> result = new ArrayList<SysdynResult>();
+ if(getCurrentResult() != null)
+ result.add(getCurrentResult());
+ result.addAll(sysdynModel.getDisplayedResults());
+ return result;
+ }
+
+ /**
+ * Initialize this experiment
+ * @param g ReadGraph
+ */
+ public void init(ReadGraph g) throws DatabaseException {
+ try {
+ this.experimentName = NameUtils.getSafeName(g, experiment);
+ } catch (DatabaseException e) {
+ this.experimentName = "Experiment";
+ }
+
+ this.session = g.getSession();
+ state = ExperimentState.STOPPED;
+ for(IExperimentListener listener : listeners.getListeners())
+ listener.stateChanged(state);
+
+ final Resource configuration = g.getPossibleObject(model, SimulationResource.getInstance(g).HasConfiguration);
+ sysdynModel = SysdynModelManager.getInstance(session).getModel(g, configuration);
+ toggleActivation(g, true);
+
+ setSysdynExperimentState(ExperimentState.INITIALIZING);
+ }
+
+ @Override
+ public void saveState() {
+ if(result == null || !(result instanceof MemoryResult))
+ return;
+ // TODO: fix this
+ //SaveResultJob saveResultJob = new SaveResultJob(AltSysdynExperiment.this, session, result);
+ //saveResultJob.schedule();
+ }
+
+ protected Thread getSaveThread(final SysdynResult result, final File file, final IProgressMonitor progressMonitor) {
+ return new Thread() {
+ @Override
+ public void run() {
+ if(!canceled) {
+ // Get and store results\r result.saveToFile(file, progressMonitor);
+ }\r }
+ };
+ }
+
+ @Override
+ public void simulate(boolean enabled) {
+ // TODO: add state checks
+ if (enabled) {
+ SysdynSimulationJob job = new SysdynSimulationJob(sysdynModel.getConfiguration().getLabel(), this);
+ job.schedule();
+ }
+ }
+
+ /**
+ * Destroy an ongoing simulation process
+ */
+ public void cancelSimulation() {
+ canceled = true;
+ if(process != null) {
+ process.destroy();
+ }
+ }
+
+ /**
+ * Toggle simulation state
+ * @param enabled true == RUNNING, false == STOPPED
+ */
+ public void toggleSimulation(boolean enabled) {
+ if(enabled) {
+ this.toggled = true;
+ changeState(ExperimentState.RUNNING);
+ if(modificationListener == null) {
+
+ modificationListener = new Runnable() {
+
+ @Override
+ public void run() {
+ session.asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ if(getState() == ExperimentState.RUNNING) {
+ // TODO: fix this
+ //SimulationScheduler.start(sysdynModel, this);
+ }
+
+ }
+ });
+
+ };
+ };
+ sysdynModel.addModificationListener(modificationListener);
+ }
+ }
+ else {
+ changeState(ExperimentState.STOPPED);
+ this.toggled = false;
+ }
+
+ }
+
+ @Override
+ public void refresh(RequestProcessor session) {
+ try {
+ session.syncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ init(graph);
+ }
+
+ });
+ } catch (DatabaseException e) {
+ LOGGER.error("refresh failed", e);
+ }
+ }
+
+ @Override
+ public void refresh(Session session) {
+ refresh((RequestProcessor)session);
+ }
+
+ @Override
+ protected void localStateChange() {
+ setSysdynExperimentState(getState());
+ switch(state) {
+ case DISPOSED:
+ onExperimentDisposed();
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ /**
+ * Returns sysdyn experiment state. It is usually the same as ordinary experiment state.
+ * Initializing phase takes longer than normally in game experiments.
+ * @return
+ */
+ public ExperimentState getSysdynExperimentState() {
+ return sysdynExperimentState;
+ }
+
+ protected void setSysdynExperimentState(final ExperimentState state) {
+ sysdynExperimentState = state;
+ session.asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
+ final Session session = graph.getSession();
+ session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 L0 = Layer0.getInstance(graph);
+ SimulationResource SR = SimulationResource.getInstance(graph);
+ graph.deny(model, SR.HasExperimentState);
+ graph.deny(experiment, SR.HasExperimentState);
+
+ Resource st = graph.newResource();
+ switch(state) {
+ case INITIALIZING:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Initializing);
+ break;
+ case RUNNING:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Running);
+ break;
+ case STOPPED:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Stopped);
+ break;
+ case DISPOSED:
+ graph.claim(st, L0.InstanceOf, SR.ExperimentState_Disposed);
+ break;
+ }
+
+ graph.claim(model, SR.HasExperimentState, st);
+ graph.claim(experiment, SR.HasExperimentState, st);
+ }});
+ }
+ });
+ }
+
+ /**
+ * Actions performed when experiment is disposed
+ * @param graph
+ */
+ protected void onExperimentDisposed() {
+ cancelSimulation();
+ sysdynModel.removeModificationListener(modificationListener);
+ modificationListener = null;
+
+ session.asyncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ toggleActivation(graph, false);
+ }
+ });
+ }
+
+
+ /**
+ * Toggles the active-state of this experiment on or off
+ * @param graph ReadGraph
+ * @param activate The active-state of this experiment
+ */
+ protected void toggleActivation(ReadGraph graph, final boolean activate) {
+ // TODO: does not work correctly, the experiment can appear inactive even when it is actually active
+ VirtualGraphSupport support = graph.getService(VirtualGraphSupport.class);
+ final Session session = graph.getSession();
+ session.asyncRequest(new WriteRequest(support.getWorkspacePersistent("experiments")) {
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ VirtualGraph runtime = graph.getService(VirtualGraph.class);
+
+ session.asyncRequest(new WriteRequest(runtime) {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ SimulationResource SIMU = SimulationResource.getInstance(graph);
+ if(activate)
+ graph.claim(experiment, SIMU.IsActive, experiment);
+ else
+ graph.denyStatement(experiment, SIMU.IsActive, experiment);
+ }
+
+ });
+ }
+ });
+ }
+
+
+ /* Result subscriptions */
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Copy from AprosExperiment
+ * @param subscription
+ */
+ @Override
+ public void addVariableValueSubscription(VariableValueSubscription subscription) {
+ assert subscription != null;
+ synchronized (variableValueSubscriptions) {
+ variableValueSubscriptions.add(subscription);
+ variableValueSubscriptionsSnapshot = null;
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Copy from AprosExperiment
+ * @param subscription
+ */
+ @Override
+ public void removeVariableValueSubscription(VariableValueSubscription subscription) {
+ assert subscription != null;
+ synchronized (variableValueSubscriptions) {
+ variableValueSubscriptions.remove(subscription);
+ variableValueSubscriptionsSnapshot = null;
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Copy from AprosExperiment
+ * @return
+ */
+ @Override
+ public VariableValueSubscription[] getListenerSnapshot() {
+ VariableValueSubscription[] snapshot = variableValueSubscriptionsSnapshot;
+ if (snapshot == null) {
+ synchronized (variableValueSubscriptions) {
+ snapshot = variableValueSubscriptionsSnapshot;
+ if (snapshot == null) {
+ snapshot = variableValueSubscriptionsSnapshot =
+ variableValueSubscriptions.toArray(new VariableValueSubscription[variableValueSubscriptions.size()]);
+ }
+ }
+ }
+ return snapshot;
+ }
+
+ volatile long previousVariableUpdateTime = 0;
+
+ /**
+ * Modified copy from AprosExperiment
+ */
+ public void resultsChanged() {
+ long time = System.nanoTime();
+ if (time - previousVariableUpdateTime > 10000000) {
+ updateSubscriptions();
+ previousVariableUpdateTime = time;
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ /**
+ * Modified copy from AporsExperiment
+ */
+ @Override
+ public void updateSubscriptions() {
+ for(VariableValueSubscription subscription : getListenerSnapshot())
+ subscription.update();
+ }
+
+ /* Experiment methods that are not used in this experiment */
+
+ @Override
+ public Lock getDatasourceLock() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Datasource getDatasource() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void simulateDuration(double duration) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void rewindTo(double time) {
+ throw new UnsupportedOperationException();
+ }
+
+
+
+ // TODO: clean this up a bit maybe?
+ public File getExperimentDir() {
+ if (experimentDir == null) {
+ File modelsDir = Activator.getBundleContext().getDataFile("models");
+ String name = experimentName;
+ List<String> files = Arrays.asList(modelsDir.list());
+ if (files.contains(name)) {
+ int i = 2;
+ while (files.contains(name + "_" + i)){
+ i++;
+ }
+ name += "_" + i;
+ }
+ experimentDir = new File(modelsDir, name);
+ experimentDir.mkdir();
+ }
+
+ return experimentDir;
+ }
+
+ public SolverType getSolverType() {
+ // should be defined in experiment properties (similarly to other experiment types)
+ return SolverSettings.getSelectedSolverType();
+ }
+
+}
+
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.simantics.Simantics;
import org.simantics.databoard.Bindings;
+import org.simantics.db.AsyncReadGraph;
import org.simantics.db.ReadGraph;
import org.simantics.db.Resource;
import org.simantics.db.Session;
import org.simantics.db.WriteGraph;
+import org.simantics.db.common.request.AsyncReadRequest;
import org.simantics.db.common.utils.NameUtils;
import org.simantics.db.exception.DatabaseException;
import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
import org.simantics.sysdyn.solver.SolverSettings;
import org.simantics.sysdyn.solver.SolverSettings.SolverType;
import org.simantics.sysdyn.solver.Solvers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import gnu.trove.set.hash.THashSet;
*/
public class SysdynModel implements IModel, IMappingListener, VariableSubscriptionManager {
+ private static final Logger LOGGER = LoggerFactory.getLogger(SysdynModel.class);
+
private Session session;
private IMapping mapping;
* @param g ReadGraph
* @param configurationResource Configration resource of the model
*/
- public SysdynModel(ReadGraph g, Resource configurationResource) {
+ public SysdynModel(ReadGraph g, Resource configurationResource) throws DatabaseException {
this.session = g.getSession();
this.configurationResource = configurationResource;
- try {
- createMapping(g);
- } catch(DatabaseException e) {
- e.printStackTrace();
- }
+ createMapping(g);
+
+ AtomicBoolean disposed = new AtomicBoolean(false);
- g.asyncRequest(new Read<ArrayList<SysdynResult>> () {
- @Override
- public ArrayList<SysdynResult> perform(ReadGraph graph) throws DatabaseException {
- ArrayList<SysdynResult> displayedResults = new ArrayList<SysdynResult>();
- // TODO: this can be done automatically with a listener
+ g.syncRequest(new AsyncReadRequest() {
+
+ @Override
+ public void run(AsyncReadGraph g2) {
+
+ g2.asyncRequest((Read<ArrayList<SysdynResult>>) graph -> {
+ ArrayList<SysdynResult> displayedResults = new ArrayList<>();
+ // TODO: this can be done automatically with a listener
- for(HistoryDatasetResult hs : listeningHistories)
- hs.disposeListeners(); // dispose old histories listening to spreadsheets
+ for(HistoryDatasetResult hs : listeningHistories)
+ hs.disposeListeners(); // dispose old histories listening to spreadsheets
- try {
- // Find all active saved results
- Layer0 l0 = Layer0.getInstance(graph);
- SysdynResource sr = SysdynResource.getInstance(graph);
- SimulationResource SIMU = SimulationResource.getInstance(graph);
- Resource model = graph.getPossibleObject(getConfigurationResource(), SIMU.IsConfigurationOf);
- if(model == null)
- return null;
-
- Collection<Resource> results = graph.syncRequest(new ActiveResults(model));
- for(Resource result : results) {
- if(graph.hasStatement(result, sr.Result_showResult)) {
- SysdynResult sysdynResult = null;
- if(graph.isInstanceOf(result, sr.HistoryDataset)) {
- HistoryDatasetResult r = new HistoryDatasetResult();
- listeningHistories.add(r);
- sysdynResult = new MemoryResult(r, NameUtils.getSafeLabel(graph, result));
- r.read((MemoryResult)sysdynResult, result);
- } else {
- sysdynResult = new FileResult(
- (String) graph.getPossibleRelatedValue(result, l0.HasLabel),
- (String) graph.getPossibleRelatedValue(result, sr.Result_resultFile));
- }
-
- if(sysdynResult != null)
- displayedResults.add(sysdynResult);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return displayedResults;
- }
-
+ try {
+ // Find all active saved results
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ SimulationResource SIMU = SimulationResource.getInstance(graph);
+ Resource model = graph.getPossibleObject(getConfigurationResource(), SIMU.IsConfigurationOf);
+ if(model == null)
+ return null;
+
+ Collection<Resource> results = graph.syncRequest(new ActiveResults(model));
+ for(Resource result : results) {
+ if(graph.hasStatement(result, sr.Result_showResult)) {
+ SysdynResult sysdynResult = null;
+ if(graph.isInstanceOf(result, sr.HistoryDataset)) {
+ HistoryDatasetResult r = new HistoryDatasetResult();
+ listeningHistories.add(r);
+ sysdynResult = new MemoryResult(r, NameUtils.getSafeLabel(graph, result));
+ r.read((MemoryResult)sysdynResult, result);
+ } else {
+ sysdynResult = new FileResult(
+ (String) graph.getPossibleRelatedValue(result, l0.HasLabel),
+ (String) graph.getPossibleRelatedValue(result, sr.Result_resultFile));
+ }
+
+ if(sysdynResult != null)
+ displayedResults.add(sysdynResult);
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.error("Failed to read history results", e);
+ }
+
+ return displayedResults;
}, new Listener<ArrayList<SysdynResult>> () {
- @Override
- public void execute(ArrayList<SysdynResult> result) {
- // Add the current result if there is one
- displayedResults = result;
- resultChanged();
- }
+ @Override
+ public void execute(ArrayList<SysdynResult> result) {
+ // Add the current result if there is one
+ displayedResults = result;
+ resultChanged();
+ }
- @Override
- public void exception(Throwable t) {
- t.printStackTrace();
- }
+ @Override
+ public void exception(Throwable t) {
+ LOGGER.error("History Result listening request failed", t);
+ }
- @Override
- public boolean isDisposed() {
- return false;
- }
+ @Override
+ public boolean isDisposed() {
+ return disposed.get();
+ }
});
+ }
+
+ });
+
}
// A dummy call for experiments
SimulationResource simu = SimulationResource.getInstance(g);
try {
configurationResource = g.getPossibleObject(modelResource, simu.HasConfiguration);
- } catch (ManyObjectsForFunctionalRelationException e) {
- e.printStackTrace();
- } catch (ServiceException e) {
- e.printStackTrace();
+ } catch (ManyObjectsForFunctionalRelationException | ServiceException e) {
+ listener.onFailure(e);
+ return null;
}
}
-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.manager;\r
-\r
-import java.util.WeakHashMap;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-\r
-/**\r
- * Manages system dynamic models.\r
- * @author Hannu Niemistö\r
- */\r
-public class SysdynModelManager {\r
- WeakHashMap<Resource, SysdynModel> models =\r
- new WeakHashMap<Resource, SysdynModel>(); // FIXME: Resources are weak, there is no guarantee that model exists in this map as long as needed.\r
- // HashTable with a disposal procedure could be better solution..\r
- Session session;\r
-\r
- public SysdynModelManager(Session session) {\r
- this.session = session;\r
- }\r
-\r
- /**\r
- * Use only if not inside a transaction\r
- */\r
- public SysdynModel getModel(final Resource resource) {\r
- synchronized(models) {\r
- SysdynModel model = models.get(resource);\r
- if(model == null) {\r
- try {\r
- session.syncRequest(new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- SysdynModel model = new SysdynModel(graph, resource);\r
- models.put(resource, model);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- model = models.get(resource);\r
- }\r
- return model;\r
- }\r
- }\r
- \r
- /**\r
- * Should be used if called inside a transaction\r
- */\r
- public SysdynModel getModel(ReadGraph g, Resource resource) {\r
- synchronized(models) {\r
- SysdynModel model = models.get(resource);\r
- if(model == null) {\r
- model = new SysdynModel(g, resource);\r
- models.put(resource, model);\r
- }\r
- return model;\r
- }\r
- }\r
-\r
- public synchronized static SysdynModelManager getInstance(Session session) {\r
- SysdynModelManager manager =\r
- session.peekService(SysdynModelManager.class);\r
- if(manager == null) {\r
- manager = new SysdynModelManager(session);\r
- session.registerService(SysdynModelManager.class, manager);\r
- }\r
- return manager;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 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.sysdyn.manager;
+
+import java.util.WeakHashMap;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.exception.DatabaseException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Manages system dynamic models.
+ * @author Hannu Niemistö
+ */
+public class SysdynModelManager {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(SysdynModelManager.class);
+
+ WeakHashMap<Resource, SysdynModel> models =
+ new WeakHashMap<Resource, SysdynModel>(); // FIXME: Resources are weak, there is no guarantee that model exists in this map as long as needed.
+ // HashTable with a disposal procedure could be better solution..
+ Session session;
+
+ public SysdynModelManager(Session session) {
+ this.session = session;
+ }
+
+ /**
+ * Use only if not inside a transaction
+ */
+ public SysdynModel getModel(final Resource resource) throws DatabaseException {
+ synchronized(models) {
+ SysdynModel model = models.get(resource);
+ if(model == null) {
+ try {
+ session.syncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ SysdynModel model = new SysdynModel(graph, resource);
+ models.put(resource, model);
+ }
+ });
+ } catch (DatabaseException e) {
+ LOGGER.error("Failed to find model", e);
+ throw e;
+ }
+
+ model = models.get(resource);
+ }
+ return model;
+ }
+ }
+
+ /**
+ * Should be used if called inside a transaction
+ */
+ public SysdynModel getModel(ReadGraph g, Resource resource) throws DatabaseException {
+ synchronized(models) {
+ SysdynModel model = models.get(resource);
+ if(model == null) {
+ try {
+ model = new SysdynModel(g, resource);
+ } catch (DatabaseException e) {
+ LOGGER.error("Failed to initialize SysdynModel for " + resource, e);
+ throw e;
+ }
+ models.put(resource, model);
+ }
+ return model;
+ }
+ }
+
+ public synchronized static SysdynModelManager getInstance(Session session) {
+ SysdynModelManager manager =
+ session.peekService(SysdynModelManager.class);
+ if(manager == null) {
+ manager = new SysdynModelManager(session);
+ session.registerService(SysdynModelManager.class, manager);
+ }
+ return manager;
+ }
+}
-package org.simantics.sysdyn.utils;\r
-\r
-import java.io.StringReader;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.HashMap;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.unitParser.ParseException;\r
-import org.simantics.sysdyn.unitParser.UnitCheckingException;\r
-import org.simantics.sysdyn.unitParser.UnitCheckingNode;\r
-import org.simantics.sysdyn.unitParser.UnitParser;\r
-import org.simantics.sysdyn.unitParser.nodes.UnitResult;\r
-import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-\r
-/**\r
- * Class to store function name, type, and parameters. \r
- * \r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class Function implements Comparable<Function>{\r
-\r
- private final String name;\r
- private final Type type;\r
- private final ArrayList<Input> inputList;\r
- private final ArrayList<Output> outputList;\r
- private final String description;\r
- \r
- public static class Parameter {\r
- public static final String ANY = "ANY";\r
- public static final String TIME = "TIME";\r
- public String name;\r
- public String unit = ANY;\r
- \r
- public UnitResult getUnitResult(\r
- HashMap<String, String> units, \r
- Function f,\r
- ArrayList<Function> functions,\r
- boolean allowEquivalents,\r
- HashMap<String, String> correspondences) throws UnitCheckingException {\r
- \r
- UnitResult result = new UnitResult(allowEquivalents);\r
- if (Parameter.ANY.equals(this.unit)) {\r
- result.setUnitType(UnitType.ANY);\r
- } else if ("1".equals(this.unit)) { // TODO: see if this should be changed to something else\r
- result.setUnitType(UnitType.SCALAR);\r
- } else {\r
- // Replace TIME with actual time unit.\r
- String timeUnit = units.get("time");\r
- String timeReplaced = this.unit.replace(Parameter.TIME, timeUnit);\r
-\r
- // Replace 'p, 'q, etc. in output with units from actual inputs.\r
- String correspondencesReplaced = replaceCorrespondences(f, timeReplaced, correspondences);\r
-\r
- try {\r
- StringReader outputReader = new StringReader(correspondencesReplaced);\r
- UnitParser outputParser = new UnitParser(outputReader);\r
- UnitCheckingNode output;\r
- output = (UnitCheckingNode) outputParser.expr();\r
- outputReader.close();\r
- result.appendResult(output.getUnits(null, functions, allowEquivalents));\r
- } catch (UnitCheckingException e) {\r
- e.printStackTrace();\r
- } catch (ParseException e) {\r
- throw new UnitCheckingException("Cannot validate units: Syntax error in expression.");\r
- }\r
- }\r
- \r
- return result;\r
- }\r
- \r
- private static String replaceCorrespondences(Function f, String original,\r
- HashMap<String, String> correspondences) throws UnitCheckingException {\r
- int index;\r
- String ret = new String(original);\r
- // Go through the unit as long as there are part of form 'p, 'q, etc. and replace them.\r
- while ((index = ret.indexOf('\'')) >= 0) {\r
- String replaced = ret.substring(index, index + 2); // The replaced units are always of length 2.\r
- try {\r
- ret = ret.replace(replaced, "(" + correspondences.get(replaced) + ")");\r
- } catch (NullPointerException npe) {\r
- throw new UnitCheckingException("Function " + f.getName() + " output unit could not be determined. Replacement unit " \r
- + replaced + " not found in input unit definitions.");\r
- }\r
- }\r
- return ret;\r
- }\r
- }\r
-\r
- public static class Input extends Parameter {\r
- public boolean variableLength = false;\r
- public boolean optional = false;\r
- public ArrayList<String> variableLengthLabels;\r
- }\r
- \r
- public static class Output extends Parameter {\r
- }\r
- \r
- public enum Type {\r
- USER_DEFINED,\r
- SHARED,\r
- SYSDYN,\r
- MODELICA, \r
- MODELICA_ARRAY,\r
- VENSIM,\r
- XMILE\r
- }\r
- \r
- public Function(\r
- String name, \r
- ArrayList<Input> inputList, \r
- ArrayList<Output> outputList, \r
- Type type, \r
- String description){\r
- \r
- this.name = new String(name);\r
- \r
- this.type = type;\r
- \r
- if (inputList != null)\r
- this.inputList = inputList;\r
- else\r
- this.inputList = new ArrayList<Input>();\r
- \r
- if (outputList != null)\r
- this.outputList = outputList;\r
- else\r
- this.outputList = new ArrayList<Output>();\r
- \r
- if (description != null)\r
- this.description = new String(description);\r
- else\r
- this.description = null;\r
- }\r
- \r
- /**\r
- * Convert list of Inputs to string\r
- * @param inputList list of Inputs\r
- * @return printable form of inputs (for function declaration)\r
- */\r
- public static String inputListToString(ArrayList<Input> inputList) {\r
- String inputStr = null;\r
- for (Input p : inputList) {\r
- String pName;\r
- // Variable length parameter list\r
- if (p.variableLength) {\r
- pName = "";\r
- for (String label : p.variableLengthLabels) {\r
- pName += label + ", ";\r
- }\r
- pName += "...";\r
- } else {\r
- pName = p.name;\r
- }\r
- \r
- if (inputStr == null)\r
- inputStr = new String(pName);\r
- else\r
- inputStr += ", " + pName;\r
- }\r
- return inputStr;\r
- }\r
- \r
- public ArrayList<Input> getInputList() {\r
- return inputList;\r
- }\r
- \r
- public ArrayList<Output> getOutputList() {\r
- return outputList;\r
- }\r
- \r
- public String getName() {\r
- return name;\r
- }\r
- \r
- public Type getType() {\r
- return type;\r
- }\r
- \r
- public String getDescription() {\r
- return description;\r
- }\r
- \r
- @Override\r
- public int compareTo(Function f) {\r
- // Sorting is done first in the order of Types and then alphabetically.\r
- int typeCompare = type.compareTo(f.getType());\r
- return typeCompare != 0 ? typeCompare : name.compareTo(f.getName());\r
- }\r
- \r
- /**\r
- * Get Modelica function input parameters\r
- * @param graph\r
- * @param sr \r
- * @param r Resource of the Modelica function\r
- * @return ArrayList of Inputs\r
- * @throws DatabaseException\r
- */\r
- public static ArrayList<Input> getFunctionInputs(ReadGraph graph, SysdynResource sr, Resource r) throws DatabaseException {\r
- Resource inputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_inputs);\r
- ArrayList<Input> inputParameters = new ArrayList<Input>();\r
- if (inputs != null) {\r
- for (Resource input : ListUtils.toList(graph, inputs)) {\r
- // Convert the Resource into Parameter;\r
- Input inputParameter = new Input();\r
- inputParameter.name = NameUtils.getSafeName(graph, input);\r
- inputParameter.optional = graph.getPossibleRelatedValue(\r
- input, \r
- sr.SysdynModelicaFunction_optional, \r
- Bindings.BOOLEAN);\r
- inputParameter.unit = graph.getPossibleRelatedValue(\r
- input, \r
- sr.SysdynModelicaFunction_unit, \r
- Bindings.STRING);\r
- if (graph.isInstanceOf(input, sr.SysdynModelicaFunction_VariableLengthInput)) {\r
- inputParameter.variableLength = true;\r
- Resource shownLabels = graph.getPossibleObject(\r
- input, \r
- sr.SysdynModelicaFunction_VariableLengthInput_shownLabels);\r
- inputParameter.variableLengthLabels = new ArrayList<String>();\r
- if (shownLabels != null) {\r
- for (Resource label : ListUtils.toList(graph, shownLabels)) {\r
- inputParameter.variableLengthLabels.add(NameUtils.getSafeName(graph, label));\r
- }\r
- }\r
- }\r
- \r
- inputParameters.add(inputParameter);\r
- }\r
- }\r
- return inputParameters;\r
- }\r
- \r
- /**\r
- * Get Modelica function outputs\r
- * @param graph\r
- * @param sr \r
- * @param r Resource of the Modelica function\r
- * @return ArrayList of Outputs\r
- * @throws DatabaseException\r
- */\r
- protected static ArrayList<Output> getFunctionOutputs(ReadGraph graph,\r
- SysdynResource sr, Resource r) throws DatabaseException {\r
- Resource outputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_outputs);\r
- ArrayList<Output> outputParameters = new ArrayList<Output>(1);\r
- if (outputs != null) {\r
- for (Resource output : ListUtils.toList(graph, outputs)) {\r
- // Convert the Resource into Parameter;\r
- Output outputParameter = new Output();\r
- outputParameter.name = NameUtils.getSafeName(graph, output);\r
- outputParameter.unit = graph.getPossibleRelatedValue(\r
- output, \r
- sr.SysdynModelicaFunction_unit, \r
- Bindings.STRING);\r
- outputParameters.add(outputParameter);\r
- }\r
- }\r
- return outputParameters;\r
- }\r
-\r
- public static String getFunctionDescription(ReadGraph graph, Resource r) throws DatabaseException {\r
- String descriptionStr = null;\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource description = graph.getPossibleObject(r, l0.HasDescription);\r
- if (description != null) {\r
- descriptionStr = graph.getPossibleRelatedValue(r, l0.HasDescription, Bindings.STRING);\r
- }\r
- \r
- return descriptionStr;\r
- }\r
- \r
- private static ArrayList<Function> getFunctionsOfType(ReadGraph graph, String functionTypeUri, Type functionType) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- ArrayList<Function> functions = new ArrayList<Function>();\r
- \r
- // Add functions\r
- Resource functionLibrary = graph.getPossibleResource(functionTypeUri);\r
- for(Resource r : graph.syncRequest(new ObjectsWithType(functionLibrary, l0.ConsistsOf, sr.SysdynModelicaFunction))) {\r
- String name = NameUtils.getSafeName(graph, r);\r
- // add a XMILE prefix to xmile functions. this should probably be\r
- // done to VENSIM functions too, but a better solutions would be\r
- // to segregate the non-sysdyn non-modelica function libraries\r
- // to a separate place, be it an external function library or\r
- // something else, instead of including them everywhere by default\r
- if (functionType.equals(Type.XMILE)) {\r
- name = "XMILE." + name;\r
- }\r
- ArrayList<Input> inputs = getFunctionInputs(graph, sr, r);\r
- ArrayList<Output> outputs = getFunctionOutputs(graph, sr, r);\r
- String description = getFunctionDescription(graph, r);\r
- functions.add(new Function(name, inputs, outputs, functionType, description));\r
- }\r
- return functions;\r
- }\r
- \r
- /**\r
- * Get all built-in Modelica functions.\r
- * Should be used if called inside a transaction\r
- * @return ArrayList containing all built-in functions.\r
- */\r
- public static ArrayList<Function> getAllBuiltInFunctions(ReadGraph graph) throws DatabaseException {\r
- ArrayList<Function> functions = new ArrayList<Function>();\r
- \r
- // Add different types of functions.\r
- functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions, Type.SYSDYN));\r
- functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Vensim_Functions, Type.VENSIM));\r
- functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Modelica_Functions, Type.MODELICA));\r
- functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Modelica_Array_Functions, Type.MODELICA_ARRAY));\r
- functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Xmile_Functions, Type.XMILE));\r
- \r
- return functions;\r
- }\r
- \r
- /**\r
- * Get all built-in Modelica functions.\r
- * @return ArrayList containing all built-in functions.\r
- */\r
- public static ArrayList<Function> getAllBuiltInFunctions() {\r
- ArrayList<Function> result = null;\r
- \r
- //Finding functions\r
- try {\r
- result = SimanticsUI.getSession().syncRequest(new Read<ArrayList<Function>>() {\r
- @Override\r
- public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {\r
- return getAllBuiltInFunctions(graph);\r
- }\r
- });\r
- }\r
- catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- return result;\r
- }\r
- \r
- /**\r
- * Get all shared Modelica functions.\r
- * @param variable of which model is in question\r
- * @return ArrayList containing all shared functions.\r
- */\r
- public static ArrayList<Function> getSharedFunctions(final Resource model) {\r
- ArrayList<Function> functions = new ArrayList<Function>();\r
- if (model == null) {\r
- return functions;\r
- }\r
- \r
- try {\r
- functions = SimanticsUI.getSession().syncRequest(new Read<ArrayList<Function>>() {\r
- \r
- @Override\r
- public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- \r
- // Full names of the collected functions\r
- ArrayList<Function> sharedFunctions = new ArrayList<Function>();\r
-\r
- Collection<Resource> linkedResources = graph.getObjects(model, l0.IsLinkedTo);\r
- for (Resource r : linkedResources) {\r
- // Find the "Shared functions" library \r
- if (graph.isInstanceOf(r, sr.SharedFunctionOntology)) {\r
- // Get all function resources under the Shared Functions "folder". \r
- Collection<Resource> userFunctionResources = getFunctionsInside(graph, r);\r
- for (Resource function : userFunctionResources) {\r
- // Construct the Modelica name of the function\r
- String fullName = NameUtils.getSafeName(graph, function);\r
- Resource parent = function; // Parent is updated properly in the loop\r
- do {\r
- parent = graph.getPossibleObject(parent, l0.PartOf);\r
- fullName = NameUtils.getSafeName(graph, parent) + "." + fullName;\r
- } while (!graph.isInstanceOf(parent, l0.Ontology));\r
- \r
- // Create a Function object out of the Resource\r
- Function sharedFunction = new Function(fullName, \r
- Function.getFunctionInputs(graph, sr, function),\r
- Function.getFunctionOutputs(graph, sr, function),\r
- Type.SHARED, \r
- Function.getFunctionDescription(graph, function));\r
- sharedFunctions.add(sharedFunction);\r
- }\r
- }\r
- }\r
- return sharedFunctions;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return functions;\r
- }\r
- \r
- /**\r
- * Get all user defined Modelica functions.\r
- * @param variable of which model is in question\r
- * @return ArrayList containing all user defined functions.\r
- */\r
- public static ArrayList<Function> getUserDefinedFunctions(final Resource model) {\r
- ArrayList<Function> functions = new ArrayList<Function>();\r
- if (model == null) {\r
- return functions;\r
- }\r
- \r
- try {\r
- functions = SimanticsUI.getSession().syncRequest(new Read<ArrayList<Function>>() {\r
- \r
- @Override\r
- public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- // Full names of the collected functions\r
- ArrayList<Function> userFunctions = new ArrayList<Function>();\r
- \r
- // Get all function resources under model recursively\r
- Collection<Resource> userFunctionResources = getFunctionsInside(graph, model);\r
- for (Resource function : userFunctionResources) {\r
- // Construct the Modelica name of the function\r
- String fullName = NameUtils.getSafeName(graph, function);\r
- Resource parent = graph.getPossibleObject(function, l0.PartOf);\r
- while (!graph.isInstanceOf(parent, sr.SysdynModel)) {\r
- fullName = NameUtils.getSafeName(graph, parent) + "." + fullName;\r
- parent = graph.getPossibleObject(parent, l0.PartOf);\r
- }\r
- \r
- // Create a Function object out of the Resource\r
- Function userFunction = new Function(fullName, \r
- Function.getFunctionInputs(graph, sr, function),\r
- Function.getFunctionOutputs(graph, sr, function),\r
- Type.USER_DEFINED, \r
- Function.getFunctionDescription(graph, function));\r
- userFunctions.add(userFunction);\r
- }\r
- \r
- return userFunctions;\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return functions;\r
- }\r
- \r
- /**\r
- * Get functions inside a resource\r
- * @param graph\r
- * @param r Recource in which functions are sought\r
- * @return found function Resources\r
- * @throws DatabaseException\r
- */\r
- public static Collection<Resource> getFunctionsInside(ReadGraph graph, Resource r) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- ArrayList<Resource> functions = new ArrayList<Resource>();\r
- functions.addAll(graph.syncRequest(new ObjectsWithType(\r
- r, \r
- l0.ConsistsOf, \r
- sr.SysdynModelicaFunction)));\r
- Collection<Resource> functionLibraries;\r
- functionLibraries = graph.syncRequest(new ObjectsWithType(\r
- r, \r
- l0.ConsistsOf,\r
- sr.SysdynModelicaFunctionLibrary));\r
- for (Resource library : functionLibraries) {\r
- functions.addAll(getFunctionsInside(graph, library));\r
- }\r
- return functions;\r
- }\r
- \r
- /**\r
- * Converts the description string to HTML-format\r
- * @return HMTL-formatted description.\r
- */\r
- public String getDescriptionHTML() {\r
- if (description == null)\r
- return null;\r
- return description.replaceAll("<", "<").replaceAll(">", ">").replaceAll("\n", "<BR>");\r
- }\r
-\r
- /**\r
- * Determine if the units of the given arguments are valid\r
- * @param argumentUnits validated arguments\r
- * @param correspondences mapping from templates to actual arguments\r
- * @param functions all functions available\r
- * @param allowEquivalents true iff equivalent units are used (e.g. $ == dollar)\r
- * @param units evm\r
- * @return true iff argument units are valid\r
- * @throws UnitCheckingException if \r
- */\r
- public boolean areArgumentUnitsValid(ArrayList<Pair<UnitResult, String>> argumentUnits, \r
- HashMap<String, String> correspondences,\r
- ArrayList<Function> functions, \r
- boolean allowEquivalents, \r
- HashMap<String, \r
- String> units) throws UnitCheckingException {\r
- ArrayList<Boolean> inputMatches = new ArrayList<Boolean>(); // Table for matching inputs.\r
- for (int i = 0; i < inputList.size(); ++i)\r
- inputMatches.add(Boolean.FALSE);\r
- \r
- for (int i = 0; i < argumentUnits.size(); ++i) { // Go through all _arguments_\r
- if (inputList.size() == 0)\r
- return false; // No inputs expected but got at least one\r
- \r
- if (argumentUnits.get(i).second != null) { // Named argument\r
- boolean found = false;\r
- for (int j = 0; j < inputList.size(); ++j) {\r
- Input namedInput = inputList.get(j);\r
- if (namedInput.name.equals(argumentUnits.get(i).second)) {\r
- // Match input unit to argument unit\r
- UnitResult inputUnit = namedInput.getUnitResult(units, this, functions, allowEquivalents, correspondences);\r
- if (!inputUnit.equals(argumentUnits.get(i).first))\r
- return false;\r
- inputMatches.set(j, Boolean.TRUE);\r
- found = true;\r
- break;\r
- }\r
- }\r
- if (!found) {\r
- throw new UnitCheckingException("Undefined input argument " + argumentUnits.get(i).second \r
- + " used in function " + this.getName() + ".");\r
- }\r
- } else { // Position argument\r
- if (i >= inputList.size()) { // Test for variable length argument\r
- // Assume there can be only one variable length input and its in the end.\r
- // And that there cannot be any optional arguments before.\r
- Input input = inputList.get(inputList.size() - 1);\r
- if (input.variableLength) {\r
- // Match input unit to argument unit\r
- UnitResult inputUnit = input.getUnitResult(units, this, functions, allowEquivalents, correspondences);\r
- if (!inputUnit.equals(argumentUnits.get(i).first))\r
- return false;\r
- // The corresponding _input_ has already been gone through, no need to set true.\r
- } else {\r
- return false;\r
- }\r
- } else {\r
- // Match input unit to argument unit\r
- UnitResult inputUnit = inputList.get(i).getUnitResult(units, this, functions, allowEquivalents, correspondences);\r
- if (inputUnit.getUnitType() == UnitType.SCALAR\r
- && !(argumentUnits.get(i).first.getUnitType() == UnitType.SCALAR))\r
- return false; // Here we don't accept a "1" replaced with a NORMAL expression, there's "ANY" for that.\r
- if (!inputUnit.equals(argumentUnits.get(i).first))\r
- return false;\r
- inputMatches.set(i, Boolean.TRUE);\r
- }\r
- }\r
- }\r
- \r
- // See if some of the required inputs has not been defined. \r
- for (int i = 0; i < inputList.size(); ++i) {\r
- if (!inputMatches.get(i) && !inputList.get(i).optional) {\r
- return false;\r
- }\r
- }\r
- \r
- return true;\r
- }\r
-}\r
+package org.simantics.sysdyn.utils;
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+
+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.utils.ListUtils;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.unitParser.ParseException;
+import org.simantics.sysdyn.unitParser.UnitCheckingException;
+import org.simantics.sysdyn.unitParser.UnitCheckingNode;
+import org.simantics.sysdyn.unitParser.UnitParser;
+import org.simantics.sysdyn.unitParser.nodes.UnitResult;
+import org.simantics.sysdyn.unitParser.nodes.UnitResult.UnitType;
+import org.simantics.utils.datastructures.Pair;
+
+
+/**
+ * Class to store function name, type, and parameters.
+ *
+ * @author Tuomas Miettinen
+ *
+ */
+public class Function implements Comparable<Function>{
+
+ private final String name;
+ private final Type type;
+ private final ArrayList<Input> inputList;
+ private final ArrayList<Output> outputList;
+ private final String description;
+
+ public static class Parameter {
+ public static final String ANY = "ANY";
+ public static final String TIME = "TIME";
+ public String name;
+ public String unit = ANY;
+
+ public UnitResult getUnitResult(
+ HashMap<String, String> units,
+ Function f,
+ ArrayList<Function> functions,
+ boolean allowEquivalents,
+ HashMap<String, String> correspondences) throws UnitCheckingException {
+
+ UnitResult result = new UnitResult(allowEquivalents);
+ if (Parameter.ANY.equals(this.unit)) {
+ result.setUnitType(UnitType.ANY);
+ } else if ("1".equals(this.unit)) { // TODO: see if this should be changed to something else
+ result.setUnitType(UnitType.SCALAR);
+ } else {
+ // Replace TIME with actual time unit.
+ String timeUnit = units.get("time");
+ String timeReplaced = this.unit.replace(Parameter.TIME, timeUnit);
+
+ // Replace 'p, 'q, etc. in output with units from actual inputs.
+ String correspondencesReplaced = replaceCorrespondences(f, timeReplaced, correspondences);
+
+ try {
+ StringReader outputReader = new StringReader(correspondencesReplaced);
+ UnitParser outputParser = new UnitParser(outputReader);
+ UnitCheckingNode output;
+ output = (UnitCheckingNode) outputParser.expr();
+ outputReader.close();
+ result.appendResult(output.getUnits(null, functions, allowEquivalents));
+ } catch (UnitCheckingException e) {
+ e.printStackTrace();
+ } catch (ParseException e) {
+ throw new UnitCheckingException("Cannot validate units: Syntax error in expression.");
+ }
+ }
+
+ return result;
+ }
+
+ private static String replaceCorrespondences(Function f, String original,
+ HashMap<String, String> correspondences) throws UnitCheckingException {
+ int index;
+ String ret = new String(original);
+ // Go through the unit as long as there are part of form 'p, 'q, etc. and replace them.
+ while ((index = ret.indexOf('\'')) >= 0) {
+ String replaced = ret.substring(index, index + 2); // The replaced units are always of length 2.
+ try {
+ ret = ret.replace(replaced, "(" + correspondences.get(replaced) + ")");
+ } catch (NullPointerException npe) {
+ throw new UnitCheckingException("Function " + f.getName() + " output unit could not be determined. Replacement unit "
+ + replaced + " not found in input unit definitions.");
+ }
+ }
+ return ret;
+ }
+ }
+
+ public static class Input extends Parameter {
+ public boolean variableLength = false;
+ public boolean optional = false;
+ public ArrayList<String> variableLengthLabels;
+ }
+
+ public static class Output extends Parameter {
+ }
+
+ public enum Type {
+ USER_DEFINED,
+ SHARED,
+ SYSDYN,
+ MODELICA,
+ MODELICA_ARRAY,
+ VENSIM,
+ XMILE
+ }
+
+ public Function(
+ String name,
+ ArrayList<Input> inputList,
+ ArrayList<Output> outputList,
+ Type type,
+ String description){
+
+ this.name = new String(name);
+
+ this.type = type;
+
+ if (inputList != null)
+ this.inputList = inputList;
+ else
+ this.inputList = new ArrayList<Input>();
+
+ if (outputList != null)
+ this.outputList = outputList;
+ else
+ this.outputList = new ArrayList<Output>();
+
+ if (description != null)
+ this.description = new String(description);
+ else
+ this.description = null;
+ }
+
+ /**
+ * Convert list of Inputs to string
+ * @param inputList list of Inputs
+ * @return printable form of inputs (for function declaration)
+ */
+ public static String inputListToString(ArrayList<Input> inputList) {
+ String inputStr = null;
+ for (Input p : inputList) {
+ String pName;
+ // Variable length parameter list
+ if (p.variableLength) {
+ pName = "";
+ for (String label : p.variableLengthLabels) {
+ pName += label + ", ";
+ }
+ pName += "...";
+ } else {
+ pName = p.name;
+ }
+
+ if (inputStr == null)
+ inputStr = new String(pName);
+ else
+ inputStr += ", " + pName;
+ }
+ return inputStr;
+ }
+
+ public ArrayList<Input> getInputList() {
+ return inputList;
+ }
+
+ public ArrayList<Output> getOutputList() {
+ return outputList;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Type getType() {
+ return type;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public int compareTo(Function f) {
+ // Sorting is done first in the order of Types and then alphabetically.
+ int typeCompare = type.compareTo(f.getType());
+ return typeCompare != 0 ? typeCompare : name.compareTo(f.getName());
+ }
+
+ /**
+ * Get Modelica function input parameters
+ * @param graph
+ * @param sr
+ * @param r Resource of the Modelica function
+ * @return ArrayList of Inputs
+ * @throws DatabaseException
+ */
+ public static ArrayList<Input> getFunctionInputs(ReadGraph graph, SysdynResource sr, Resource r) throws DatabaseException {
+ Resource inputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_inputs);
+ ArrayList<Input> inputParameters = new ArrayList<Input>();
+ if (inputs != null) {
+ for (Resource input : ListUtils.toList(graph, inputs)) {
+ // Convert the Resource into Parameter;
+ Input inputParameter = new Input();
+ inputParameter.name = NameUtils.getSafeName(graph, input);
+ inputParameter.optional = graph.getPossibleRelatedValue(
+ input,
+ sr.SysdynModelicaFunction_optional,
+ Bindings.BOOLEAN);
+ inputParameter.unit = graph.getPossibleRelatedValue(
+ input,
+ sr.SysdynModelicaFunction_unit,
+ Bindings.STRING);
+ if (graph.isInstanceOf(input, sr.SysdynModelicaFunction_VariableLengthInput)) {
+ inputParameter.variableLength = true;
+ Resource shownLabels = graph.getPossibleObject(
+ input,
+ sr.SysdynModelicaFunction_VariableLengthInput_shownLabels);
+ inputParameter.variableLengthLabels = new ArrayList<String>();
+ if (shownLabels != null) {
+ for (Resource label : ListUtils.toList(graph, shownLabels)) {
+ inputParameter.variableLengthLabels.add(NameUtils.getSafeName(graph, label));
+ }
+ }
+ }
+
+ inputParameters.add(inputParameter);
+ }
+ }
+ return inputParameters;
+ }
+
+ /**
+ * Get Modelica function outputs
+ * @param graph
+ * @param sr
+ * @param r Resource of the Modelica function
+ * @return ArrayList of Outputs
+ * @throws DatabaseException
+ */
+ protected static ArrayList<Output> getFunctionOutputs(ReadGraph graph,
+ SysdynResource sr, Resource r) throws DatabaseException {
+ Resource outputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_outputs);
+ ArrayList<Output> outputParameters = new ArrayList<Output>(1);
+ if (outputs != null) {
+ for (Resource output : ListUtils.toList(graph, outputs)) {
+ // Convert the Resource into Parameter;
+ Output outputParameter = new Output();
+ outputParameter.name = NameUtils.getSafeName(graph, output);
+ outputParameter.unit = graph.getPossibleRelatedValue(
+ output,
+ sr.SysdynModelicaFunction_unit,
+ Bindings.STRING);
+ outputParameters.add(outputParameter);
+ }
+ }
+ return outputParameters;
+ }
+
+ public static String getFunctionDescription(ReadGraph graph, Resource r) throws DatabaseException {
+ String descriptionStr = null;
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource description = graph.getPossibleObject(r, l0.HasDescription);
+ if (description != null) {
+ descriptionStr = graph.getPossibleRelatedValue(r, l0.HasDescription, Bindings.STRING);
+ }
+
+ return descriptionStr;
+ }
+
+ private static ArrayList<Function> getFunctionsOfType(ReadGraph graph, String functionTypeUri, Type functionType) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+ ArrayList<Function> functions = new ArrayList<Function>();
+
+ // Add functions
+ Resource functionLibrary = graph.getPossibleResource(functionTypeUri);
+ for(Resource r : graph.syncRequest(new ObjectsWithType(functionLibrary, l0.ConsistsOf, sr.SysdynModelicaFunction))) {
+ String name = NameUtils.getSafeName(graph, r);
+ // add a XMILE prefix to xmile functions. this should probably be
+ // done to VENSIM functions too, but a better solutions would be
+ // to segregate the non-sysdyn non-modelica function libraries
+ // to a separate place, be it an external function library or
+ // something else, instead of including them everywhere by default
+ if (functionType.equals(Type.XMILE)) {
+ name = "XMILE." + name;
+ }
+ ArrayList<Input> inputs = getFunctionInputs(graph, sr, r);
+ ArrayList<Output> outputs = getFunctionOutputs(graph, sr, r);
+ String description = getFunctionDescription(graph, r);
+ functions.add(new Function(name, inputs, outputs, functionType, description));
+ }
+ return functions;
+ }
+
+ /**
+ * Get all built-in Modelica functions.
+ * Should be used if called inside a transaction
+ * @return ArrayList containing all built-in functions.
+ */
+ public static ArrayList<Function> getAllBuiltInFunctions(ReadGraph graph) throws DatabaseException {
+ ArrayList<Function> functions = new ArrayList<Function>();
+
+ // Add different types of functions.
+ functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions, Type.SYSDYN));
+ functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Vensim_Functions, Type.VENSIM));
+ functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Modelica_Functions, Type.MODELICA));
+ functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Modelica_Array_Functions, Type.MODELICA_ARRAY));
+ functions.addAll(getFunctionsOfType(graph, SysdynResource.URIs.Built$in_Functions_Xmile_Functions, Type.XMILE));
+
+ return functions;
+ }
+
+ /**
+ * Get all built-in Modelica functions.
+ * @return ArrayList containing all built-in functions.
+ */
+ public static ArrayList<Function> getAllBuiltInFunctions() {
+ ArrayList<Function> result = null;
+
+ //Finding functions
+ try {
+ result = Simantics.getSession().syncRequest(new Read<ArrayList<Function>>() {
+ @Override
+ public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {
+ return getAllBuiltInFunctions(graph);
+ }
+ });
+ }
+ catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ return result;
+ }
+
+ /**
+ * Get all shared Modelica functions.
+ * @param variable of which model is in question
+ * @return ArrayList containing all shared functions.
+ */
+ public static ArrayList<Function> getSharedFunctions(final Resource model) {
+ ArrayList<Function> functions = new ArrayList<Function>();
+ if (model == null) {
+ return functions;
+ }
+
+ try {
+ functions = Simantics.getSession().syncRequest(new Read<ArrayList<Function>>() {
+
+ @Override
+ public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ // Full names of the collected functions
+ ArrayList<Function> sharedFunctions = new ArrayList<Function>();
+
+ Collection<Resource> linkedResources = graph.getObjects(model, l0.IsLinkedTo);
+ for (Resource r : linkedResources) {
+ // Find the "Shared functions" library
+ if (graph.isInstanceOf(r, sr.SharedFunctionOntology)) {
+ // Get all function resources under the Shared Functions "folder".
+ Collection<Resource> userFunctionResources = getFunctionsInside(graph, r);
+ for (Resource function : userFunctionResources) {
+ // Construct the Modelica name of the function
+ String fullName = NameUtils.getSafeName(graph, function);
+ Resource parent = function; // Parent is updated properly in the loop
+ do {
+ parent = graph.getPossibleObject(parent, l0.PartOf);
+ fullName = NameUtils.getSafeName(graph, parent) + "." + fullName;
+ } while (!graph.isInstanceOf(parent, l0.Ontology));
+
+ // Create a Function object out of the Resource
+ Function sharedFunction = new Function(fullName,
+ Function.getFunctionInputs(graph, sr, function),
+ Function.getFunctionOutputs(graph, sr, function),
+ Type.SHARED,
+ Function.getFunctionDescription(graph, function));
+ sharedFunctions.add(sharedFunction);
+ }
+ }
+ }
+ return sharedFunctions;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return functions;
+ }
+
+ /**
+ * Get all user defined Modelica functions.
+ * @param variable of which model is in question
+ * @return ArrayList containing all user defined functions.
+ */
+ public static ArrayList<Function> getUserDefinedFunctions(final Resource model) {
+ ArrayList<Function> functions = new ArrayList<Function>();
+ if (model == null) {
+ return functions;
+ }
+
+ try {
+ functions = Simantics.getSession().syncRequest(new Read<ArrayList<Function>>() {
+
+ @Override
+ public ArrayList<Function> perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ // Full names of the collected functions
+ ArrayList<Function> userFunctions = new ArrayList<Function>();
+
+ // Get all function resources under model recursively
+ Collection<Resource> userFunctionResources = getFunctionsInside(graph, model);
+ for (Resource function : userFunctionResources) {
+ // Construct the Modelica name of the function
+ String fullName = NameUtils.getSafeName(graph, function);
+ Resource parent = graph.getPossibleObject(function, l0.PartOf);
+ while (!graph.isInstanceOf(parent, sr.SysdynModel)) {
+ fullName = NameUtils.getSafeName(graph, parent) + "." + fullName;
+ parent = graph.getPossibleObject(parent, l0.PartOf);
+ }
+
+ // Create a Function object out of the Resource
+ Function userFunction = new Function(fullName,
+ Function.getFunctionInputs(graph, sr, function),
+ Function.getFunctionOutputs(graph, sr, function),
+ Type.USER_DEFINED,
+ Function.getFunctionDescription(graph, function));
+ userFunctions.add(userFunction);
+ }
+
+ return userFunctions;
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return functions;
+ }
+
+ /**
+ * Get functions inside a resource
+ * @param graph
+ * @param r Recource in which functions are sought
+ * @return found function Resources
+ * @throws DatabaseException
+ */
+ public static Collection<Resource> getFunctionsInside(ReadGraph graph, Resource r) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ ArrayList<Resource> functions = new ArrayList<Resource>();
+ functions.addAll(graph.syncRequest(new ObjectsWithType(
+ r,
+ l0.ConsistsOf,
+ sr.SysdynModelicaFunction)));
+ Collection<Resource> functionLibraries;
+ functionLibraries = graph.syncRequest(new ObjectsWithType(
+ r,
+ l0.ConsistsOf,
+ sr.SysdynModelicaFunctionLibrary));
+ for (Resource library : functionLibraries) {
+ functions.addAll(getFunctionsInside(graph, library));
+ }
+ return functions;
+ }
+
+ /**
+ * Converts the description string to HTML-format
+ * @return HMTL-formatted description.
+ */
+ public String getDescriptionHTML() {
+ if (description == null)
+ return null;
+ return description.replaceAll("<", "<").replaceAll(">", ">").replaceAll("\n", "<BR>");
+ }
+
+ /**
+ * Determine if the units of the given arguments are valid
+ * @param argumentUnits validated arguments
+ * @param correspondences mapping from templates to actual arguments
+ * @param functions all functions available
+ * @param allowEquivalents true iff equivalent units are used (e.g. $ == dollar)
+ * @param units evm
+ * @return true iff argument units are valid
+ * @throws UnitCheckingException if
+ */
+ public boolean areArgumentUnitsValid(ArrayList<Pair<UnitResult, String>> argumentUnits,
+ HashMap<String, String> correspondences,
+ ArrayList<Function> functions,
+ boolean allowEquivalents,
+ HashMap<String,
+ String> units) throws UnitCheckingException {
+ ArrayList<Boolean> inputMatches = new ArrayList<Boolean>(); // Table for matching inputs.
+ for (int i = 0; i < inputList.size(); ++i)
+ inputMatches.add(Boolean.FALSE);
+
+ for (int i = 0; i < argumentUnits.size(); ++i) { // Go through all _arguments_
+ if (inputList.size() == 0)
+ return false; // No inputs expected but got at least one
+
+ if (argumentUnits.get(i).second != null) { // Named argument
+ boolean found = false;
+ for (int j = 0; j < inputList.size(); ++j) {
+ Input namedInput = inputList.get(j);
+ if (namedInput.name.equals(argumentUnits.get(i).second)) {
+ // Match input unit to argument unit
+ UnitResult inputUnit = namedInput.getUnitResult(units, this, functions, allowEquivalents, correspondences);
+ if (!inputUnit.equals(argumentUnits.get(i).first))
+ return false;
+ inputMatches.set(j, Boolean.TRUE);
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ throw new UnitCheckingException("Undefined input argument " + argumentUnits.get(i).second
+ + " used in function " + this.getName() + ".");
+ }
+ } else { // Position argument
+ if (i >= inputList.size()) { // Test for variable length argument
+ // Assume there can be only one variable length input and its in the end.
+ // And that there cannot be any optional arguments before.
+ Input input = inputList.get(inputList.size() - 1);
+ if (input.variableLength) {
+ // Match input unit to argument unit
+ UnitResult inputUnit = input.getUnitResult(units, this, functions, allowEquivalents, correspondences);
+ if (!inputUnit.equals(argumentUnits.get(i).first))
+ return false;
+ // The corresponding _input_ has already been gone through, no need to set true.
+ } else {
+ return false;
+ }
+ } else {
+ // Match input unit to argument unit
+ UnitResult inputUnit = inputList.get(i).getUnitResult(units, this, functions, allowEquivalents, correspondences);
+ if (inputUnit.getUnitType() == UnitType.SCALAR
+ && !(argumentUnits.get(i).first.getUnitType() == UnitType.SCALAR))
+ return false; // Here we don't accept a "1" replaced with a NORMAL expression, there's "ANY" for that.
+ if (!inputUnit.equals(argumentUnits.get(i).first))
+ return false;
+ inputMatches.set(i, Boolean.TRUE);
+ }
+ }
+ }
+
+ // See if some of the required inputs has not been defined.
+ for (int i = 0; i < inputList.size(); ++i) {
+ if (!inputMatches.get(i) && !inputList.get(i).optional) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.utils;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.NoSingleResultException;\r
-import org.simantics.db.exception.ServiceException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.elementaryCycles.ElementaryCyclesSearch;\r
-import org.simantics.ui.SimanticsUI;\r
-\r
-/**\r
- * Utils for loops\r
- * @author Tuomas Miettinen\r
- *\r
- */\r
-public class LoopUtils {\r
-\r
- private static class ElementaryLoopItem {\r
- public int mapping;\r
- ArrayList<Resource> dependencies;\r
- \r
- public ElementaryLoopItem(int mapping, ArrayList<Resource> dependencies) {\r
- this.mapping = mapping;\r
- this.dependencies = dependencies;\r
- }\r
- }\r
- \r
- public enum LoopType {\r
- REINFORCING,\r
- BALANCING,\r
- UNDEFINED\r
- };\r
- \r
- /**\r
- * Get all the loops within the diagram where the resource belongs to.\r
- * @param r Resource that is studied\r
- * @return List of loops; each loop is a list of resources in the same order in which\r
- * they appear in the loop. The first item in the list can be any of the items in the\r
- * loop. \r
- */\r
- public static List<List<Resource>> getLoops(final Resource r) {\r
- List<List<Resource>> loops = Collections.emptyList();\r
- try {\r
- loops = SimanticsUI.getSession().syncRequest(new Read<List<List<Resource>>>() {\r
-\r
- @Override\r
- public List<List<Resource>> perform(ReadGraph graph)\r
- throws DatabaseException {\r
- return getLoops(graph, r);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- return loops;\r
- }\r
- \r
- @SuppressWarnings({ "rawtypes", "unchecked", "unused" })\r
- public static List<List<Resource>> getLoops(ReadGraph g, Resource r) throws DatabaseException, ServiceException {\r
- // Get all loops in the diagram.\r
- List<List<Resource>> cycles = getAllLoopsInDiagram(g, r);\r
- \r
- // Collect all those loops in which the original resource exists.\r
- List<List<Resource>> loops = new ArrayList<List<Resource>>();\r
- for (Object o : cycles) {\r
- if (o instanceof List) {\r
- List loop = (List)o;\r
- if (loop.contains(r))\r
- loops.add(loop);\r
- }\r
- }\r
- \r
- // Debug print the result\r
- if (false) {\r
- System.out.println(cyclesToString(g, cycles));\r
- }\r
- \r
- return loops;\r
- }\r
- \r
- @SuppressWarnings({ "rawtypes", "unchecked" })\r
- public static List<List<Resource>> getAllLoopsInDiagram(ReadGraph g, Resource r) throws DatabaseException, ServiceException {\r
- Layer0 l0 = Layer0.getInstance(g);\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- Resource configuration = g.getPossibleObject(r, l0.PartOf);\r
- if (configuration == null)\r
- return Collections.emptyList();\r
- \r
- Collection<Resource> variables = g.getObjects(configuration, l0.ConsistsOf);\r
- ArrayList<Resource> shadows = new ArrayList<Resource>();\r
- \r
- // Leave only independent variables and shadows (and modules)\r
- Iterator<Resource> it = variables.iterator();\r
- while (it.hasNext()) {\r
- Resource v = it.next();\r
- if (g.isInstanceOf(v, sr.IndependentVariable)) {\r
- } else if (g.isInstanceOf(v, sr.Shadow)) {\r
- shadows.add(v);\r
- it.remove();\r
- /*} else if (|| g.isInstanceOf(v, sr.Module)) {\r
- */\r
- } else {\r
- it.remove();\r
- }\r
- }\r
- \r
- int variableCount = variables.size();\r
- Resource nodes[] = new Resource[variableCount];\r
- \r
- // Add independent variables to map and array\r
- int k = 0;\r
- HashMap<Resource, ElementaryLoopItem> elementaryLoopItems = new HashMap<Resource, ElementaryLoopItem>();\r
- for (Resource variable : variables) {\r
- ArrayList<Resource> dependingVariables = new ArrayList<Resource>();\r
- // Add forward dependencies and flows from valves.\r
- Collection<Resource> dependencies = g.getObjects(variable, sr.Variable_isTailOf);\r
- for (Resource dependency : dependencies) {\r
- Resource head = g.getPossibleObject(dependency, sr.Variable_HasHead);\r
- // Skip dependencies and flows to modules and clouds.\r
- if (head == null \r
- || g.isInstanceOf(head, sr.Module)\r
- || g.isInstanceOf(head, sr.Cloud))\r
- continue;\r
- \r
- if ((g.isInstanceOf(dependency, sr.Flow) && g.isInstanceOf(variable, sr.Valve))\r
- || g.isInstanceOf(dependency, sr.Dependency)) {\r
- // Add all dependencies\r
- // Add (only) such flows that start from a valve.\r
- dependingVariables.add(head);\r
- }\r
- }\r
- // Add backward flows from stocks.\r
- Collection<Resource> backwardFlows = g.getObjects(variable, sr.Variable_isHeadOf);\r
- for (Resource flow : backwardFlows) {\r
- if (g.isInstanceOf(flow, sr.Flow)) {\r
- Resource tail = g.getPossibleObject(flow, sr.Variable_HasTail);\r
- if (tail != null && g.isInstanceOf(tail, sr.Stock)) {\r
- // Add (only) such flows that start from a stock.\r
- dependingVariables.add(tail);\r
- }\r
- }\r
- }\r
- // Put the variable in the hash map.\r
- elementaryLoopItems.put(variable, new ElementaryLoopItem(k, dependingVariables));\r
- nodes[k++] = variable;\r
- }\r
- \r
- // Add dependencies of shadow variables for their original variables\r
- for (Resource shadow : shadows) {\r
- Resource original = g.getPossibleObject(shadow, sr.Shadow_original);\r
- ArrayList<Resource> dependingVariables = new ArrayList<Resource>();\r
- Collection<Resource> dependencies = g.getObjects(shadow, sr.Variable_isTailOf);\r
- for (Resource dependency : dependencies) {\r
- Resource head = g.getPossibleObject(dependency, sr.Variable_HasHead);\r
- if (!g.isInstanceOf(head, sr.Module)) {\r
- dependingVariables.add(head);\r
- }\r
- }\r
- ElementaryLoopItem el = elementaryLoopItems.get(original);\r
- if (el != null)\r
- el.dependencies.addAll(dependingVariables);\r
- }\r
- \r
- // Fill the adjacent matrix\r
- boolean adjMatrix[][] = new boolean[variableCount][variableCount];\r
- for (int j = 0; j < nodes.length; ++j) {\r
- ArrayList<Resource> dependingVariables = elementaryLoopItems.get(nodes[j]).dependencies;\r
- for (Resource v : dependingVariables) {\r
- adjMatrix[j][elementaryLoopItems.get(v).mapping] = true;\r
- }\r
- }\r
- \r
- // Get ALL nodes in the diagram.\r
- ElementaryCyclesSearch ecs = new ElementaryCyclesSearch(adjMatrix, nodes);\r
- List cycles = ecs.getElementaryCycles();\r
- \r
- return cycles;\r
- }\r
- \r
- /**\r
- * Get the String representation of cycles. \r
- * @param g\r
- * @param cycles List of Resource Lists of which names are returned.\r
- * @return the String representation of cycles\r
- * @throws DatabaseException\r
- */\r
- public static String cyclesToString(ReadGraph g, List<List<Resource>> cycles) throws DatabaseException {\r
- StringBuilder sb = new StringBuilder("");\r
- for (int i = 0; i < cycles.size(); i++) {\r
- sb.append(cycleToString(g, cycles.get(i)));\r
- sb.append("\n");\r
- }\r
- return sb.toString();\r
- }\r
- \r
- /**\r
- * Get the String representation of a cycle. \r
- * @param g\r
- * @param cycle List of Resources of which names are returned.\r
- * @return the String representation of a cycle\r
- * @throws DatabaseException\r
- */\r
- public static String cycleToString(ReadGraph g, List<Resource> cycle) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(g);\r
- StringBuilder sb = new StringBuilder("");\r
- for (int j = 0; j < cycle.size(); j++) {\r
- Resource node = (Resource) cycle.get(j);\r
- if (j < cycle.size() - 1) {\r
- sb.append(g.getPossibleRelatedValue(node, l0.HasName, Bindings.STRING) + " -> ");\r
- } else {\r
- sb.append(g.<String>getPossibleRelatedValue(node, l0.HasName, Bindings.STRING));\r
- }\r
- }\r
- return sb.toString();\r
- }\r
- \r
- /**\r
- * Get the type of the loop, i.e. whether the loop is reinforcing or balancing.\r
- * The type is determined based on the dependency arrows and flows on the diagram;\r
- * the loop is balancing if there is odd number of dependencies with negative\r
- * polarity (Polarity = "-"). Note:\r
- * 1) each flow of which tail is a valve is considered a dependency with positive \r
- * (+) polarity.\r
- * 2) each flow of which tail is a stock is considered a dependency with negative \r
- * (-) polarity which GOES TO THE OPPOSITE DIRECTION.\r
- * 3) the polarity of a supplementary dependency arrow overrides a flow.\r
- * 4) the loops are defined as a list of Resources. If the set of dependencies\r
- * between is ambiguous, the implementation may choose any possible dependency. \r
- * 5) empty and null polarity are considered positive (+) polarities. \r
- * @param graph\r
- * @param resource The loop component\r
- * @return the type of the loop. If the type cannot be determined,\r
- * LoopType.UNDEFINED is returned\r
- * @throws DatabaseException\r
- */\r
- public static LoopType getLoopType(ReadGraph graph, Resource resource) throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph); \r
- ModelingResources mod = ModelingResources.getInstance(graph);\r
- Resource loopResource = graph.getPossibleObject(resource, sr.Loop_Items);\r
- \r
- if (loopResource == null)\r
- return LoopType.UNDEFINED;\r
-\r
- boolean oddNumberOfNegativeCausalities = false;\r
- List<Resource> loop = ListUtils.toPossibleList(graph, loopResource);\r
- for (int i = 0; i < loop.size(); ++i) {\r
- boolean skipBackwardFlows = false;\r
- \r
- // Go through forward dependencies and flows\r
- Collection<Resource> forwardDependencies = graph.getObjects(loop.get(i), sr.Variable_isTailOf);\r
- \r
- // And also through the forward dependencies of possible shadows.\r
- Collection<Resource> shadows = graph.getObjects(loop.get(i), sr.Shadow_original_Inverse);\r
- for (Resource shadow : shadows)\r
- forwardDependencies.addAll(graph.getObjects(shadow, sr.Variable_isTailOf));\r
- \r
- for (Resource dependency : forwardDependencies) {\r
- Resource dependingVariable = graph.getSingleObject(dependency, sr.Variable_HasHead);\r
- if (dependingVariable.equals(loop.get((i + 1) % loop.size()))) {\r
- if (graph.isInstanceOf(dependency, sr.Flow)) {\r
- /*\r
- * Forward flows never affect the loop type. Allow dependency arrows \r
- * override flows; thus don't touch skipBackwardFlows and continue.\r
- * continue also because we may have a flow from stock, which\r
- * is the wrong dependency and we need to keep searching.\r
- */\r
- continue;\r
- }\r
- skipBackwardFlows = true;\r
- \r
- Resource dependencyConnection;\r
- try {\r
- dependencyConnection = graph.getSingleObject(dependency, mod.ConnectionToDiagramConnection);\r
- } catch (NoSingleResultException e) {\r
- return LoopType.UNDEFINED;\r
- }\r
- String polarity = (String)graph.getPossibleRelatedValue(dependencyConnection, sr.DependencyConnection_polarity, Bindings.STRING);\r
- if ("-".equals(polarity)) {\r
- oddNumberOfNegativeCausalities = !oddNumberOfNegativeCausalities;\r
- } else if (polarity != null \r
- && !"".equals(polarity)\r
- && !"+".equals(polarity)) {\r
- // There's something other than + in one of the dependencies\r
- return LoopType.UNDEFINED;\r
- }\r
- // "+" doesn't affect loop type, consider null and "" as a "+".\r
- break;\r
- }\r
- }\r
- \r
- if (skipBackwardFlows)\r
- continue;\r
- \r
- // Backward flows from stocks.\r
- Collection<Resource> backwardFlows = graph.getObjects(loop.get(i), sr.Variable_isHeadOf);\r
- for (Resource flow : backwardFlows) {\r
- if (graph.isInstanceOf(flow, sr.Flow)) {\r
- Resource dependingVariable = graph.getSingleObject(flow, sr.Variable_HasTail);\r
- if (dependingVariable.equals(loop.get((i + 1) % loop.size()))) {\r
- if (graph.isInstanceOf(dependingVariable, sr.Stock)) {\r
- // Basically, we should always end up here since all other\r
- // possibilities have already been gone through.\r
- oddNumberOfNegativeCausalities = !oddNumberOfNegativeCausalities;\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- }\r
- return oddNumberOfNegativeCausalities ? LoopType.BALANCING : LoopType.REINFORCING;\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2014 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.sysdyn.utils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+import org.simantics.Simantics;
+import org.simantics.databoard.Bindings;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.utils.ListUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.NoSingleResultException;
+import org.simantics.db.exception.ServiceException;
+import org.simantics.db.request.Read;
+import org.simantics.layer0.Layer0;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.elementaryCycles.ElementaryCyclesSearch;
+
+/**
+ * Utils for loops
+ * @author Tuomas Miettinen
+ *
+ */
+public class LoopUtils {
+
+ private static class ElementaryLoopItem {
+ public int mapping;
+ ArrayList<Resource> dependencies;
+
+ public ElementaryLoopItem(int mapping, ArrayList<Resource> dependencies) {
+ this.mapping = mapping;
+ this.dependencies = dependencies;
+ }
+ }
+
+ public enum LoopType {
+ REINFORCING,
+ BALANCING,
+ UNDEFINED
+ };
+
+ /**
+ * Get all the loops within the diagram where the resource belongs to.
+ * @param r Resource that is studied
+ * @return List of loops; each loop is a list of resources in the same order in which
+ * they appear in the loop. The first item in the list can be any of the items in the
+ * loop.
+ */
+ public static List<List<Resource>> getLoops(final Resource r) {
+ List<List<Resource>> loops = Collections.emptyList();
+ try {
+ loops = Simantics.getSession().syncRequest(new Read<List<List<Resource>>>() {
+
+ @Override
+ public List<List<Resource>> perform(ReadGraph graph)
+ throws DatabaseException {
+ return getLoops(graph, r);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ return loops;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
+ public static List<List<Resource>> getLoops(ReadGraph g, Resource r) throws DatabaseException, ServiceException {
+ // Get all loops in the diagram.
+ List<List<Resource>> cycles = getAllLoopsInDiagram(g, r);
+
+ // Collect all those loops in which the original resource exists.
+ List<List<Resource>> loops = new ArrayList<List<Resource>>();
+ for (Object o : cycles) {
+ if (o instanceof List) {
+ List loop = (List)o;
+ if (loop.contains(r))
+ loops.add(loop);
+ }
+ }
+
+ // Debug print the result
+ if (false) {
+ System.out.println(cyclesToString(g, cycles));
+ }
+
+ return loops;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public static List<List<Resource>> getAllLoopsInDiagram(ReadGraph g, Resource r) throws DatabaseException, ServiceException {
+ Layer0 l0 = Layer0.getInstance(g);
+ SysdynResource sr = SysdynResource.getInstance(g);
+ Resource configuration = g.getPossibleObject(r, l0.PartOf);
+ if (configuration == null)
+ return Collections.emptyList();
+
+ Collection<Resource> variables = g.getObjects(configuration, l0.ConsistsOf);
+ ArrayList<Resource> shadows = new ArrayList<Resource>();
+
+ // Leave only independent variables and shadows (and modules)
+ Iterator<Resource> it = variables.iterator();
+ while (it.hasNext()) {
+ Resource v = it.next();
+ if (g.isInstanceOf(v, sr.IndependentVariable)) {
+ } else if (g.isInstanceOf(v, sr.Shadow)) {
+ shadows.add(v);
+ it.remove();
+ /*} else if (|| g.isInstanceOf(v, sr.Module)) {
+ */
+ } else {
+ it.remove();
+ }
+ }
+
+ int variableCount = variables.size();
+ Resource nodes[] = new Resource[variableCount];
+
+ // Add independent variables to map and array
+ int k = 0;
+ HashMap<Resource, ElementaryLoopItem> elementaryLoopItems = new HashMap<Resource, ElementaryLoopItem>();
+ for (Resource variable : variables) {
+ ArrayList<Resource> dependingVariables = new ArrayList<Resource>();
+ // Add forward dependencies and flows from valves.
+ Collection<Resource> dependencies = g.getObjects(variable, sr.Variable_isTailOf);
+ for (Resource dependency : dependencies) {
+ Resource head = g.getPossibleObject(dependency, sr.Variable_HasHead);
+ // Skip dependencies and flows to modules and clouds.
+ if (head == null
+ || g.isInstanceOf(head, sr.Module)
+ || g.isInstanceOf(head, sr.Cloud))
+ continue;
+
+ if ((g.isInstanceOf(dependency, sr.Flow) && g.isInstanceOf(variable, sr.Valve))
+ || g.isInstanceOf(dependency, sr.Dependency)) {
+ // Add all dependencies
+ // Add (only) such flows that start from a valve.
+ dependingVariables.add(head);
+ }
+ }
+ // Add backward flows from stocks.
+ Collection<Resource> backwardFlows = g.getObjects(variable, sr.Variable_isHeadOf);
+ for (Resource flow : backwardFlows) {
+ if (g.isInstanceOf(flow, sr.Flow)) {
+ Resource tail = g.getPossibleObject(flow, sr.Variable_HasTail);
+ if (tail != null && g.isInstanceOf(tail, sr.Stock)) {
+ // Add (only) such flows that start from a stock.
+ dependingVariables.add(tail);
+ }
+ }
+ }
+ // Put the variable in the hash map.
+ elementaryLoopItems.put(variable, new ElementaryLoopItem(k, dependingVariables));
+ nodes[k++] = variable;
+ }
+
+ // Add dependencies of shadow variables for their original variables
+ for (Resource shadow : shadows) {
+ Resource original = g.getPossibleObject(shadow, sr.Shadow_original);
+ ArrayList<Resource> dependingVariables = new ArrayList<Resource>();
+ Collection<Resource> dependencies = g.getObjects(shadow, sr.Variable_isTailOf);
+ for (Resource dependency : dependencies) {
+ Resource head = g.getPossibleObject(dependency, sr.Variable_HasHead);
+ if (!g.isInstanceOf(head, sr.Module)) {
+ dependingVariables.add(head);
+ }
+ }
+ ElementaryLoopItem el = elementaryLoopItems.get(original);
+ if (el != null)
+ el.dependencies.addAll(dependingVariables);
+ }
+
+ // Fill the adjacent matrix
+ boolean adjMatrix[][] = new boolean[variableCount][variableCount];
+ for (int j = 0; j < nodes.length; ++j) {
+ ArrayList<Resource> dependingVariables = elementaryLoopItems.get(nodes[j]).dependencies;
+ for (Resource v : dependingVariables) {
+ adjMatrix[j][elementaryLoopItems.get(v).mapping] = true;
+ }
+ }
+
+ // Get ALL nodes in the diagram.
+ ElementaryCyclesSearch ecs = new ElementaryCyclesSearch(adjMatrix, nodes);
+ List cycles = ecs.getElementaryCycles();
+
+ return cycles;
+ }
+
+ /**
+ * Get the String representation of cycles.
+ * @param g
+ * @param cycles List of Resource Lists of which names are returned.
+ * @return the String representation of cycles
+ * @throws DatabaseException
+ */
+ public static String cyclesToString(ReadGraph g, List<List<Resource>> cycles) throws DatabaseException {
+ StringBuilder sb = new StringBuilder("");
+ for (int i = 0; i < cycles.size(); i++) {
+ sb.append(cycleToString(g, cycles.get(i)));
+ sb.append("\n");
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Get the String representation of a cycle.
+ * @param g
+ * @param cycle List of Resources of which names are returned.
+ * @return the String representation of a cycle
+ * @throws DatabaseException
+ */
+ public static String cycleToString(ReadGraph g, List<Resource> cycle) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(g);
+ StringBuilder sb = new StringBuilder("");
+ for (int j = 0; j < cycle.size(); j++) {
+ Resource node = (Resource) cycle.get(j);
+ if (j < cycle.size() - 1) {
+ sb.append(g.getPossibleRelatedValue(node, l0.HasName, Bindings.STRING) + " -> ");
+ } else {
+ sb.append(g.<String>getPossibleRelatedValue(node, l0.HasName, Bindings.STRING));
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Get the type of the loop, i.e. whether the loop is reinforcing or balancing.
+ * The type is determined based on the dependency arrows and flows on the diagram;
+ * the loop is balancing if there is odd number of dependencies with negative
+ * polarity (Polarity = "-"). Note:
+ * 1) each flow of which tail is a valve is considered a dependency with positive
+ * (+) polarity.
+ * 2) each flow of which tail is a stock is considered a dependency with negative
+ * (-) polarity which GOES TO THE OPPOSITE DIRECTION.
+ * 3) the polarity of a supplementary dependency arrow overrides a flow.
+ * 4) the loops are defined as a list of Resources. If the set of dependencies
+ * between is ambiguous, the implementation may choose any possible dependency.
+ * 5) empty and null polarity are considered positive (+) polarities.
+ * @param graph
+ * @param resource The loop component
+ * @return the type of the loop. If the type cannot be determined,
+ * LoopType.UNDEFINED is returned
+ * @throws DatabaseException
+ */
+ public static LoopType getLoopType(ReadGraph graph, Resource resource) throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ ModelingResources mod = ModelingResources.getInstance(graph);
+ Resource loopResource = graph.getPossibleObject(resource, sr.Loop_Items);
+
+ if (loopResource == null)
+ return LoopType.UNDEFINED;
+
+ boolean oddNumberOfNegativeCausalities = false;
+ List<Resource> loop = ListUtils.toPossibleList(graph, loopResource);
+ for (int i = 0; i < loop.size(); ++i) {
+ boolean skipBackwardFlows = false;
+
+ // Go through forward dependencies and flows
+ Collection<Resource> forwardDependencies = graph.getObjects(loop.get(i), sr.Variable_isTailOf);
+
+ // And also through the forward dependencies of possible shadows.
+ Collection<Resource> shadows = graph.getObjects(loop.get(i), sr.Shadow_original_Inverse);
+ for (Resource shadow : shadows)
+ forwardDependencies.addAll(graph.getObjects(shadow, sr.Variable_isTailOf));
+
+ for (Resource dependency : forwardDependencies) {
+ Resource dependingVariable = graph.getSingleObject(dependency, sr.Variable_HasHead);
+ if (dependingVariable.equals(loop.get((i + 1) % loop.size()))) {
+ if (graph.isInstanceOf(dependency, sr.Flow)) {
+ /*
+ * Forward flows never affect the loop type. Allow dependency arrows
+ * override flows; thus don't touch skipBackwardFlows and continue.
+ * continue also because we may have a flow from stock, which
+ * is the wrong dependency and we need to keep searching.
+ */
+ continue;
+ }
+ skipBackwardFlows = true;
+
+ Resource dependencyConnection;
+ try {
+ dependencyConnection = graph.getSingleObject(dependency, mod.ConnectionToDiagramConnection);
+ } catch (NoSingleResultException e) {
+ return LoopType.UNDEFINED;
+ }
+ String polarity = (String)graph.getPossibleRelatedValue(dependencyConnection, sr.DependencyConnection_polarity, Bindings.STRING);
+ if ("-".equals(polarity)) {
+ oddNumberOfNegativeCausalities = !oddNumberOfNegativeCausalities;
+ } else if (polarity != null
+ && !"".equals(polarity)
+ && !"+".equals(polarity)) {
+ // There's something other than + in one of the dependencies
+ return LoopType.UNDEFINED;
+ }
+ // "+" doesn't affect loop type, consider null and "" as a "+".
+ break;
+ }
+ }
+
+ if (skipBackwardFlows)
+ continue;
+
+ // Backward flows from stocks.
+ Collection<Resource> backwardFlows = graph.getObjects(loop.get(i), sr.Variable_isHeadOf);
+ for (Resource flow : backwardFlows) {
+ if (graph.isInstanceOf(flow, sr.Flow)) {
+ Resource dependingVariable = graph.getSingleObject(flow, sr.Variable_HasTail);
+ if (dependingVariable.equals(loop.get((i + 1) % loop.size()))) {
+ if (graph.isInstanceOf(dependingVariable, sr.Stock)) {
+ // Basically, we should always end up here since all other
+ // possibilities have already been gone through.
+ oddNumberOfNegativeCausalities = !oddNumberOfNegativeCausalities;
+ break;
+ }
+ }
+ }
+ }
+ }
+ return oddNumberOfNegativeCausalities ? LoopType.BALANCING : LoopType.REINFORCING;
+ }
+}
-package org.simantics.sysdyn.utils;\r
-\r
-import java.util.UUID;\r
-\r
-import org.simantics.Simantics;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.Logger;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.Template;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.document.DocumentResource;\r
-import org.simantics.issues.ontology.IssueResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.modeling.ModelingUtils;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.project.ontology.ProjectResource;\r
-import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.manager.SysdynModel;\r
-import org.simantics.sysdyn.manager.SysdynModelManager;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-\r
-public class ModelUtils {\r
-\r
- /**\r
- * Returns the SysdynModel where the given variable is located\r
- * \r
- * @param graph ReadGraph\r
- * @param variable Variable whose model is wanted\r
- * @return SysdynModel where variable is located\r
- * @throws DatabaseException\r
- */\r
- public static SysdynModel getModel(ReadGraph graph, Resource variable) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource configuration = graph.getPossibleObject(variable, l0.PartOf);\r
- if(configuration == null)\r
- return null;\r
- SysdynModelManager sdm = SysdynModelManager.getInstance(Simantics.getSession());\r
- SysdynModel model = sdm.getModel(graph, configuration);\r
- try {\r
- model.update(graph);\r
- } catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- return model;\r
- }\r
-\r
- public static Resource createModel(WriteGraph graph) {\r
- return createModelAt(graph, Simantics.getProject().get());\r
- }\r
-\r
- // TODO: remove this\r
- public static Resource createModelAt(WriteGraph g, Resource library) {\r
- \r
- g.markUndoPoint();\r
- try {\r
- Layer0 l0 = Layer0.getInstance(g);\r
- Layer0X L0X = Layer0X.getInstance(g);\r
- SysdynResource sr = SysdynResource.getInstance(g);\r
- SpreadsheetResource SHEET = SpreadsheetResource.getInstance(g);\r
- ModelingUtils mu = new ModelingUtils(g);\r
- DocumentResource DOC = DocumentResource.getInstance(g);\r
-\r
- String modelName = NameUtils.findFreshName(g, "Model", library, l0.ConsistsOf, "%s%d");\r
-\r
- Resource project = Simantics.getProject().get();\r
- Resource model = GraphUtils.create2(g,\r
- sr.SysdynModel,\r
- l0.PartOf, project,\r
- l0.HasName, modelName,\r
- l0.HasLabel, modelName,\r
- L0X.IsActivatedBy, project\r
- );\r
-\r
- GraphUtils.create2(g,\r
- sr.Validations_Dependencies_MissingDependencyConnectionsIssueSource,\r
- L0X.IsActivatedBy, model,\r
- l0.PartOf, model\r
- );\r
-\r
- GraphUtils.create2(g,\r
- sr.Validations_Dependencies_DependencyConnectionsIssueSource,\r
- L0X.IsActivatedBy, model,\r
- l0.PartOf, model\r
- );\r
- \r
- GraphUtils.create2(g,\r
- sr.Validations_Expressions_ExpressionIssueSource,\r
- L0X.IsActivatedBy, model,\r
- l0.PartOf, model\r
- );\r
- \r
- GraphUtils.create2(g,\r
- sr.Validations_Enumerations_EnumerationIssueSource,\r
- L0X.IsActivatedBy, model,\r
- l0.PartOf, model\r
- ); \r
- \r
- GraphUtils.create2(g,\r
- sr.Validations_Units_UnitIssueSource,\r
- L0X.IsActivatedBy, model,\r
- l0.PartOf, model,\r
- IssueResource.getInstance(g).IssueSource_active, false\r
- ); \r
- \r
- Resource conf = GraphUtils.create2(g,\r
- sr.Configuration,\r
- l0.PartOf, model,\r
- L0X.IsBaseRealizationOf, model,\r
- l0.HasName, modelName\r
- );\r
-\r
- Resource diagram = g.newResource();\r
- g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,\r
- ArrayMap\r
- .keys("", "diagram", "name")\r
- .values(conf, diagram, "Diagrammi")\r
- );\r
-\r
- g.claim(model, mu.SIMU.HasConfiguration, conf);\r
-\r
- Resource book = g.newResource();\r
- g.claim(book, l0.InstanceOf, null, SHEET.Book);\r
- g.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING);\r
- g.claim(conf, l0.ConsistsOf, l0.PartOf, book);\r
-\r
- SheetUtils.createSheet(g, book, "Sheet1", new String[] { }, new int[] { 50 });\r
-\r
-\r
-\r
- ModelingResources mr = ModelingResources.getInstance(g);\r
- // Remove default mapping and add sysdyn mapping\r
- for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {\r
- if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {\r
- g.deny(diagram, L0X.HasTrigger, trigger);\r
- }\r
- }\r
- Resource mapping = g.newResource();\r
- g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);\r
- g.claim(diagram, L0X.HasTrigger, mapping);\r
-\r
- Resource report = GraphUtils.create2(g, DOC.Report, DOC.HasDocumentation, "===Report===");\r
-\r
- GraphUtils.create2(g, sr.BasicExperiment,\r
- l0.HasName, "Experiment",\r
- l0.HasLabel, "Experiment",\r
- DOC.HasReportFactory, report,\r
- l0.PartOf, model);\r
-\r
- // #5484: removed (deprecated) sheet experiment from new models\r
-// Resource sheetExperiment = GraphUtils.create2(g, SHEET.Experiment,\r
-// l0.HasName, "SheetExperiment",\r
-// l0.HasLabel, "Sheet Experiment",\r
-// l0.PartOf, model);\r
-//\r
-// Resource sheetRun = GraphUtils.create2(g, SHEET.Run,\r
-// l0.HasName, "Default",\r
-// l0.PartOf, sheetExperiment);\r
-\r
- ProjectResource PROJ = ProjectResource.getInstance(g);\r
- for(Resource dep : g.getObjects(library, l0.IsLinkedTo)) {\r
- if(g.isInstanceOf(dep, PROJ.NamespaceRequirement)) {\r
- for(Resource req : g.getObjects(dep, PROJ.RequiresNamespace)) {\r
- String uri = g.getPossibleValue(req, Bindings.STRING);\r
- if(uri != null) {\r
- Resource target = g.getResource(uri);\r
- if(target != null) {\r
- g.claim(model, l0.IsLinkedTo, null, target);\r
- }\r
- }\r
- }\r
- }\r
- }\r
- \r
- createSCLMain(g, model);\r
- \r
- ProfileEntries.createStandardProfiles(g, model);\r
- \r
- Layer0Utils.addCommentMetadata(g, "Created new Sysdyn Model '" + modelName + "' " + model.toString());\r
- \r
- return model;\r
- \r
- } catch (DatabaseException e ) {\r
- Logger.defaultLogError(e);\r
- }\r
- \r
- return null;\r
- }\r
- \r
- public static void createSCLMain(WriteGraph graph, Resource model) throws DatabaseException {\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- Resource SCLModule = GraphUtils.create2(graph,\r
- L0.SCLModule,\r
- L0.PartOf, model,\r
- L0.HasName, "SCLMain"\r
- );\r
-\r
- if(graph.hasStatement(SCLModule, L0.SCLModule_definition))\r
- graph.deny(SCLModule, L0.SCLModule_definition);\r
-\r
- graph.claimLiteral(SCLModule, L0.SCLModule_definition, \r
- "include \"Simantics/All\"\n" +\r
- "include \"Simantics/Sysdyn\"\n", \r
- Bindings.STRING);\r
-\r
- }\r
-}\r
+package org.simantics.sysdyn.utils;
+
+import java.util.UUID;
+
+import org.simantics.Simantics;
+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.utils.Logger;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.adapter.Template;
+import org.simantics.db.layer0.util.Layer0Utils;
+import org.simantics.document.DocumentResource;
+import org.simantics.issues.ontology.IssueResource;
+import org.simantics.layer0.Layer0;
+import org.simantics.layer0.utils.direct.GraphUtils;
+import org.simantics.modeling.ModelingResources;
+import org.simantics.modeling.ModelingUtils;
+import org.simantics.operation.Layer0X;
+import org.simantics.project.ontology.ProjectResource;
+import org.simantics.spreadsheet.graph.SpreadsheetGraphUtils;
+import org.simantics.spreadsheet.util.SpreadsheetUtils;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.manager.SysdynModel;
+import org.simantics.sysdyn.manager.SysdynModelManager;
+import org.simantics.utils.datastructures.ArrayMap;
+
+public class ModelUtils {
+
+ /**
+ * Returns the SysdynModel where the given variable is located
+ *
+ * @param graph ReadGraph
+ * @param variable Variable whose model is wanted
+ * @return SysdynModel where variable is located
+ * @throws DatabaseException
+ */
+ public static SysdynModel getModel(ReadGraph graph, Resource variable) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource configuration = graph.getPossibleObject(variable, l0.PartOf);
+ if(configuration == null)
+ return null;
+ SysdynModelManager sdm = SysdynModelManager.getInstance(Simantics.getSession());
+ SysdynModel model = sdm.getModel(graph, configuration);
+ try {
+ model.update(graph);
+ } catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ return model;
+ }
+
+ public static Resource createModel(WriteGraph graph) {
+ return createModelAt(graph, Simantics.getProject().get());
+ }
+
+ // TODO: remove this
+ public static Resource createModelAt(WriteGraph g, Resource library) {
+
+ g.markUndoPoint();
+ try {
+ Layer0 l0 = Layer0.getInstance(g);
+ Layer0X L0X = Layer0X.getInstance(g);
+ SysdynResource sr = SysdynResource.getInstance(g);
+
+ ModelingUtils mu = new ModelingUtils(g);
+ DocumentResource DOC = DocumentResource.getInstance(g);
+
+ String modelName = NameUtils.findFreshName(g, "Model", library, l0.ConsistsOf, "%s%d");
+
+ Resource project = Simantics.getProject().get();
+ Resource model = GraphUtils.create2(g,
+ sr.SysdynModel,
+ l0.PartOf, project,
+ l0.HasName, modelName,
+ l0.HasLabel, modelName,
+ L0X.IsActivatedBy, project
+ );
+
+ GraphUtils.create2(g,
+ sr.Validations_Dependencies_MissingDependencyConnectionsIssueSource,
+ L0X.IsActivatedBy, model,
+ l0.PartOf, model
+ );
+
+ GraphUtils.create2(g,
+ sr.Validations_Dependencies_DependencyConnectionsIssueSource,
+ L0X.IsActivatedBy, model,
+ l0.PartOf, model
+ );
+
+ GraphUtils.create2(g,
+ sr.Validations_Expressions_ExpressionIssueSource,
+ L0X.IsActivatedBy, model,
+ l0.PartOf, model
+ );
+
+ GraphUtils.create2(g,
+ sr.Validations_Enumerations_EnumerationIssueSource,
+ L0X.IsActivatedBy, model,
+ l0.PartOf, model
+ );
+
+ GraphUtils.create2(g,
+ sr.Validations_Units_UnitIssueSource,
+ L0X.IsActivatedBy, model,
+ l0.PartOf, model,
+ IssueResource.getInstance(g).IssueSource_active, false
+ );
+
+ Resource conf = GraphUtils.create2(g,
+ sr.Configuration,
+ l0.PartOf, model,
+ L0X.IsBaseRealizationOf, model,
+ l0.HasName, modelName
+ );
+
+ Resource diagram = g.newResource();
+ g.adapt(sr.ConfigurationDiagramTemplate, Template.class).apply(g,
+ ArrayMap
+ .keys("", "diagram", "name")
+ .values(conf, diagram, "Diagram")
+ );
+
+ g.claim(model, mu.SIMU.HasConfiguration, conf);
+
+ Resource book = SpreadsheetGraphUtils.createBook(g, conf, "Book" + UUID.randomUUID().toString());
+
+ SpreadsheetUtils.createSheet(g, book, "Sheet1", new String[] { }, new int[] { 50 });
+
+
+ ModelingResources mr = ModelingResources.getInstance(g);
+ // Remove default mapping and add sysdyn mapping
+ for(Resource trigger : g.getObjects(diagram, L0X.HasTrigger)) {
+ if(g.isInstanceOf(trigger, mr.DiagramToCompositeMapping)) {
+ g.deny(diagram, L0X.HasTrigger, trigger);
+ }
+ }
+ Resource mapping = g.newResource();
+ g.claim(mapping, l0.InstanceOf, null, sr.DiagramToCompositeMapping);
+ g.claim(diagram, L0X.HasTrigger, mapping);
+
+ Resource report = GraphUtils.create2(g, DOC.Report, DOC.HasDocumentation, "===Report===");
+
+ GraphUtils.create2(g, sr.BasicExperiment,
+ l0.HasName, "Experiment",
+ l0.HasLabel, "Experiment",
+ DOC.HasReportFactory, report,
+ l0.PartOf, model);
+
+ // #5484: removed (deprecated) sheet experiment from new models
+// Resource sheetExperiment = GraphUtils.create2(g, SHEET.Experiment,
+// l0.HasName, "SheetExperiment",
+// l0.HasLabel, "Sheet Experiment",
+// l0.PartOf, model);
+//
+// Resource sheetRun = GraphUtils.create2(g, SHEET.Run,
+// l0.HasName, "Default",
+// l0.PartOf, sheetExperiment);
+
+ ProjectResource PROJ = ProjectResource.getInstance(g);
+ for(Resource dep : g.getObjects(library, l0.IsLinkedTo)) {
+ if(g.isInstanceOf(dep, PROJ.NamespaceRequirement)) {
+ for(Resource req : g.getObjects(dep, PROJ.RequiresNamespace)) {
+ String uri = g.getPossibleValue(req, Bindings.STRING);
+ if(uri != null) {
+ Resource target = g.getResource(uri);
+ if(target != null) {
+ g.claim(model, l0.IsLinkedTo, null, target);
+ }
+ }
+ }
+ }
+ }
+
+ createSCLMain(g, model);
+
+ ProfileEntries.createStandardProfiles(g, model);
+
+ Layer0Utils.addCommentMetadata(g, "Created new Sysdyn Model '" + modelName + "' " + model.toString());
+
+ return model;
+
+ } catch (DatabaseException e ) {
+ Logger.defaultLogError(e);
+ }
+
+ return null;
+ }
+
+ public static void createSCLMain(WriteGraph graph, Resource model) throws DatabaseException {
+ Layer0 L0 = Layer0.getInstance(graph);
+ Resource SCLModule = GraphUtils.create2(graph,
+ L0.SCLModule,
+ L0.PartOf, model,
+ L0.HasName, "SCLMain"
+ );
+
+ if(graph.hasStatement(SCLModule, L0.SCLModule_definition))
+ graph.deny(SCLModule, L0.SCLModule_definition);
+
+ graph.claimLiteral(SCLModule, L0.SCLModule_definition,
+ "include \"Simantics/All\"\n" +
+ "include \"Simantics/Sysdyn\"\n",
+ Bindings.STRING);
+
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.utils;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.databoard.binding.mutable.Variant;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.spreadsheet.SheetVariables;\r
-import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
-\r
-public class SheetUtils {\r
-\r
- public static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- SpreadsheetResource sr = SpreadsheetResource.getInstance(graph);\r
-\r
- Resource result = graph.newResource();\r
- graph.claim(result, L0.InstanceOf, null, sr.Spreadsheet);\r
-\r
- if(name == null) {\r
- name = NameUtils.findFreshEscapedName(graph, "Sheet", book, L0.ConsistsOf);\r
- }\r
- graph.claimLiteral(result, L0.HasName, L0.NameOf, L0.String, name, Bindings.STRING);\r
- graph.claim(book, L0.ConsistsOf, L0.PartOf, result);\r
-\r
- {\r
- Resource newCell = graph.newResource();\r
- graph.claim(newCell, L0.InstanceOf, null, sr.Dimensions);\r
- graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Dimensions", Bindings.STRING);\r
- graph.addLiteral(newCell, sr.Dimensions_fitColumns, sr.Dimensions_fitColumns_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
- graph.addLiteral(newCell, sr.Dimensions_fitRows, sr.Dimensions_fitRows_Inverse, L0.Boolean, false, Bindings.BOOLEAN);\r
- graph.addLiteral(newCell, sr.Dimensions_columnCount, sr.Dimensions_columnCount_Inverse, L0.Integer, 128, Bindings.INTEGER);\r
- graph.addLiteral(newCell, sr.Dimensions_rowCount, sr.Dimensions_rowCount_Inverse, L0.Integer, 256, Bindings.INTEGER);\r
- graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
- }\r
-\r
- {\r
- Resource newCell = graph.newResource();\r
- graph.claim(newCell, L0.InstanceOf, null, sr.Headers);\r
- graph.claimLiteral(newCell, L0.HasName, L0.NameOf, L0.String, "Headers", Bindings.STRING);\r
- graph.addLiteral(newCell, sr.Headers_columnLabels, sr.Headers_columnLabels_Inverse, L0.StringArray, colNames, Bindings.STRING_ARRAY);\r
- graph.addLiteral(newCell, sr.Headers_columnWidths, sr.Headers_columnWidths_Inverse, L0.IntegerArray, colWidths, Bindings.INT_ARRAY);\r
- graph.claim(result, L0.ConsistsOf, L0.PartOf, newCell);\r
- }\r
-\r
-// {\r
-// \r
-// double[] doubles = new double[10*2];\r
-// for(int i=0;i<10*2;i++) doubles[i] = i;\r
-// \r
-// Resource newCell = graph.newResource();\r
-// graph.claim(newCell, L0.InstanceOf, null, sr.DoubleArrayCell);\r
-// graph.addLiteral(newCell, sr.DoubleArrayCell_HasWidth, sr.DoubleArrayCell_HasWidth_Inverse, L0.Integer, 10, Bindings.INTEGER);\r
-// graph.addLiteral(newCell, sr.HasLocation, sr.HasLocation_Inverse, L0.String, "B2", Bindings.STRING);\r
-// graph.addLiteral(newCell, sr.DoubleArrayCell_HasDoubleArray, sr.DoubleArrayCell_HasDoubleArray_Inverse, L0.DoubleArray, doubles, Bindings.DOUBLE_ARRAY);\r
-// graph.claim(result, L0.HasChildVariables, L0.HasChildVariables_Inverse, newCell);\r
-// \r
-// }\r
- return result;\r
-\r
- }\r
-\r
- public static String getStringRepresentation(ReadGraph graph, Resource model, String sheetName, String range) throws DatabaseException {\r
- Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);\r
- Variable sheetVariable = null;\r
- for(Resource book : graph.syncRequest(new ObjectsWithType(configuration, L0.ConsistsOf, SHEET.Book))) {\r
- for(Resource sheet : graph.syncRequest(new ObjectsWithType(book, L0.ConsistsOf, SHEET.Spreadsheet))) {\r
- if(sheetName.equals(NameUtils.getSafeName(graph, sheet))) {\r
- sheetVariable = Variables.getVariable(graph, sheet);\r
- }\r
- }\r
- }\r
-\r
- if(sheetVariable == null)\r
- return null;\r
-\r
- Variable rangeVariable = sheetVariable.getChild(graph, range);\r
-\r
-\r
- String[][] rangeCells = rangeVariable.getPropertyValue(graph, SheetVariables.RANGE_CELL_NAMES);\r
- if(rangeCells == null || rangeCells[0].length <= 1)\r
- return null;\r
- else {\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("{");\r
- for(int i = 0; i < rangeCells.length; i++) {\r
- sb.append("{");\r
- for(int j = 0; j < rangeCells[i].length; j++) {\r
- String valueCell = rangeCells[i][j];\r
- Variable cell = sheetVariable.getChild(graph, valueCell);\r
- Variant valueVariant = cell.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT);\r
- Object valueObject = valueVariant.getValue();\r
- sb.append(valueObject.toString());\r
- if(j < rangeCells[i].length - 1)\r
- sb.append(", ");\r
- }\r
- sb.append("}");\r
- if(i < rangeCells.length - 1)\r
- sb.append(", ");\r
- }\r
- sb.append("}");\r
-\r
- return sb.toString();\r
- }\r
- }\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011 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.sysdyn.utils;
+
+import org.simantics.databoard.Bindings;
+import org.simantics.databoard.binding.mutable.Variant;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ObjectsWithType;
+import org.simantics.db.common.utils.NameUtils;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.layer0.Layer0;
+import org.simantics.simulation.ontology.SimulationResource;
+import org.simantics.spreadsheet.SheetVariables;
+import org.simantics.spreadsheet.resource.SpreadsheetResource;
+
+public class SheetUtils {
+
+ /**
+ * Used by WithLookupExpression, nothing else, to find a String representation of a certain range
+ * @param graph
+ * @param model
+ * @param sheetName
+ * @param range
+ * @return
+ * @throws DatabaseException
+ */
+ public static String getStringRepresentation(ReadGraph graph, Resource model, String sheetName, String range) throws DatabaseException {
+ Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);
+ Layer0 L0 = Layer0.getInstance(graph);
+ SpreadsheetResource SHEET = SpreadsheetResource.getInstance(graph);
+ Variable sheetVariable = null;
+ for(Resource book : graph.syncRequest(new ObjectsWithType(configuration, L0.ConsistsOf, SHEET.Book))) {
+ for(Resource sheet : graph.syncRequest(new ObjectsWithType(book, L0.ConsistsOf, SHEET.Spreadsheet))) {
+ if(sheetName.equals(NameUtils.getSafeName(graph, sheet))) {
+ sheetVariable = Variables.getVariable(graph, sheet);
+ }
+ }
+ }
+
+ if(sheetVariable == null)
+ return null;
+
+ Variable rangeVariable = sheetVariable.getChild(graph, range);
+
+
+ String[][] rangeCells = rangeVariable.getPropertyValue(graph, SheetVariables.RANGE_CELL_NAMES);
+ if(rangeCells == null || rangeCells[0].length <= 1)
+ return null;
+ else {
+ StringBuilder sb = new StringBuilder();
+ sb.append("{");
+ for(int i = 0; i < rangeCells.length; i++) {
+ sb.append("{");
+ for(int j = 0; j < rangeCells[i].length; j++) {
+ String valueCell = rangeCells[i][j];
+ Variable cell = sheetVariable.getChild(graph, valueCell);
+ Variant valueVariant = cell.getPropertyValue(graph, SheetVariables.CONTENT, Bindings.VARIANT);
+ Object valueObject = valueVariant.getValue();
+ sb.append(valueObject.toString());
+ if(j < rangeCells[i].length - 1)
+ sb.append(", ");
+ }
+ sb.append("}");
+ if(i < rangeCells.length - 1)
+ sb.append(", ");
+ }
+ sb.append("}");
+
+ return sb.toString();
+ }
+ }
+}
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\r
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\r
- <modelVersion>4.0.0</modelVersion>\r
- <artifactId>org.simantics.sysdyn.repository</artifactId>\r
- <version>1.10.0-SNAPSHOT</version>\r
- <packaging>eclipse-repository</packaging>\r
-\r
- <parent>\r
- <groupId>org.simantics</groupId>\r
- <artifactId>org.simantics.sysdyn.root.releng</artifactId>\r
- <version>1.0.0-SNAPSHOT</version>\r
- </parent>\r
-\r
- <build>\r
- <pluginManagement>\r
- <plugins>\r
- <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->\r
- <plugin>\r
- <groupId>org.eclipse.m2e</groupId>\r
- <artifactId>lifecycle-mapping</artifactId>\r
- <version>1.0.0</version>\r
- <configuration>\r
- <lifecycleMappingMetadata>\r
- <pluginExecutions>\r
- <pluginExecution>\r
- <pluginExecutionFilter>\r
- <groupId>\r
- org.apache.maven.plugins\r
- </groupId>\r
- <artifactId>\r
- maven-clean-plugin\r
- </artifactId>\r
- <versionRange>\r
- [2.5,)\r
- </versionRange>\r
- <goals>\r
- <goal>clean</goal>\r
- </goals>\r
- </pluginExecutionFilter>\r
- <action>\r
- <ignore></ignore>\r
- </action>\r
- </pluginExecution>\r
- <pluginExecution>\r
- <pluginExecutionFilter>\r
- <groupId>\r
- org.eclipse.tycho\r
- </groupId>\r
- <artifactId>\r
- tycho-packaging-plugin\r
- </artifactId>\r
- <versionRange>\r
- [0.26.0,)\r
- </versionRange>\r
- <goals>\r
- <goal>\r
- build-qualifier-aggregator\r
- </goal>\r
- </goals>\r
- </pluginExecutionFilter>\r
- <action>\r
- <ignore></ignore>\r
- </action>\r
- </pluginExecution>\r
- </pluginExecutions>\r
- </lifecycleMappingMetadata>\r
- </configuration>\r
- </plugin>\r
- </plugins>\r
- </pluginManagement>\r
- </build>\r
-</project>\r
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>org.simantics.sysdyn.repository</artifactId>
+ <version>1.10.0-SNAPSHOT</version>
+ <packaging>eclipse-repository</packaging>
+
+ <parent>
+ <groupId>org.simantics</groupId>
+ <artifactId>org.simantics.sysdyn.root.releng</artifactId>
+ <version>1.0.0-SNAPSHOT</version>
+ </parent>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>
+ org.apache.maven.plugins
+ </groupId>
+ <artifactId>
+ maven-clean-plugin
+ </artifactId>
+ <versionRange>
+ [2.5,)
+ </versionRange>
+ <goals>
+ <goal>clean</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore></ignore>
+ </action>
+ </pluginExecution>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>
+ org.eclipse.tycho
+ </groupId>
+ <artifactId>
+ tycho-packaging-plugin
+ </artifactId>
+ <versionRange>
+ [0.26.0,)
+ </versionRange>
+ <goals>
+ <goal>
+ build-qualifier-aggregator
+ </goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore></ignore>
+ </action>
+ </pluginExecution>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>org.simantics</groupId>
+ <artifactId>
+ graph-builder-maven-plugin
+ </artifactId>
+ <versionRange>
+ [0.0.9,)
+ </versionRange>
+ <goals>
+ <goal>compile-graphs</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore></ignore>
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+</project>