From: Miro Richard Eklund Date: Fri, 27 Jul 2018 15:05:22 +0000 (+0300) Subject: Sysdyn model browser context update X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=commitdiff_plain;h=1c0b4b4ba8ddc060459a6939feb00216802ad2bd;p=simantics%2Fsysdyn.git Sysdyn model browser context update + Re-introduce missing model browser contexts such as import, export, new for libraries, functions, charts and more for Sysdyn models. Full list: Modules: Import Module Experiments: New Game Experiment, New Sensitivity Analysis Experiment Functions: Import Function Library Function Library: Export Function Library, New Function, New Function Library Charts: New Sensitivity Chart Experiment: Assign IC Model: Export Model History Dataset: Show in charts Module: Assign Symbol Groups..., Export Module Model: Open Diagram Editor (also works with double-click) + Reintroduced "Initial Conditions" folder under sysdyn model + Allow underscore characters in sysdyn name validator + Use SpreadsheetUtils and SpreadsheetGraphUtils (not sysdyn.SheetUtils) to create new books and spreadsheets for Sysdyn models. This way the implementation relies on the platform implementation and doesn't need to copy-paste the implementation to a sysdyn-specific SheetUtils class. + Previously, deleting a Module only removed the Symbol associated with it, leaving the Module itself intact and listed under the .sysdyn model's graph. Now, a separate remover for deleting a module has been added that checks if the deleted resource is a symbol, in which case it searches for the parent Module and deletes that instead of the symbol. + Refactor testGraph to sub-folder + Make changes to various async and sync requests to take into account changes in platform. + Replace all deprecated usage of SimanticsUI with Simantics + Fix PlaybackSliderContribution + ModelBrowser view shows type of Variables again (just like in 1.9.1). I.e. NAME : TYPE (e.g MAX DISCOVERY RATE : Auxiliary). gitlab #7 gitlab #3 gitlab #18 gitlab #13 gitlab #19 gitlab #20 gitlab #21 gitlab #23 gitlab #24 gitlab #25 gitlab #26 gitlab #27 closes #7 closes #3 closes #18 closes #13 closes #19 closes #20 closes #21 closes #23 closes #24 closes #25 closes #26 closes #27 Change-Id: I2e93cbd6497c77d4796c91e32f64f0d43749ba3c --- diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanel.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanel.java index a698efe8..804759ff 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanel.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanel.java @@ -1,471 +1,471 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 charts; - private ArrayList minimizedResources; - - private ArrayList 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(); - - 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(); - - // add chart resources to chart lists from settings - try { - SimanticsUI.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(); - - 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 { - SimanticsUI.getSession().syncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - if (settings != null) { - String[] uris = new String[chartElements.size() - 1]; - ArrayList minimized = new ArrayList(); - 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) { - SimanticsUI.getSession().asyncRequest(new Read() { - - @Override - public Boolean perform(ReadGraph graph) throws DatabaseException { - return graph.hasStatement(chart); - } - }, new AsyncListener() { - - 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 getElements() { - return chartElements; - } -} +/******************************************************************************* + * 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 charts; + private ArrayList minimizedResources; + + private ArrayList 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(); + + 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(); + + // 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(); + + 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 minimized = new ArrayList(); + 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() { + + @Override + public Boolean perform(ReadGraph graph) throws DatabaseException { + return graph.hasStatement(chart); + } + }, new AsyncListener() { + + 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 getElements() { + return chartElements; + } +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelHeader.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelHeader.java index 5935c34f..1b95c4b3 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelHeader.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/ChartPanelHeader.java @@ -1,397 +1,397 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 result = SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public Pair 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(label, image); - } - - }, new Listener>() { - - @Override - public void execute(final Pair 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); - } - - } -} +/******************************************************************************* + * 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 result = Simantics.getSession().syncRequest(new Read>() { + + @Override + public Pair 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(label, image); + } + + }, new Listener>() { + + @Override + public void execute(final Pair 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); + } + + } +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractPlot.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractPlot.java index c24759cd..600de403 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractPlot.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/AbstractPlot.java @@ -1,209 +1,209 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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(); - SimanticsUI.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 { - - 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 axisMap = new HashMap(); - - // 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 { - - 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; - } - - } -} +/******************************************************************************* + * 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 { + + 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 axisMap = new HashMap(); + + // 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 { + + 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; + } + + } +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite.java index 6d571f54..e9088797 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite.java @@ -1,161 +1,160 @@ -/******************************************************************************* - * 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.ui.SimanticsUI; -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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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() { - - @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() { - - @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(); - - } - }); - } - -} +/******************************************************************************* + * 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() { + + @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() { + + @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() { + + @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(); + + } + }); + } + +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite2.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite2.java index 198fe014..32ef7c34 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite2.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ChartComposite2.java @@ -28,7 +28,6 @@ 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.ui.SimanticsUI; import org.simantics.utils.threads.AWTThread; import org.simantics.utils.threads.ThreadUtils; import org.simantics.utils.ui.SWTAWTComponent; @@ -50,7 +49,7 @@ public class ChartComposite2 extends SWTAWTComponent { public ChartComposite2(Composite parent, final String chartResourceURI, int style) { super(parent, style); try { - Resource chartResource = SimanticsUI.getSession().syncRequest(new Read() { + Resource chartResource = Simantics.getSession().syncRequest(new Read() { @Override public Resource perform(ReadGraph graph) throws DatabaseException { diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/JFreeChart.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/JFreeChart.java index a76cb1d2..788df9f8 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/JFreeChart.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/JFreeChart.java @@ -1,209 +1,209 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 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(); - SimanticsUI.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> { - - public JFreeChartQuery() { - } - - @Override - public Pair 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(title, legendVisible); - } - } - - protected class JFreeChartListener implements Listener> { - - private boolean disposed = false; - private LegendTitle legend; - - public JFreeChartListener() { - - } - - public void dispose() { - disposed = true; - } - - @Override - public void execute(final Pair 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; - } - - } - -} +/******************************************************************************* + * 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 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> { + + public JFreeChartQuery() { + } + + @Override + public Pair 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(title, legendVisible); + } + } + + protected class JFreeChartListener implements Listener> { + + private boolean disposed = false; + private LegendTitle legend; + + public JFreeChartListener() { + + } + + public void dispose() { + disposed = true; + } + + @Override + public void execute(final Pair 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; + } + + } + +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisDropAction.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisDropAction.java index 40bca222..673e7f43 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisDropAction.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/AxisDropAction.java @@ -1,104 +1,104 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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() { - SimanticsUI.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 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; - } - -} +/******************************************************************************* + * 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 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; + } + +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesDropAction.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesDropAction.java index 41c6bb69..cdf6ddf5 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesDropAction.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/ge/SeriesDropAction.java @@ -1,139 +1,139 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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() { - SimanticsUI.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.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 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; - } - -} +/******************************************************************************* + * 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.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 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; + } + +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableExistsValidator.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableExistsValidator.java index 32abe9e6..c86b90b5 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableExistsValidator.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableExistsValidator.java @@ -1,129 +1,129 @@ -package org.simantics.jfreechart.chart.properties; - -import java.util.ArrayList; -import java.util.Collection; - -import org.eclipse.jface.dialogs.IInputValidator; -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.ui.SimanticsUI; -import org.simantics.utils.ui.AdaptionUtils; - -/** - * Variable exists validator for tracked text widgets. - * - * @author Teemu Lempinen - * - */ -public class VariableExistsValidator implements IInputValidator, Widget { - - protected Collection 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(); - 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(); - 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) - SimanticsUI.getSession().asyncRequest(query - , new Listener>() { - - @Override - public void execute(Collection 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(); - } - } - -} +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 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(); + 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(); + 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>() { + + @Override + public void execute(Collection 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(); + } + } + +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableProposalProvider.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableProposalProvider.java index da399f6b..fac86108 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableProposalProvider.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/VariableProposalProvider.java @@ -1,194 +1,194 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.AdaptionUtils; - -/** - * - * @author Marko Luukkainen - * - */ -public class VariableProposalProvider implements IContentProposalProvider, Widget { - - /* - * The proposals provided. - */ - private Collection 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 true) - * @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 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 items) { - this.proposals = items; - contentProposals = null; - } - - /** - * Set the boolean that controls whether proposals are filtered according to - * the current field content. - * - * @param filterProposals - * true if the proposals should be filtered to - * show only those that match the current contents of the field, - * and false 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(); - 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); - SimanticsUI.getSession().asyncRequest(query - , new Listener>() { - - @Override - public void execute(Collection 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(); - } - - - - } - -} +/******************************************************************************* + * 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 + * + */ +public class VariableProposalProvider implements IContentProposalProvider, Widget { + + /* + * The proposals provided. + */ + private Collection 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 true) + * @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 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 items) { + this.proposals = items; + contentProposals = null; + } + + /** + * Set the boolean that controls whether proposals are filtered according to + * the current field content. + * + * @param filterProposals + * true if the proposals should be filtered to + * show only those that match the current contents of the field, + * and false 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(); + 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>() { + + @Override + public void execute(Collection 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(); + } + + + + } + +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisAndVariablesExplorerComposite.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisAndVariablesExplorerComposite.java index 04b02097..ebaed442 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisAndVariablesExplorerComposite.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/AxisAndVariablesExplorerComposite.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 args, IWorkbenchSite site, Composite parent, - WidgetSupport support, int style) { - super(args, site, parent, support, style); - - SimanticsUI.getSession().asyncRequest(new ReadRequest() { - @Override - public void run(ReadGraph graph) throws DatabaseException { - ArrayList browseContexts = new ArrayList(); - 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; - - SimanticsUI.getSession().asyncRequest(new Read() { - @Override - public Runnable perform(ReadGraph graph) throws DatabaseException { - if (dndBrowseContext == null) - return null; - return dndBrowseContext.getAction(graph, target, data); - } - }, new Procedure() { - @Override - public void execute(Runnable result) { - if (result != null) - result.run(); - } - - @Override - public void exception(Throwable t) { - ErrorLogger.defaultLogError(t); - } - }); - } - -} +/******************************************************************************* + * 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 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 browseContexts = new ArrayList(); + 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() { + @Override + public Runnable perform(ReadGraph graph) throws DatabaseException { + if (dndBrowseContext == null) + return null; + return dndBrowseContext.getAction(graph, target, data); + } + }, new Procedure() { + @Override + public void execute(Runnable result) { + if (result != null) + result.run(); + } + + @Override + public void exception(Throwable t) { + ErrorLogger.defaultLogError(t); + } + }); + } + +} diff --git a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineAxisAndVariablesTab.java b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineAxisAndVariablesTab.java index ea2714ec..d4af57c9 100644 --- a/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineAxisAndVariablesTab.java +++ b/bundles/org.simantics.jfreechart/src/org/simantics/jfreechart/chart/properties/xyline/XYLineAxisAndVariablesTab.java @@ -1,330 +1,330 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 { - - 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 { - - 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 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 { - - 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); - } -} +/******************************************************************************* + * 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() { + + @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 { + + 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 { + + 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 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 { + + 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph b/bundles/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph index 04c7a5d6..5564458c 100644 --- a/bundles/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph +++ b/bundles/org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph @@ -329,8 +329,8 @@ SYSDYN.ExternalFunctionFile -- SYSDYN.ExternalFunctionFile.externalFile --> L0.ByteArray -VP = -SIMU = -PROJECT = -IMAGE = -ACT = -MOD = -STR = -SYSDYN = -SILK = -SHEET = -JFREE = -SEL = - -SYSDYN.SysdynSelectionProcessor : SEL.SelectionProcessorContribution - -SBC = SYSDYN.ModelingBrowseContext : VP.BrowseContext -SAC = SYSDYN.ModelingActionContext : VP.BrowseContext - VP.BrowseContext.IsIncludedIn PROJECT.ProjectActionContext - -SBC.VariableNodeType -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 - @VP.relationChildRuleWithFolder SYSDYN.SysdynModel L0.ConsistsOf SYSDYN.Experiment - SBC.ExperimentsFolder - @VP.relationChildRule SYSDYN.Experiment SYSDYN.Experiment.result SYSDYN.Result - - @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.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.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.brick - @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.BasicExperiment SILK.time - @VP.constantImageRule SYSDYN.PlaybackExperiment SILK.timeline_marker - @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 - -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 "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 "Sheet" SHEET.Book SILK.table VP.NewActionCategory ACTIONS.NewSheet - @VP.actionContribution "History Data" SYSDYN.Experiment SILK.table VP.NewActionCategory ACTIONS.NewHistoryData - - -// 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 - +L0 = +VP = +SIMU = +PROJECT = +IMAGE = +ACT = +MOD = +STR = +SYSDYN = +SILK = +SHEET = +JFREE = +SEL = + +SYSDYN.SysdynSelectionProcessor : SEL.SelectionProcessorContribution + +SBC = SYSDYN.ModelingBrowseContext : VP.BrowseContext +SAC = SYSDYN.ModelingActionContext : VP.BrowseContext + VP.BrowseContext.IsIncludedIn PROJECT.ProjectActionContext + +SBC.VariableNodeType +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 + diff --git a/bundles/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java b/bundles/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java index 065d5d4f..2b21dd6c 100644 --- a/bundles/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java +++ b/bundles/org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java @@ -573,20 +573,32 @@ public class SysdynResource { 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; @@ -594,6 +606,7 @@ public class SysdynResource { 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; @@ -1434,20 +1447,32 @@ public class SysdynResource { 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"; @@ -1455,6 +1480,7 @@ public class SysdynResource { 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"; @@ -2305,20 +2331,32 @@ public class SysdynResource { 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); @@ -2326,6 +2364,7 @@ public class SysdynResource { 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); diff --git a/bundles/org.simantics.sysdyn.ontology/testGraph.tg b/bundles/org.simantics.sysdyn.ontology/testGraph/testGraph.tg similarity index 100% rename from bundles/org.simantics.sysdyn.ontology/testGraph.tg rename to bundles/org.simantics.sysdyn.ontology/testGraph/testGraph.tg diff --git a/bundles/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF b/bundles/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF index 15e1d2cb..537c054d 100644 --- a/bundles/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.sysdyn.ui/META-INF/MANIFEST.MF @@ -59,7 +59,8 @@ Require-Bundle: org.simantics.layer0.utils;bundle-version="0.6.2", 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 diff --git a/bundles/org.simantics.sysdyn.ui/adapters.xml b/bundles/org.simantics.sysdyn.ui/adapters.xml index 24267a0f..531c4cf9 100644 --- a/bundles/org.simantics.sysdyn.ui/adapters.xml +++ b/bundles/org.simantics.sysdyn.ui/adapters.xml @@ -217,6 +217,10 @@ class="org.simantics.sysdyn.ui.browser.actions.newActions.NewExperimentAction" /> + + + class="org.simantics.sysdyn.ui.browser.actions.newActions.NewHistoryDataAction" /> + - + + + + + + + + + + + + + + + + - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ActivateExperimentAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ActivateExperimentAction.java index 4e00ace6..f99bbb53 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ActivateExperimentAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/actions/ActivateExperimentAction.java @@ -1,59 +1,59 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 = SimanticsUI.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(SimanticsUI.getSession(), project, experimentManager, experiment); - } - }); - e.consume(); - } - - } - -} +/******************************************************************************* + * 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(); + } + + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/AssignICAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/AssignICAction.java new file mode 100644 index 00000000..95dc839b --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/AssignICAction.java @@ -0,0 +1,27 @@ +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(); + } + } + }; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/AssignSymbolGroupsAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/AssignSymbolGroupsAction.java new file mode 100644 index 00000000..5c9ac515 --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/AssignSymbolGroupsAction.java @@ -0,0 +1,32 @@ +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 symbols = new HashSet<>(); + symbols.add(symbol); + AssignSymbolGroupsHandler.handleStatic(symbols); + } catch (ExecutionException e) { + e.printStackTrace(); + } + } + }; + } +} \ No newline at end of file diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenDiagramEditorFromModelAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenDiagramEditorFromModelAction.java new file mode 100644 index 00000000..48cd657e --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenDiagramEditorFromModelAction.java @@ -0,0 +1,58 @@ +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 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); + } + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenDiagramEditorFromModelDoubleClickAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenDiagramEditorFromModelDoubleClickAction.java new file mode 100644 index 00000000..8e7607db --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/OpenDiagramEditorFromModelDoubleClickAction.java @@ -0,0 +1,36 @@ +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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ShowInChartsAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ShowInChartsAction.java new file mode 100644 index 00000000..ec80690e --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/ShowInChartsAction.java @@ -0,0 +1,28 @@ +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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/ChartDropAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/ChartDropAction.java index 72d6a34d..907b9699 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/ChartDropAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/ChartDropAction.java @@ -1,180 +1,180 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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() { - SimanticsUI.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); - } -} +/******************************************************************************* + * 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/FunctionDropAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/FunctionDropAction.java index cb3e1626..01804a61 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/FunctionDropAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/drop/FunctionDropAction.java @@ -1,83 +1,83 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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() { - SimanticsUI.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); - } - - }); - } - }; - } - -} +/******************************************************************************* + * 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); + } + + }); + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportFunctionLibraryAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportFunctionLibraryAction.java new file mode 100644 index 00000000..5aba53a1 --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportFunctionLibraryAction.java @@ -0,0 +1,27 @@ +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(); + } + } + }; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportModelAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportModelAction.java new file mode 100644 index 00000000..9d908b42 --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportModelAction.java @@ -0,0 +1,28 @@ +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(); + } + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportModuleAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportModuleAction.java new file mode 100644 index 00000000..e2509832 --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/exportActions/ExportModuleAction.java @@ -0,0 +1,28 @@ +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(); + } + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/importActions/ImportFunctionLibraryAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/importActions/ImportFunctionLibraryAction.java new file mode 100644 index 00000000..9f8f804b --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/importActions/ImportFunctionLibraryAction.java @@ -0,0 +1,27 @@ +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(); + } + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/importActions/ImportModuleAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/importActions/ImportModuleAction.java new file mode 100644 index 00000000..427dbac6 --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/importActions/ImportModuleAction.java @@ -0,0 +1,28 @@ +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(); + } + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewBarChartAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewBarChartAction.java index 2e16bcec..23a64938 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewBarChartAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewBarChartAction.java @@ -1,111 +1,111 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - SimanticsUI.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.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); - } - - }); - } - }; - } - -} +/******************************************************************************* + * 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.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); + } + + }); + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewEnumerationAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewEnumerationAction.java index ffc74ba1..61bbd8b7 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewEnumerationAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewEnumerationAction.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - - SimanticsUI.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.emptyList()), - l0.PartOf, configuration); - } - }); - } - }; - } - -} +/******************************************************************************* + * 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.emptyList()), + l0.PartOf, configuration); + } + }); + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewExperimentAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewExperimentAction.java index 05f79146..af3ba154 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewExperimentAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewExperimentAction.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - - SimanticsUI.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"; - } -} +/******************************************************************************* + * 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"; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionAction.java index a76b5c17..a1bda48d 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionAction.java @@ -1,72 +1,72 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - SimanticsUI.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); - } - }); - - } - }; - } -} +/******************************************************************************* + * 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); + } + }); + + } + }; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionLibraryAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionLibraryAction.java index 031e37e9..21374f99 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionLibraryAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewFunctionLibraryAction.java @@ -1,100 +1,100 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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) { - SimanticsUI.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); - } - }); - } -} +/******************************************************************************* + * 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); + } + }); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewGameExperimentAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewGameExperimentAction.java new file mode 100644 index 00000000..fc13dd9d --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewGameExperimentAction.java @@ -0,0 +1,29 @@ +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(); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewHistoryDataAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewHistoryDataAction.java index 43f0ffac..9999e3f9 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewHistoryDataAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewHistoryDataAction.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - SimanticsUI.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); - } - }); - } - }; - } - -} +/******************************************************************************* + * 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); + } + }); + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewLineChartAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewLineChartAction.java index b21e7fcf..2b080ed1 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewLineChartAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewLineChartAction.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - SimanticsUI.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()), - 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); - } - - }); - } - }; - } - - -} +/******************************************************************************* + * 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()), + 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); + } + + }); + } + }; + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewModuleTypeAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewModuleTypeAction.java index 1d503d02..b15bcfa2 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewModuleTypeAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewModuleTypeAction.java @@ -1,144 +1,145 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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() { - SimanticsUI.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, 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; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewPieChartAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewPieChartAction.java index 1ae83a6a..de823b9b 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewPieChartAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewPieChartAction.java @@ -1,90 +1,90 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - SimanticsUI.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.emptyList()) - ); - - // Plot - GraphUtils.create2(graph, jfree.PiePlot, - l0.HasName, "PiePlot" + UUID.randomUUID().toString(), - l0.PartOf, jfreechart, - l0.ConsistsOf, dataset - ); - } - - }); - } - }; - } - -} +/******************************************************************************* + * 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.emptyList()) + ); + + // Plot + GraphUtils.create2(graph, jfree.PiePlot, + l0.HasName, "PiePlot" + UUID.randomUUID().toString(), + l0.PartOf, jfreechart, + l0.ConsistsOf, dataset + ); + } + + }); + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSensitivityAnalysisExperimentAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSensitivityAnalysisExperimentAction.java new file mode 100644 index 00000000..835b006e --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSensitivityAnalysisExperimentAction.java @@ -0,0 +1,29 @@ +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(); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSensitivityChartAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSensitivityChartAction.java new file mode 100644 index 00000000..73b94fcd --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSensitivityChartAction.java @@ -0,0 +1,28 @@ +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(); + } + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSheetAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSheetAction.java index e579df6c..8ea14324 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSheetAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSheetAction.java @@ -1,51 +1,51 @@ -/******************************************************************************* - * 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.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.sysdyn.utils.SheetUtils; -import org.simantics.ui.SimanticsUI; - -/** - * 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() { - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - SheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50}); - } - - }); - } - }; - } - -} +/******************************************************************************* + * 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}); + } + + }); + } + }; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSimulationPlaybackExperimentAction.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSimulationPlaybackExperimentAction.java index b0363b95..d70c4aee 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSimulationPlaybackExperimentAction.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/newActions/NewSimulationPlaybackExperimentAction.java @@ -1,55 +1,45 @@ -/******************************************************************************* - * 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.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 simulation playback experiment - * @author Teemu Lempinen - * - */ -public class NewSimulationPlaybackExperimentAction extends NewExperimentAction { - - protected 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); - } - - protected Resource getExperimentType(ReadGraph g) { - return SysdynResource.getInstance(g).PlaybackExperiment; - } - - protected String getNameSuggestion() { - return "Playback Experiment"; - } - -} +/******************************************************************************* + * 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(); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleSymbolRemover.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleSymbolRemover.java new file mode 100644 index 00000000..1b5becef --- /dev/null +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleSymbolRemover.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * 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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleTypeRemover.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleTypeRemover.java deleted file mode 100644 index e21bd811..00000000 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/actions/remove/ModuleTypeRemover.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2012 Association for Decentralized Information Management in - * Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.sysdyn.ui.browser.actions.remove; - -import java.util.Map; - -import org.simantics.db.ReadGraph; -import org.simantics.db.Resource; -import org.simantics.db.WriteGraph; -import org.simantics.db.exception.DatabaseException; -import org.simantics.db.layer0.adapter.Remover; -import org.simantics.modeling.ui.modelBrowser.handlers.DeleteNodeHandler; - -/** - * Remover for module type nodes. Not functioning - {@link DeleteNodeHandler} prevents deleting other than entityNodes - * - * @author Teemu Lempinen - * - */ -public class ModuleTypeRemover implements Remover { - - private Resource resource; - - public ModuleTypeRemover(ReadGraph graph, Resource resource) { - this.resource = resource; - } - - @Override - public String canRemove(ReadGraph graph, Map aux) throws DatabaseException { - return null; - } - - @Override - public void remove(WriteGraph graph) throws DatabaseException { - System.out.println("Delete resource " + resource); - } - -} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/ModuleTypeLabelRule.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/ModuleTypeLabelRule.java index 90d72345..dd4738ee 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/ModuleTypeLabelRule.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/ModuleTypeLabelRule.java @@ -1,32 +1,34 @@ -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 getLabel(ReadGraph graph, Object content) throws DatabaseException { - Resource symbol = (Resource)content; - Resource component = graph.getSingleObject(symbol, ModelingResources.getInstance(graph).SymbolToComponentType); - - return Collections.singletonMap(ColumnKeys.SINGLE, - NameUtils.getSafeName(graph, component) - ); - } - -} +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 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(); + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/VariableNameLabelRule.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/VariableNameLabelRule.java index 8e97b427..bb8e7dbc 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/VariableNameLabelRule.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/labelrules/VariableNameLabelRule.java @@ -1,40 +1,62 @@ -/******************************************************************************* - * 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.utils.ui.AdaptionUtils; - -public class VariableNameLabelRule implements LabelRule { - public static final ModuleTypeLabelRule INSTANCE = new ModuleTypeLabelRule(); - - @Override - public boolean isCompatible(Class contentType) { - return contentType.equals(Variable.class); - } - - @Override - public Map getLabel(ReadGraph graph, Object content) throws DatabaseException { - Variable var = AdaptionUtils.adaptToSingle(content, Variable.class); - return Collections.singletonMap(ColumnKeys.SINGLE, - var != null ? var.getName(graph) : "No variable" - ); - } - -} +/******************************************************************************* + * 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 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 ""; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AbstractChartNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AbstractChartNode.java index 0d17007c..7a511d88 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AbstractChartNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AbstractChartNode.java @@ -1,85 +1,85 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public abstract class AbstractChartNode extends AbstractNode 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 { - SimanticsUI.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); - } - - } - +/******************************************************************************* + * 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 extends AbstractNode 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationType.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationType.java index d5f3b6ba..db98eccd 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationType.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationType.java @@ -1,68 +1,67 @@ -/******************************************************************************* - * 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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class AnnotationType extends AbstractNode implements IDeletableNode, IModifiableNode { - - public AnnotationType(Resource resource) { - super(resource); - } - - @Override - public void delete() throws DeleteException { - try { - SimanticsUI.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; - } - -} +/******************************************************************************* + * 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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationValue.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationValue.java index 0f551eee..c64494c2 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationValue.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/AnnotationValue.java @@ -1,59 +1,58 @@ -/******************************************************************************* - * 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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class AnnotationValue extends AbstractNode implements IDeletableNode, IModifiableNode { - - public AnnotationValue(Resource resource) { - super(resource); - } - - @Override - public void delete() throws DeleteException { - try { - SimanticsUI.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); - } - -} +/******************************************************************************* + * 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 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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BarChartNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BarChartNode.java index 9dff79b6..f0c80007 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BarChartNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/BarChartNode.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * Bar chart node - * @author Teemu Lempinen - * - */ -public class BarChartNode extends AbstractChartNode { - - public BarChartNode(Resource data) { - super(data); - } - - - /** - * Adds a variable to this chart - * @param variable - */ - @Override - protected void addVariableToChart(final Variable variable) { - - SimanticsUI.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); - } - }); - } - -} +/******************************************************************************* + * 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 { + + 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); + } + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/EnumerationNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/EnumerationNode.java index bfa2943d..88cd7420 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/EnumerationNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/EnumerationNode.java @@ -1,112 +1,112 @@ -package org.simantics.sysdyn.ui.browser.nodes; - -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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class EnumerationNode extends VariableNode 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 = SimanticsUI.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 { - SimanticsUI.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); - } - } - -} +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 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); + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentNode.java index e059b644..5b0516b7 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExperimentNode.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.ErrorLogger; -import org.simantics.utils.ui.ExceptionUtils; - -public class ExperimentNode extends AbstractNode implements IDoubleClickableNode, IDeletableNode, IModifiableNode{ - - public ExperimentNode(Resource resource) { - super(resource); - } - - @Override - public boolean handleDoubleClick() { - if (data == null) - return false; - IProject project = SimanticsUI.getProject(); - IExperimentManager experimentManager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); - if (experimentManager == null) { - ErrorLogger.defaultLogWarning("Experiment manager not available.", new Exception()); - return false; - } - SysdynExperimentActivator.scheduleActivation(SimanticsUI.getSession(), project, experimentManager, data); - return true; - } - - @Override - public Modifier getModifier(String columnId) { - LabelModifier modifier = new LabelModifier(SimanticsUI.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 { - SimanticsUI.getSession().syncRequest(new WriteRequest() { - @Override - public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException { - Collection results = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_result); - if(results != null) - for(Resource result : results) - SimulationResultNode.unlinkResult(graph, result); - Collection 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); - } - } - -} +/******************************************************************************* + * 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 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 results = graph.getObjects(data, SysdynResource.getInstance(graph).Experiment_result); + if(results != null) + for(Resource result : results) + SimulationResultNode.unlinkResult(graph, result); + Collection 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); + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExportTester.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExportTester.java index dad1cd44..6921dbff 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExportTester.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ExportTester.java @@ -1,92 +1,92 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 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 = SimanticsUI.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() { - @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; - } - } - -} +/******************************************************************************* + * 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 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() { + @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; + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionLibraryNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionLibraryNode.java index 8813df95..9dcbfd68 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionLibraryNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/FunctionLibraryNode.java @@ -1,104 +1,103 @@ -/******************************************************************************* - * 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.SimanticsUI; -import org.simantics.ui.utils.ResourceAdaptionUtils; - -public class FunctionLibraryNode extends AbstractNode implements IDeletableNode, IModifiableNode, IDropTargetNode { - - - public FunctionLibraryNode(Resource resource) { - super(resource); - } - - @Override - public Modifier getModifier(String columnId) { - try { - Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName; - LabelModifier modifier = new LabelModifier(SimanticsUI.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 { - SimanticsUI.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); - } - } - } - }); - } - } - -} +/******************************************************************************* + * 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 extends AbstractNode 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); + } + } + } + }); + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/HistoryDataNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/HistoryDataNode.java index 196a52ef..70cc037c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/HistoryDataNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/HistoryDataNode.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class HistoryDataNode extends SimulationResultNode { - - public HistoryDataNode(Resource resource) { - super(resource); - } - - @Override - public void delete() throws DeleteException { - try { - SimanticsUI.getSession().syncRequest(new WriteRequest() { - @Override - public void perform(WriteGraph graph) throws DatabaseException, CancelTransactionException { - RemoverUtil.remove(graph, data); - } - }); - } catch (DatabaseException e) { - ExceptionUtils.logAndShowError(e); - } - - } -} +/******************************************************************************* + * 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 { + + 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); + } + + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialCondition.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialCondition.java index dcd937a5..51a2ea0c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialCondition.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/InitialCondition.java @@ -1,58 +1,58 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class InitialCondition extends AbstractNode implements IDeletableNode, IModifiableNode { - - public InitialCondition(Resource resource) { - super(resource); - } - - @Override - public void delete() throws DeleteException { - try { - SimanticsUI.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 = SimanticsUI.getSession(); - return new LabelModifier(session, data, session.getService(Layer0.class).HasName); - } - -} +/******************************************************************************* + * 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 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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/Library.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/Library.java index 736081eb..47c73728 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/Library.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/Library.java @@ -1,59 +1,58 @@ -/******************************************************************************* - * 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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class Library extends AbstractNode implements IDeletableNode, IModifiableNode { - - public Library(Resource resource) { - super(resource); - } - - @Override - public void delete() throws DeleteException { - try { - SimanticsUI.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); - } - -} +/******************************************************************************* + * 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 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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/LineChartNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/LineChartNode.java index ef2ec492..e377dd32 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/LineChartNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/LineChartNode.java @@ -1,76 +1,76 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * Node representing a line chart - * @author Teemu Lempinen - * - */ -public class LineChartNode extends AbstractChartNode { - - 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) { - - SimanticsUI.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); - } - }); - } - -} +/******************************************************************************* + * 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 { + + 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); + } + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModelNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModelNode.java index 13971866..ba7e13b2 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModelNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModelNode.java @@ -1,160 +1,159 @@ -/******************************************************************************* - * 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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class ModelNode extends AbstractNode implements IDoubleClickableNode, IDeletableNode, IModifiableNode { - - Listener configurationNameSynchronizer; - private boolean disposed = false; - - public ModelNode(Resource resource) { - super(resource); - - // Not the best solution for name sync - configurationNameSynchronizer = new Listener() { - - @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; - } - }; - - SimanticsUI.getSession().asyncRequest(new Read() { - - @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(SimanticsUI.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 { - SimanticsUI.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; - } - -} +/******************************************************************************* + * 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 implements IDoubleClickableNode, IDeletableNode, IModifiableNode { + + Listener configurationNameSynchronizer; + private boolean disposed = false; + + public ModelNode(Resource resource) { + super(resource); + + // Not the best solution for name sync + configurationNameSynchronizer = new Listener() { + + @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() { + + @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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleNode.java index 297124a0..234b0d5e 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleNode.java @@ -1,114 +1,114 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class ModuleNode extends ConfigurationNode implements IModifiableNode { - - Resource configuration; - - public ModuleNode(Resource resource) { - super(resource); - - - SimanticsUI.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); - - SimanticsUI.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 = SimanticsUI.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; - } -} +/******************************************************************************* + * 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 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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleTypeNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleTypeNode.java index 06e93bd0..25ab0aa0 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleTypeNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/ModuleTypeNode.java @@ -1,216 +1,216 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class ModuleTypeNode extends AbstractNode implements IDeletableNode, IModifiableNode { - - - Listener configurationNameSynchronizer; - private boolean disposed = false; - private Resource configuration; - - public ModuleTypeNode(Resource resource) { - super(resource); - - SimanticsUI.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() { - - @Override - public void execute(final String result) { - if(result == null) - return; - - SimanticsUI.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; - } - }; - - SimanticsUI.getSession().asyncRequest(new Read() { - - @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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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(SimanticsUI.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 { - SimanticsUI.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 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); - } -} +/******************************************************************************* + * 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 implements IDeletableNode, IModifiableNode { + + + Listener 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() { + + @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() { + + @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() { + + @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 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/PieChartNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/PieChartNode.java index 776cbdb0..d00d9089 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/PieChartNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/PieChartNode.java @@ -1,68 +1,68 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * Node for pie charts - * @author Teemu Lempinen - * - */ -public class PieChartNode extends AbstractChartNode { - - public PieChartNode(Resource data) { - super(data); - } - - /** - * Adds a variable to this chart - * @param variable - */ - @Override - protected void addVariableToChart(final Variable variable) { - SimanticsUI.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); - } - }); - } - -} +/******************************************************************************* + * 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 { + + 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); + } + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java index 9307287e..116bd33d 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SCLModule.java @@ -1,61 +1,61 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class SCLModule extends AbstractNode implements IDeletableNode, IModifiableNode { - - public SCLModule(Resource resource) { - super(resource); - } - - @Override - public void delete() throws DeleteException { - try { - SimanticsUI.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 = SimanticsUI.getSession(); - return new LabelModifier(session, data, session.getService(Layer0.class).HasName); - } - -} +/******************************************************************************* + * 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 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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SheetNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SheetNode.java index 39fdb224..01be7fdd 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SheetNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SheetNode.java @@ -1,83 +1,83 @@ -package org.simantics.sysdyn.ui.browser.nodes; - -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -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.SimanticsUI; -import org.simantics.ui.workbench.ResourceEditorInput2; -import org.simantics.utils.ui.workbench.WorkbenchUtils; - -public class SheetNode extends AbstractNode implements IModifiableNode, IDoubleClickableNode { - - public SheetNode(Resource data) { - super(data); - } - - @Override - public Modifier getModifier(String columnId) { - - Session session = SimanticsUI.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 { - - SimanticsUI.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; - } - - -} +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 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; + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultNode.java index bc9c4a3f..c62b7b8f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultNode.java @@ -1,95 +1,95 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class SimulationResultNode extends AbstractNode implements IDoubleClickableNode, IDeletableNode, IModifiableNode { - - public SimulationResultNode(Resource resource) { - super(resource); - } - - - @Override - public Modifier getModifier(String columnId) { - LabelModifier modifier = new LabelModifier(SimanticsUI.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 { - SimanticsUI.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; - } -} +/******************************************************************************* + * 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 extends AbstractNode 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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultSetNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultSetNode.java index 194e1c9e..57f09367 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultSetNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/SimulationResultSetNode.java @@ -1,84 +1,84 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.ExceptionUtils; - -public class SimulationResultSetNode extends AbstractNode implements IDoubleClickableNode, IDeletableNode, IModifiableNode { - - public SimulationResultSetNode(Resource resource) { - super(resource); - } - - - @Override - public Modifier getModifier(String columnId) { - LabelModifier modifier = new LabelModifier(SimanticsUI.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 { - SimanticsUI.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; - } -} +/******************************************************************************* + * 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 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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/VariableNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/VariableNode.java index fdfcb134..fddffdef 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/VariableNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/nodes/VariableNode.java @@ -1,88 +1,88 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class VariableNode extends AbstractNode 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 = SimanticsUI.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; - } -} +/******************************************************************************* + * 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 extends AbstractNode 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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromConfigurationAdapter.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromConfigurationAdapter.java index 8fe5d1dd..cd5b24f9 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromConfigurationAdapter.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/OpenDiagramFromConfigurationAdapter.java @@ -1,121 +1,116 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 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 { - - SimanticsUI.getSession().asyncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph g) 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(); -// System.out.println("Activating diagram: model=" + modelURI + " rvi='" + rvi + "'"); - WorkbenchUtils.openEditor(editorId, new ResourceEditorInput2(editorId, diagram, model, rvi)); - } catch (PartInitException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - }); - - } - - }); - - } -} +/******************************************************************************* + * 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(); + } + } + }); + + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorInput.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorInput.java index 7e317c6b..e0a56d44 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorInput.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/SysdynEditorInput.java @@ -1,387 +1,386 @@ -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.db.ReadGraph; -import org.simantics.db.RequestProcessor; -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.SimanticsUI; -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 = SimanticsUI.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, - * null 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 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) - */ - @SuppressWarnings("rawtypes") - @Override - public Object getAdapter(Class 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(RequestProcessor processor, boolean sync) throws DatabaseException { - ReadRequest req = new ReadRequest() { - @Override - public void run(ReadGraph g) throws DatabaseException { - update(g); - } - }; - if (sync) { - processor.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 + "]"; - } - - - -} +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, + * null 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 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 getAdapter(Class 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 + "]"; + } + + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/CreateVariablesShortcutParticipant.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/CreateVariablesShortcutParticipant.java index 0fc30199..1c5f40be 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/CreateVariablesShortcutParticipant.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/CreateVariablesShortcutParticipant.java @@ -1,334 +1,334 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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() { - @Override - public void accept(DiagramMutator m) { - - Resource r; - try { - r = SimanticsUI - .getSession() - .syncRequest( - Queries - .resource(variableInformation.symbolURI)); - ElementClass ec = SimanticsUI.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 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; - } - -} +/******************************************************************************* + * 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() { + @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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SelectionUpdaterParticipant.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SelectionUpdaterParticipant.java index 023c78ce..8c2947ed 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SelectionUpdaterParticipant.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SelectionUpdaterParticipant.java @@ -1,96 +1,96 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 elements = AdaptionUtils.adaptToCollection(newValue, IElement.class); - if(diagram != null) { - Session session = SimanticsUI.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 = SimanticsUI.getSession(); - session.asyncRequest(new ModifyDiagramSelection(session.getService(VirtualGraph.class), diagram, null)); - } - } - - - private class ModifyDiagramSelection extends WriteRequest { - IDiagram diagram; - Collection elements; - - public ModifyDiagramSelection(VirtualGraph provider, IDiagram diagram, Collection 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); - } - } - } - } - } -} +/******************************************************************************* + * 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 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 elements; + + public ModifyDiagramSelection(VirtualGraph provider, IDiagram diagram, Collection 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); + } + } + } + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectTool.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectTool.java index f4faa9fd..1903d60a 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectTool.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/editor/participant/SysdynConnectTool.java @@ -1,468 +1,468 @@ -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.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.ui.SimanticsUI; -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 terminals = new ArrayList(); - 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 toSegments(Deque points) { - if (points.isEmpty()) - return Collections.emptyList(); - - List segments = new ArrayList(); - - Iterator 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 segments = toSegments(controlPoints); - //System.out.println("controlpoints: " + controlPoints); - //System.out.println("segments: " + segments); - router.route(new SysdynConnection() { - @Override - public Collection 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 SimanticsUI.getSession().syncRequest(new Read() { - - @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 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 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 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 controlPoints = this.controlPoints; - final TerminalInfo startTerminal = this.startTerminal; - final TerminalInfo endTerminal = this.endTerminal; - - SimanticsUI.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); - }); - } -} +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 terminals = new ArrayList(); + 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 toSegments(Deque points) { + if (points.isEmpty()) + return Collections.emptyList(); + + List segments = new ArrayList(); + + Iterator 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 segments = toSegments(controlPoints); + //System.out.println("controlpoints: " + controlPoints); + //System.out.println("segments: " + segments); + router.route(new SysdynConnection() { + @Override + public Collection 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() { + + @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 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 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 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 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); + }); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopFactory.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopFactory.java index 6dd76892..56d433bc 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopFactory.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopFactory.java @@ -1,380 +1,380 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 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 Consumer getCallback(final IElement e, G2DParentNode parent, Class nodeClass) { - return new Consumer() { - @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; - SimanticsUI.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 { - SimanticsUI.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); - } - }); - } - }; - } - - } - - -} +/******************************************************************************* + * 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 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 Consumer getCallback(final IElement e, G2DParentNode parent, Class nodeClass) { + return new Consumer() { + @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); + } + }); + } + }; + } + + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopNode.java index 57289682..e7d21c59 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/LoopNode.java @@ -1,241 +1,241 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 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 children = diagramNode.getNodes(); - Iterator 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 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 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 getAllLoopItems() { - IElement loopElement = DiagramNodeUtil.getElement(this); - final Resource loopSymbolResource = loopElement.getHint(ElementHints.KEY_OBJECT); - List loopItems = Collections.emptyList(); - - try { - loopItems = SimanticsUI.getSession().syncRequest(new Read>(){ - - @Override - public List 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 loopItems = ListUtils.toPossibleList(graph, loopResource); - if (loopItems == null) - return Collections.emptyList(); - - ArrayList dependencyItems = new ArrayList(); - - // Add dependencies and flows. - for (int i = 0; i < loopItems.size(); ++i) { - boolean skipBackwardFlows = false; - - // Go through forward dependencies and flows - Collection forwardDependencies = graph.getObjects(loopItems.get(i), sr.Variable_isTailOf); - - // And also through the forward dependencies of possible shadows. - Collection 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 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; - } - -} +/******************************************************************************* + * 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 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 children = diagramNode.getNodes(); + Iterator 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 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 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 getAllLoopItems() { + IElement loopElement = DiagramNodeUtil.getElement(this); + final Resource loopSymbolResource = loopElement.getHint(ElementHints.KEY_OBJECT); + List loopItems = Collections.emptyList(); + + try { + loopItems = Simantics.getSession().syncRequest(new Read>(){ + + @Override + public List 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 loopItems = ListUtils.toPossibleList(graph, loopResource); + if (loopItems == null) + return Collections.emptyList(); + + ArrayList dependencyItems = new ArrayList(); + + // Add dependencies and flows. + for (int i = 0; i < loopItems.size(); ++i) { + boolean skipBackwardFlows = false; + + // Go through forward dependencies and flows + Collection forwardDependencies = graph.getObjects(loopItems.get(i), sr.Variable_isTailOf); + + // And also through the forward dependencies of possible shadows. + Collection 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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceDialogRunnable.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceDialogRunnable.java index 6e1f7de9..54d735bb 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceDialogRunnable.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/ShadowVariableReferenceDialogRunnable.java @@ -1,53 +1,53 @@ -/******************************************************************************* - * 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.db.Resource; -import org.simantics.ui.SimanticsUI; - -public class ShadowVariableReferenceDialogRunnable implements Runnable { - - private Resource shadow; - private HashMap possibleReferences; - - public ShadowVariableReferenceDialogRunnable(Resource shadow, HashMap 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]); - - SimanticsUI.getSession().asyncRequest(new ShadowVariableReferenceRequest(shadow, resource)); - } -} +/******************************************************************************* + * 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 possibleReferences; + + public ShadowVariableReferenceDialogRunnable(Resource shadow, HashMap 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)); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementNoBounds.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementNoBounds.java index 276bc066..b557586b 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementNoBounds.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/SysdynTextElementNoBounds.java @@ -1,318 +1,318 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 Consumer getCallback(final IElement e, G2DParentNode parent, Class nodeClass) { - return new Consumer() { - @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; - SimanticsUI.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) { - SimanticsUI.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 { - SimanticsUI.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); - } - -} +/******************************************************************************* + * 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 Consumer getCallback(final IElement e, G2DParentNode parent, Class nodeClass) { + return new Consumer() { + @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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowConnectionStyle.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowConnectionStyle.java index a7476de6..b04a138c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowConnectionStyle.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/FlowConnectionStyle.java @@ -1,97 +1,97 @@ -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.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; -import org.simantics.ui.SimanticsUI; - -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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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; - } - -} +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() { + + @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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowConnectionFactory.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowConnectionFactory.java index 517a696e..39f8d127 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowConnectionFactory.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/connections/RouteFlowConnectionFactory.java @@ -1,718 +1,626 @@ -/******************************************************************************* - * 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 java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.atomic.AtomicInteger; - -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.db.procedure.SyncMultiProcedure; -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 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(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 nodes = new HashSet(); - Set links = new HashSet(); - Map nodeByData = new HashMap(); - - // Needed to support ConnectionEntity#getTerminalConnections - Set backendonnections = new HashSet(); - - // 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. 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); - } - }); - - // A complicated-looking procedure for obtaining all HasProperties to properties map - final AtomicInteger ready = new AtomicInteger(1); - final ConcurrentSkipListMap> properties = new ConcurrentSkipListMap>(); - graph.forEachPredicate(connection, new SyncMultiProcedure() { - - @Override - public void exception(ReadGraph graph, Throwable throwable) { - throwable.printStackTrace(); - } - - @Override - public void execute(ReadGraph graph, final Resource property) { - - ready.incrementAndGet(); - Layer0 l0; - try { - l0 = Layer0.getInstance(graph.getSession()); - } catch (DatabaseException e) { - e.printStackTrace(); - return; - } - - graph.forIsSubrelationOf(property, l0.HasProperty, new AsyncProcedure() { - - @Override - public void exception(AsyncReadGraph graph, Throwable throwable) { - throwable.printStackTrace(); - } - - @Override - public void execute(AsyncReadGraph graph, final Boolean isProperty) { - - if(isProperty) { - - graph.forPossibleRelatedValue(connection, property, new AsyncProcedure() { - - @Override - public void exception(AsyncReadGraph graph, Throwable throwable) { - throwable.printStackTrace(); - } - - @Override - public void execute(AsyncReadGraph graph, final Object value) { - - Layer0 l0; - try { - l0 = Layer0.getInstance(graph.getSession()); - } catch (DatabaseException e) { - e.printStackTrace(); - return; - } - - graph.forPossibleRelatedValue(property, l0.HasName, Bindings.STRING, new AsyncProcedure() { - - @Override - public void exception(AsyncReadGraph graph, Throwable throwable) { - throwable.printStackTrace(); - } - - @Override - public void execute(AsyncReadGraph graph, String name) { - - properties.put(name, Pair.make(property, value)); - if(ready.decrementAndGet() == 0) { - element.setHint(DiagramHints.PROPERTIES, new HashMap>(properties)); - } - - } - - }); - - } - - }); - - - } else { - - if(ready.decrementAndGet() == 0) { - element.setHint(DiagramHints.PROPERTIES, new HashMap>(properties)); - } - - } - - } - - }); - } - - @Override - public void finished(ReadGraph graph) { - - if(ready.decrementAndGet() == 0) { - element.setHint(DiagramHints.PROPERTIES, new HashMap(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. 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 backendConnections; - - /** - * Cache. - */ - Set terminalConnections; - - - public CE(IDiagram diagram, Resource connection, IElement connectionElement, Set 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 getBranchPoints(Collection result) { - return result != null ? result : Collections. emptyList(); - } - - @Override - public Collection getSegments(Collection result) { - return result != null ? result : Collections. emptyList(); - } - - @Override - public Collection getTerminalConnections(Collection result) { - if (terminalConnections == null) - terminalConnections = calculateTerminalConnections(); - if (result == null) - result = new ArrayList(terminalConnections); - else - result.addAll(terminalConnections); - return terminalConnections; - } - - private Set calculateTerminalConnections() { - DataElementMap dem = diagram.getDiagramClass().getSingleItem(DataElementMap.class); - Set result = new HashSet(); - ArrayList ts = new ArrayList(); - 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 + "]"; - } - } - -} - +/******************************************************************************* + * 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 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(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 nodes = new HashSet(); + Set links = new HashSet(); + Map nodeByData = new HashMap(); + + // Needed to support ConnectionEntity#getTerminalConnections + Set backendonnections = new HashSet(); + + // 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. 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> 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. 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 backendConnections; + + /** + * Cache. + */ + Set terminalConnections; + + + public CE(IDiagram diagram, Resource connection, IElement connectionElement, Set 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 getBranchPoints(Collection result) { + return result != null ? result : Collections. emptyList(); + } + + @Override + public Collection getSegments(Collection result) { + return result != null ? result : Collections. emptyList(); + } + + @Override + public Collection getTerminalConnections(Collection result) { + if (terminalConnections == null) + terminalConnections = calculateTerminalConnections(); + if (result == null) + result = new ArrayList(terminalConnections); + else + result.addAll(terminalConnections); + return terminalConnections; + } + + private Set calculateTerminalConnections() { + DataElementMap dem = diagram.getDiagramClass().getSingleItem(DataElementMap.class); + Set result = new HashSet(); + ArrayList ts = new ArrayList(); + 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 + "]"; + } + } + +} + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/SimulationPlaybackStyle.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/SimulationPlaybackStyle.java index 35516ae8..28be032a 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/SimulationPlaybackStyle.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements/profiles/SimulationPlaybackStyle.java @@ -1,316 +1,316 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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> { - - 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 calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException { - - // Find SimulationPlaybackExperiment - IProject project = SimanticsUI.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 datasets = new ArrayList(); - - 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 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 colorValues = new ArrayList(); - 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(at, multiplier, cg); - - } catch(Exception ignore) { - ignore.printStackTrace(); - } - return null; - } - - @Override - public void styleResultChanged(Observer observer, Resource runtimeDiagram, Resource element, Triple 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 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; - } - - } -} +/******************************************************************************* + * 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> { + + 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 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 datasets = new ArrayList(); + + 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 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 colorValues = new ArrayList(); + 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(at, multiplier, cg); + + } catch(Exception ignore) { + ignore.printStackTrace(); + } + return null; + } + + @Override + public void styleResultChanged(Observer observer, Resource runtimeDiagram, Resource element, Triple 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 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; + } + + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/AssignIC.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/AssignIC.java index 16bb242b..0c51cdf3 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/AssignIC.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/AssignIC.java @@ -1,116 +1,122 @@ -/******************************************************************************* - * 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 { - - private Resource query(Resource experiment) throws DatabaseException { - - Map> map = Simantics.getSession().syncRequest(new ResourceRead>>(experiment) { - - @Override - public Map> perform(ReadGraph graph) throws DatabaseException { - Map> result = new HashMap>(); - 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(name, null)); - } - return result; - } - - }); - - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); - ResourceSelectionDialog3 dialog = new ResourceSelectionDialog3(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; - - } - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - - ISelection selection = HandlerUtil.getCurrentSelection(event); - final Resource experiment = ResourceAdaptionUtils.toSingleResource(selection); - if (experiment == null) - return null; - - 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; - } -} +/******************************************************************************* + * 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> map = Simantics.getSession().syncRequest(new ResourceRead>>(experiment) { + + @Override + public Map> perform(ReadGraph graph) throws DatabaseException { + Map> result = new HashMap>(); + 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(name, null)); + } + return result; + } + + }); + + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + ResourceSelectionDialog3 dialog = new ResourceSelectionDialog3(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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DisposeExperiment.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DisposeExperiment.java index 45c3ef94..4381c40e 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DisposeExperiment.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/DisposeExperiment.java @@ -1,38 +1,38 @@ -/******************************************************************************* - * 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.project.IProject; -import org.simantics.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.ui.utils.HandlerUtils; -import org.simantics.ui.SimanticsUI; - -public class DisposeExperiment extends AbstractHandler { - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - HandlerUtils.saveBeforeExperimentRun(event); - - IProject project = SimanticsUI.getProject(); - IExperimentManager manager = - project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); - IExperiment experiment = manager.getActiveExperiment(); - if (experiment != null) - experiment.shutdown(null); - return null; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java index f77b693f..7a218377 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewAnnotationTypeHandler.java @@ -1,51 +1,51 @@ -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.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.ui.SimanticsUI; -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 node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); - if (node == null) - return null; - res = node.data; - } - - final Resource parent = res; - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - AnnotationUtils.newAnnotationType(graph, parent); - } - - }); - - return null; - - } - -} +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 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; + + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java index 0f20af7d..cf31f285 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewLibraryHandler.java @@ -1,48 +1,48 @@ -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.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.ui.SimanticsUI; -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 node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); - if (node == null) - return null; - res = node.data; - } - - final Resource parent = res; - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - NewLibrary.createLibrary(graph, parent); - } - - }); - - return null; - - } - -} +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 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; + + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewSCLModuleHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewSCLModuleHandler.java index 459079a9..e1e80ad4 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewSCLModuleHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/NewSCLModuleHandler.java @@ -1,51 +1,51 @@ -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.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.ui.SimanticsUI; -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 node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); - if (node == null) - return null; - res = node.data; - } - - final Resource parent = res; - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - ModelingUtils.createSCLModuleDefault(graph, parent); - } - - }); - - return null; - - } - -} +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 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; + + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RemoveNodeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RemoveNodeHandler.java index e2ee3669..ed57e0c6 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RemoveNodeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RemoveNodeHandler.java @@ -1,67 +1,67 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 { - SimanticsUI.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); - } - } - +/******************************************************************************* + * 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java index 1eba038f..c81690c2 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/RunBasicExperiment.java @@ -1,61 +1,61 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -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 = - SimanticsUI.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 = - SimanticsUI.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); - } - } - } -} +/******************************************************************************* + * 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); + } + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveResultsHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveResultsHandler.java index 616f835c..5065fd01 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveResultsHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SaveResultsHandler.java @@ -1,38 +1,38 @@ -/******************************************************************************* - * 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.simulation.experiment.IDynamicExperiment; -import org.simantics.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.ui.utils.HandlerUtils; -import org.simantics.ui.SimanticsUI; - -public class SaveResultsHandler extends AbstractHandler { - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - HandlerUtils.saveBeforeExperimentRun(event); - - IExperimentManager manager = - SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); - IExperiment experiment = manager.getActiveExperiment(); - if(experiment instanceof IDynamicExperiment) { - ((IDynamicExperiment)experiment).saveState(); - } - return null; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ShowModuleHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ShowModuleHandler.java index 0514909f..ceb39d2a 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ShowModuleHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ShowModuleHandler.java @@ -1,115 +1,115 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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; - - SimanticsUI.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; - } - - -} +/******************************************************************************* + * 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; + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SynthesisSimulation.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SynthesisSimulation.java index 00f12bb6..01da8b2f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SynthesisSimulation.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SynthesisSimulation.java @@ -1,87 +1,87 @@ -/******************************************************************************* - * 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.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.manager.SysdynExperiment; -import org.simantics.sysdyn.ui.utils.HandlerUtils; -import org.simantics.ui.SimanticsUI; - -/** - * @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 = - SimanticsUI.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); - } -} +/******************************************************************************* + * 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SysdynExperimentActivator.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SysdynExperimentActivator.java index 4b13c46c..70604669 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SysdynExperimentActivator.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/SysdynExperimentActivator.java @@ -1,194 +1,194 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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() { - @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 problem = new DataContainer(); - 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 = SimanticsUI.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(SimanticsUI.getSession(), project, experimentManager, experiment); - return null; - } - -} +/******************************************************************************* + * 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() { + @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 problem = new DataContainer(); + 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultActivation.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultActivation.java index 024c6cbc..ad55b409 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultActivation.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultActivation.java @@ -1,64 +1,70 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -import org.simantics.ui.utils.ResourceAdaptionUtils; - -public class ToggleResultActivation 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 { - SimanticsUI.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) { - - } - } -} +/******************************************************************************* + * 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(); + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultSetActivation.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultSetActivation.java index a667a8c0..2bde3c70 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultSetActivation.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleResultSetActivation.java @@ -1,76 +1,76 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 { - SimanticsUI.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 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) { - - } - } -} +/******************************************************************************* + * 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 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) { + + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleSimulation.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleSimulation.java index 351f9c4f..17ead809 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleSimulation.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/ToggleSimulation.java @@ -1,84 +1,84 @@ -/******************************************************************************* - * 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.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.manager.SysdynExperiment; -import org.simantics.sysdyn.ui.utils.HandlerUtils; -import org.simantics.ui.SimanticsUI; - -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 = - SimanticsUI.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); - } -} +/******************************************************************************* + * 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportExternalFunctionFilesHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportExternalFunctionFilesHandler.java index fe9d1934..2df60b78 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportExternalFunctionFilesHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportExternalFunctionFilesHandler.java @@ -1,97 +1,97 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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; - } - - SimanticsUI.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; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java index 251ab7a4..3569e0d6 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java @@ -1,115 +1,124 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -import org.simantics.ui.utils.ResourceAdaptionUtils; - -/** - * Exports a function library - * - * @author Teemu Lempinen - * @author Tuomas Miettinen - * - */ -public class ExportFunctionLibrary extends AbstractHandler { - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - - ISelection sel = HandlerUtil.getCurrentSelection(event); - final Resource functionLibrary = ResourceAdaptionUtils.toSingleResource(sel); - if(functionLibrary == null) return null; - - String name = null; - try { - name = SimanticsUI.getSession().syncRequest(new Read() { - - @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(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; - - // Find a location (and name) for the exported library using FileDialog - Shell shell = HandlerUtil.getActiveShellChecked(event); - 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 - SimanticsUI.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; - } - -} +/******************************************************************************* + * 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() { + + @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(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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelAsButtonHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelAsButtonHandler.java index 8e631842..d38e5422 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelAsButtonHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelAsButtonHandler.java @@ -1,49 +1,51 @@ -/******************************************************************************* - * 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.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; - - String selected = getAbsolutePath(model, event, true); - - if (selected != null) { - createFile(model, selected); - setExportStatus(model, selected); - } - - return null; - } - -} - +/******************************************************************************* + * 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; + } + +} + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelButtonHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelButtonHandler.java index 9954ae65..68001177 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelButtonHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelButtonHandler.java @@ -1,122 +1,124 @@ -/******************************************************************************* - * 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.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.handlers.HandlerUtil; -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.SimanticsUI; -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; - - String selected = getAbsolutePath(model, event, 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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; - } - -} - +/******************************************************************************* + * 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() { + + @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; + } + +} + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java index 78e893d2..8e6596cf 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java @@ -1,291 +1,273 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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; - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - - status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) ); - - final Resource model = determineModel(event); - if (model == null) - return null; - - String selected = getAbsolutePath(model, event, true); - - 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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(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); - } - -// // Asynchronously create the file using transferable graph -// SimanticsUI.getSession().asyncRequest(new ReadRequest() { -// -// @Override -// public void run(ReadGraph graph) throws DatabaseException { -// HashMap map = new HashMap(); -// -// Resource relation = graph.getPossibleResource("http://www.simantics.org/Documentation-1.1/createdBy"); -// if(relation != null) { -// Resource createdBy = graph.getPossibleObject(model, relation); -// if(createdBy != null) -// map.put(createdBy, ExtentStatus.EXCLUDED); -// } -// -// TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, model); -// conf.preStatus.putAll(map); -// -// TransferableGraphSource s = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf)); -// try { -// TransferableGraphs.writeTransferableGraph(graph, "sysdynModel", 1, s,new File(fileName)); -// } catch (Exception e) { -// ExceptionUtils.logAndShowError("Model Export Failed", "Sysdyn model export failed, see exception for details", e); -// -// File modelFile = new File(fileName); -// if (modelFile.exists()) -// modelFile.delete(); -// } -// } -// }); - } - - /** - * 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, ExecutionEvent event, boolean saveAs) throws ExecutionException { - - // Determine the default path. - String path = null; - try { - //If the model has been exported earlier, use that path. - path = SimanticsUI.getSession().syncRequest(new Read() { - - @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(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, event, 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, event, 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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(model, SR.SysdynModel_lastExportFileName, Bindings.STRING )); - if (name == null) { - // If not, use the model name. - name = graph.syncRequest(new PossibleRelatedValue(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 - Shell shell = HandlerUtil.getActiveShellChecked(event); - 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 { - SimanticsUI.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); - } - -} +/******************************************************************************* + * 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() { + + @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(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() { + + @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(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() { + + @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(model, SR.SysdynModel_lastExportFileName, Bindings.STRING )); + if (name == null) { + // If not, use the model name. + name = graph.syncRequest(new PossibleRelatedValue(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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java index 6a0cc12f..380b1de3 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java @@ -1,276 +1,286 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -import org.simantics.ui.utils.ResourceAdaptionUtils; -import org.simantics.utils.datastructures.Pair; - -/** - * 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 dependencies; - - ContainsDependenciesException(Collection dependencies) { - this.dependencies = dependencies; - } - - public Collection getDependencies() { - return this.dependencies; - } - - } - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - - ISelection sel = HandlerUtil.getCurrentSelection(event); - final Resource modulesymbol = ResourceAdaptionUtils.toSingleResource(sel); - if(modulesymbol == null) return null; - - String name = null; - try { - name = SimanticsUI.getSession().syncRequest(new Read() { - - @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 dependencies = null; - for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) { - if(dependencies == null) - dependencies = new ArrayList(); - 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) { - Shell shell = HandlerUtil.getActiveShellChecked(event); - 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 - Shell shell = HandlerUtil.getActiveShellChecked(event); - 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 - SimanticsUI.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(component, l0.HasName, Bindings.STRING )); - final ArrayList> roots = new ArrayList>(); - 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> 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> replacements = new ArrayList>(); - - 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(enumeration, replacement)); - } - } - } - - for(Pair replacement : replacements) - graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second); - - SimanticsUI.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 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(); - } - } +/******************************************************************************* + * 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 dependencies; + + ContainsDependenciesException(Collection dependencies) { + this.dependencies = dependencies; + } + + public Collection 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() { + + @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 dependencies = null; + for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) { + if(dependencies == null) + dependencies = new ArrayList(); + 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(component, l0.HasName, Bindings.STRING )); + final ArrayList> roots = new ArrayList>(); + 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> 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> replacements = new ArrayList>(); + + 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(enumeration, replacement)); + } + } + } + + for(Pair 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 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/ReloadGameExperimentHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/ReloadGameExperimentHandler.java index 218512cd..fedf9d93 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/ReloadGameExperimentHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/ReloadGameExperimentHandler.java @@ -1,106 +1,106 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 = SimanticsUI.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"); - } - } - -} +/******************************************************************************* + * 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"); + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/StepHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/StepHandler.java index ecb69ef5..ecc16637 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/StepHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/game/StepHandler.java @@ -1,108 +1,108 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 = SimanticsUI.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"); - } - } -} +/******************************************************************************* + * 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"); + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportExternalFunctionFilesHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportExternalFunctionFilesHandler.java index 50277c1c..26e070f4 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportExternalFunctionFilesHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportExternalFunctionFilesHandler.java @@ -1,120 +1,120 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 selected = importFiles(shell, "Import...", C_EXTENSIONS); - if(selected.second == null || selected.second.length < 1) return null; - - SimanticsUI.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 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(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 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(); - } - - } - - } - -} +/******************************************************************************* + * 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 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 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(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 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(); + } + + } + + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java index 4e227e73..821d75c6 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java @@ -1,88 +1,101 @@ -/******************************************************************************* - * 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; - -/** - * Imports an exported function library (or shared function library) transferable graph. - * @author Teemu Lempinen - * - */ -public class ImportFunctionLibrary extends AbstractHandler { - - /** - * 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; - - - // Get a transferable graph file - Shell shell = HandlerUtil.getActiveShellChecked(event); - 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; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportMdlHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportMdlHandler.java index a42b66b0..a2f89c8d 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportMdlHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportMdlHandler.java @@ -1,89 +1,89 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 = SimanticsUI.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; - } - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - @Override - public void perform(WriteGraph graph) throws DatabaseException { - model.write(graph, project, new WriteContext()); - } - }); - - return null; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java index 19c40314..3e51c803 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java @@ -1,83 +1,99 @@ -/******************************************************************************* - * 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; - -/** - * Imports modules from exported transferable graph files. - * - * @author Teemu Lempinen - * - */ -public class ImportModuleHandler extends AbstractHandler { - - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - ISelection sel = HandlerUtil.getCurrentSelection(event); - - @SuppressWarnings("unchecked") - AbstractNode 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); - 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; - } - -} +/******************************************************************************* + * 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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewBarChartHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewBarChartHandler.java index 1e342142..dd26eacf 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewBarChartHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewBarChartHandler.java @@ -1,115 +1,115 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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; - - SimanticsUI.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.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; - } - -} +/******************************************************************************* + * 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.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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewEnumerationNodeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewEnumerationNodeHandler.java index 81128020..ddeddaf2 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewEnumerationNodeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewEnumerationNodeHandler.java @@ -1,91 +1,91 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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); - - SimanticsUI.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()), - l0.PartOf, configuration); - Layer0Utils.addCommentMetadata(g, "Created new Enumeration " + name + " to " + g.getRelatedValue2(configuration, l0.HasLabel, Bindings.STRING)); - } - }); - return null; - } - -} +/******************************************************************************* + * 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()), + l0.PartOf, configuration); + Layer0Utils.addCommentMetadata(g, "Created new Enumeration " + name + " to " + g.getRelatedValue2(configuration, l0.HasLabel, Bindings.STRING)); + } + }); + return null; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewExperimentNodeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewExperimentNodeHandler.java index ddfc2b1d..e5dd508f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewExperimentNodeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewExperimentNodeHandler.java @@ -1,101 +1,101 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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; - - SimanticsUI.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 - */ - 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"; - } - -} +/******************************************************************************* + * 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"; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionHandler.java index e048657c..c65c24f0 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionHandler.java @@ -1,90 +1,90 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 node = AdaptionUtils.adaptToSingle(sel, AbstractNode.class); - if (node == null) - return null; - - final Resource data = node.data; - - SimanticsUI.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; - } - - -} +/******************************************************************************* + * 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 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; + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionLibraryHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionLibraryHandler.java index 62d88a4a..8b753418 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionLibraryHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewFunctionLibraryHandler.java @@ -1,110 +1,110 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 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) { - SimanticsUI.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()); - } - }); - } -} +/******************************************************************************* + * 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 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()); + } + }); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewGameExperimentNodeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewGameExperimentNodeHandler.java index 601de37a..6d527470 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewGameExperimentNodeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewGameExperimentNodeHandler.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * 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 { - - protected Resource getExperimentType(ReadGraph g) { - return SysdynResource.getInstance(g).GameExperiment; - } - - /** - * Override to do experiment-specific alterations - */ - protected 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); - } - - protected String getNameSuggestion() { - return "Game Experiment"; - } - -} +/******************************************************************************* + * 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"; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewHistoryDataHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewHistoryDataHandler.java index d97b6845..e499931b 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewHistoryDataHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewHistoryDataHandler.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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); - - SimanticsUI.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; - } - +/******************************************************************************* + * 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModelHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModelHandler.java index 6ed6858e..7ca384f2 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModelHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModelHandler.java @@ -1,64 +1,64 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 { - SimanticsUI.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; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModuleNodeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModuleNodeHandler.java index b5939cb7..0854b53f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModuleNodeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewModuleNodeHandler.java @@ -1,134 +1,134 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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; - - SimanticsUI.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; - } - - -} +/******************************************************************************* + * 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; + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPieChartHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPieChartHandler.java index 0d386c7b..9b304762 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPieChartHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPieChartHandler.java @@ -1,98 +1,98 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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; - - SimanticsUI.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.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; - } -} +/******************************************************************************* + * 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.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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPlaybackExperimentNodeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPlaybackExperimentNodeHandler.java index a54ce36f..8b48489c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPlaybackExperimentNodeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewPlaybackExperimentNodeHandler.java @@ -1,55 +1,55 @@ -/******************************************************************************* - * 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 { - - protected 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); - } - - protected Resource getExperimentType(ReadGraph g) { - return SysdynResource.getInstance(g).PlaybackExperiment; - } - - protected String getNameSuggestion() { - return "Playback Experiment"; - } +/******************************************************************************* + * 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityAnalysisExperimentNodeHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityAnalysisExperimentNodeHandler.java index 1a8ae7a9..f58d3be7 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityAnalysisExperimentNodeHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityAnalysisExperimentNodeHandler.java @@ -1,66 +1,66 @@ -/******************************************************************************* - * 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 - protected 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 parameterList = new ArrayList(); - parameterList.add(parameter); - - graph.claim(experiment, sr.SensitivityAnalysisExperiment_parameterList, ListUtils.create(graph, parameterList)); - } - - @Override - protected Resource getExperimentType(ReadGraph g) { - return SysdynResource.getInstance(g).SensitivityAnalysisExperiment; - } - - @Override - protected String getNameSuggestion() { - return "Sensitivity Experiment"; - } +/******************************************************************************* + * 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 parameterList = new ArrayList(); + 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityChartHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityChartHandler.java index 7bc7a370..8de4ca27 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityChartHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSensitivityChartHandler.java @@ -1,159 +1,159 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.AdaptionUtils; - -public class NewSensitivityChartHandler 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; - - SimanticsUI.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, "SensitivityChart" + 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 confidenceBounds = new ArrayList(); - 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()), - 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; - } +/******************************************************************************* + * 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 confidenceBounds = new ArrayList(); + 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()), + 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSpreadSheetHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSpreadSheetHandler.java index 5a612a49..c666a082 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSpreadSheetHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewSpreadSheetHandler.java @@ -1,57 +1,57 @@ -/******************************************************************************* - * 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.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.sysdyn.utils.SheetUtils; -import org.simantics.ui.SimanticsUI; -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; - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - graph.markUndoPoint(); - Resource sheet = SheetUtils.createSheet(graph, book, null, new String[] {}, new int[] {50}); - Layer0Utils.addCommentMetadata(graph, "Created new Spreadsheet " + NameUtils.getSafeName(graph, sheet) + " " + sheet.toString()); - } - }); - return null; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewXYLineChartHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewXYLineChartHandler.java index 9c2e675e..0ea46d62 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewXYLineChartHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/newComponents/NewXYLineChartHandler.java @@ -1,119 +1,119 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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; - - SimanticsUI.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()), - 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; - } - -} +/******************************************************************************* + * 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()), + 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/RunSensitivityAnalysisExperiment.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/RunSensitivityAnalysisExperiment.java index a6602763..de41de5e 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/RunSensitivityAnalysisExperiment.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/RunSensitivityAnalysisExperiment.java @@ -1,69 +1,69 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 = - SimanticsUI.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 = - SimanticsUI.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); - } - } - } -} +/******************************************************************************* + * 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); + } + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/SaveResultsHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/SaveResultsHandler.java index dab71d2b..1aea7a87 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/SaveResultsHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/SaveResultsHandler.java @@ -1,45 +1,45 @@ -/******************************************************************************* - * 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.simulation.experiment.IDynamicExperiment; -import org.simantics.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.ui.utils.HandlerUtils; -import org.simantics.ui.SimanticsUI; - -/** - * 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 = - SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); - IExperiment experiment = manager.getActiveExperiment(); - if(experiment instanceof IDynamicExperiment) { - ((IDynamicExperiment)experiment).saveState(); - } - return null; - } - -} +/******************************************************************************* + * 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/ToggleSimulation.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/ToggleSimulation.java index f90605c4..5ea2e1da 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/ToggleSimulation.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/sensitivityAnalysis/ToggleSimulation.java @@ -1,86 +1,86 @@ -/******************************************************************************* - * 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.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.manager.SysdynExperiment; -import org.simantics.sysdyn.ui.utils.HandlerUtils; -import org.simantics.ui.SimanticsUI; - -/** - * 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 = - SimanticsUI.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); - } -} +/******************************************************************************* + * 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackExperimentHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackExperimentHandler.java index 72ae6ec7..1c0c3e7e 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackExperimentHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackExperimentHandler.java @@ -1,82 +1,82 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -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 = SimanticsUI.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 = - SimanticsUI.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"))); - } - } - } -} +/******************************************************************************* + * 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"))); + } + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackReloadHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackReloadHandler.java index 75cc05ac..a2c38484 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackReloadHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackReloadHandler.java @@ -1,27 +1,27 @@ -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.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.manager.SysdynPlaybackExperiment; -import org.simantics.sysdyn.ui.utils.HandlerUtils; -import org.simantics.ui.SimanticsUI; - -public class PlaybackReloadHandler extends AbstractHandler { - - @Override - public Object execute(ExecutionEvent event) throws ExecutionException { - HandlerUtils.saveBeforeExperimentRun(event); - - IExperimentManager manager = SimanticsUI.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; - } - -} +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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackResetHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackResetHandler.java index e4155b67..553be10c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackResetHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/PlaybackResetHandler.java @@ -1,63 +1,63 @@ -/******************************************************************************* - * 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.simulation.experiment.ExperimentState; -import org.simantics.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.manager.SysdynPlaybackExperiment; -import org.simantics.ui.SimanticsUI; - -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 = SimanticsUI.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 = - SimanticsUI.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); - } - - } - -} +/******************************************************************************* + * 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); + } + + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SpeedHandler.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SpeedHandler.java index 4fe96910..fc248ed4 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SpeedHandler.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/simulationPlayback/SpeedHandler.java @@ -1,50 +1,50 @@ -/******************************************************************************* - * 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.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.manager.SysdynPlaybackExperiment; -import org.simantics.ui.SimanticsUI; - -abstract class SpeedHandler extends AbstractHandler { - - protected void setPlaybackSpeed(long duration) { - - - IExperimentManager manager = SimanticsUI.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); - } - }); - } - -} +/******************************************************************************* + * 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); + } + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynPlaybackExperimentListener.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynPlaybackExperimentListener.java index 70dc93d3..c5e09d19 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynPlaybackExperimentListener.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/listeners/SysdynPlaybackExperimentListener.java @@ -1,267 +1,266 @@ -/******************************************************************************* - * 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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 previousRuntimeDiagramsAndModelUris = new HashMap(); - - private void activatePlaybackProfile() { - PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { - - @Override - public void run() { - previousRuntimeDiagramsAndModelUris.clear(); - previousRuntimeDiagramsAndModelUris = getCurrentRuntimeDiagramInfos(); - activatePlaybackProfileRequest(previousRuntimeDiagramsAndModelUris); - } - }); - } - - private void revertPlaybackProfiles() { - - IProject project = SimanticsUI.getProject(); - if(project == null) - return; - IExperimentManager manager = SimanticsUI.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 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 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 getCurrentRuntimeDiagramInfos() { - HashMap runtimeDiagramsAndModelUris = new HashMap(); - 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 getRuntimesForModel(WriteGraph graph, HashMap allInfos, Resource model) throws DatabaseException { - HashMap runtimeDiagramsAndModelUris = new HashMap(); - 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 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 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; - } - -} +/******************************************************************************* + * 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 previousRuntimeDiagramsAndModelUris = new HashMap(); + + 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 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 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 getCurrentRuntimeDiagramInfos() { + HashMap runtimeDiagramsAndModelUris = new HashMap(); + 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 getRuntimesForModel(WriteGraph graph, HashMap allInfos, Resource model) throws DatabaseException { + HashMap runtimeDiagramsAndModelUris = new HashMap(); + 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 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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/FontContextMenuContribution.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/FontContextMenuContribution.java index 9f69f7b3..726e0f2f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/FontContextMenuContribution.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/FontContextMenuContribution.java @@ -1,196 +1,196 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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 - SimanticsUI.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) { - } - - } -} +/******************************************************************************* + * 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) { + } + + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/GameStepDurationContribution.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/GameStepDurationContribution.java index fb1e41c7..7b576b4f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/GameStepDurationContribution.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/GameStepDurationContribution.java @@ -1,106 +1,96 @@ -/******************************************************************************* - * 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.action.IContributionItem; -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.ToolBar; -import org.eclipse.swt.widgets.ToolItem; -import org.eclipse.ui.actions.CompoundContributionItem; -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.ui.SimanticsUI; -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 - * - */ -public class GameStepDurationContribution extends CompoundContributionItem { - - private TrackedText stepDuration; - private int width = 40; - private ToolItem ti; - - public static String COMMAND = "org.simantics.sysdyn.ui.gameStepDuration"; - - public GameStepDurationContribution() { - super(COMMAND); - } - - @Override - protected IContributionItem[] getContributionItems() { - return new IContributionItem[0]; - } - - @Override - public void fill(final ToolBar parent, final int index) { - IProject project = SimanticsUI.peekProject(); - if (project == null) - return; - - // Find game experiment - IExperimentManager manager = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); - - IExperiment active = manager.getActiveExperiment(); - if (!(active instanceof SysdynGameExperimentBase)) - return; - - final SysdynGameExperimentBase game = (SysdynGameExperimentBase) active; - - // Create the text - - ti = new ToolItem(parent, SWT.SEPARATOR, index); - ti.setText("Step Duration"); - ti.setToolTipText("Step Duration"); - - ISessionContext context = SimanticsUI.getSessionContext(); - WidgetSupportImpl support = new WidgetSupportImpl(); // Dummy widget support for using tracked text - - stepDuration = new TrackedText(parent, 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()); - - ti.setWidth(width); - ti.setControl(stepDuration.getWidget()); - - } - - @Override - public boolean isDynamic() { - return true; - } - +/******************************************************************************* + * 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java index 27e3b551..cb775805 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java @@ -1,171 +1,182 @@ -/******************************************************************************* - * 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.jface.action.ToolBarContributionItem; -import org.eclipse.jface.layout.GridDataFactory; -import org.eclipse.jface.layout.GridLayoutFactory; -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.Label; -import org.eclipse.swt.widgets.Slider; -import org.eclipse.swt.widgets.ToolBar; -import org.eclipse.swt.widgets.ToolItem; -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.simulation.experiment.IExperiment; -import org.simantics.simulation.project.IExperimentManager; -import org.simantics.sysdyn.SysdynResource; -import org.simantics.sysdyn.manager.SysdynPlaybackExperiment; -import org.simantics.ui.SimanticsUI; - -/** - * Contribution to the main toolbar. PlaybackSliderContribution contains a slider - * that can be used to control the time in a playback experiment - * - * @author Teemu Lempinen - * - */ -public class PlaybackSliderContribution extends ToolBarContributionItem { - - Runnable timeListener; - SysdynPlaybackExperiment spe; - Slider s; - Double startTime, endTime; - boolean ignoreChange = false; - - @Override - public void fill(ToolBar parent, int index) - { - if (parent != null) { - - IExperimentManager manager = SimanticsUI.getProject().getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER); - IExperiment experiment = manager.getActiveExperiment(); - if(experiment == null || !(experiment instanceof SysdynPlaybackExperiment)) - return; - spe = (SysdynPlaybackExperiment)experiment; - - Double[] numbers = new Double[2]; - try { - numbers = SimanticsUI.getSession().syncRequest(new Read() { - @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(); - } - - // Separator ToolItem can contain a composite. Add a composite with a slider to this item - ToolItem ti = new ToolItem(parent, SWT.SEPARATOR); - - Composite composite = new Composite(parent, SWT.NONE); - GridLayoutFactory.fillDefaults().margins(3, SWT.DEFAULT).numColumns(2).applyTo(composite); - GridDataFactory.fillDefaults().applyTo(composite); - - s = new Slider(composite, SWT.NONE); - s.setMinimum(0); - s.setMaximum(100); - s.setIncrement(1); - s.setPageIncrement(1); - s.setThumb(1); - - final Label label = new Label(composite, SWT.NONE); - GridDataFactory.fillDefaults().hint(70, SWT.DEFAULT).applyTo(label); - label.setText("0.0"); - - ti.setWidth(270); - ti.setControl(composite); - - 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 - s.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() { - s.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)); - s.setSelection(value); - label.setText(format.format(spe.getTime())); - } - }); - - } - - }; - spe.addTimeListener(timeListener); - } - } - - @Override - public void dispose() { - if(this.timeListener != null && spe != null) { - spe.removeTimeListener(timeListener); - this.timeListener = null; - } - super.dispose(); - - } -} +/******************************************************************************* + * 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() { + @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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/SysdynModelicaEditor.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/SysdynModelicaEditor.java index bc00c02a..5cbaa65a 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/SysdynModelicaEditor.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/modelica/SysdynModelicaEditor.java @@ -1,159 +1,159 @@ -/******************************************************************************* - * 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.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.SimanticsUI; -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(SimanticsUI.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(SimanticsUI.getSession(), ((ResourceEditorInput)element).getResource()); - - HashSet configurations = new HashSet(); - 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 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); - } - - -} - +/******************************************************************************* + * 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 configurations = new HashSet(); + 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 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); + } + + +} + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java index 4072c806..cfaec046 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/EquationTab.java @@ -1,774 +1,774 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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() { - - @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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 = SimanticsUI.getSession().syncRequest(new WriteResultRequest() { - - @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.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 addition = new ArrayList(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 - SimanticsUI.getSession().asyncRequest(new Read>() { - - /** - * Find out if user can add a new expression or delete the current expression - */ - @Override - public Pair perform(ReadGraph graph) throws DatabaseException { - SysdynResource sr = SysdynResource.getInstance(graph); - Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList); - if(expressions == null) { - return new Pair(false, false); - } - List expressionList = ListUtils.toList(graph, expressions); - if(expressionList.isEmpty()) { - return new Pair(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(canAdd, canDelete); - } - }, new AsyncListener>() { - - @Override - public void execute(AsyncReadGraph graph, - final Pair 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(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 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(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 addition = new ArrayList(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>() { - - @Override - public Map perform(ReadGraph graph, final Resource input) throws DatabaseException { - - Map map = new HashMap(); - 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() { - - @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>() { - - @Override - public Map perform(ReadGraph graph, final Resource input) throws DatabaseException { - Map map = new HashMap(); - - SysdynResource sr = SysdynResource.getInstance(graph); - Layer0 l0 = Layer0.getInstance(graph); - Resource model = graph.getPossibleObject(input, l0.PartOf); - if (model != null) { - Collection 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() { - - @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() { - - @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 expressionList = ListUtils.toList(graph, expressions); - if(expressionList.isEmpty()) { - return null; - } - expression = expressionList.get(0); - } - return expression; - } -} +/******************************************************************************* + * 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() { + + @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() { + + @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() { + + @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() { + + @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.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 addition = new ArrayList(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>() { + + /** + * Find out if user can add a new expression or delete the current expression + */ + @Override + public Pair perform(ReadGraph graph) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + Resource expressions = graph.getPossibleObject(variable, sr.Variable_expressionList); + if(expressions == null) { + return new Pair(false, false); + } + List expressionList = ListUtils.toList(graph, expressions); + if(expressionList.isEmpty()) { + return new Pair(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(canAdd, canDelete); + } + }, new AsyncListener>() { + + @Override + public void execute(AsyncReadGraph graph, + final Pair 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(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 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(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 addition = new ArrayList(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>() { + + @Override + public Map perform(ReadGraph graph, final Resource input) throws DatabaseException { + + Map map = new HashMap(); + 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() { + + @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>() { + + @Override + public Map perform(ReadGraph graph, final Resource input) throws DatabaseException { + Map map = new HashMap(); + + SysdynResource sr = SysdynResource.getInstance(graph); + Layer0 l0 = Layer0.getInstance(graph); + Resource model = graph.getPossibleObject(input, l0.PartOf); + if (model != null) { + Collection 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() { + + @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() { + + @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 expressionList = ListUtils.toList(graph, expressions); + if(expressionList.isEmpty()) { + return null; + } + expression = expressionList.get(0); + } + return expression; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LoopTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LoopTab.java index ffec528d..bf469f44 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LoopTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/LoopTab.java @@ -1,409 +1,409 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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>() { - - @Override - public Map perform(ReadGraph graph, final Resource input) throws DatabaseException { - - LoopTab.this.resource = input; - Map map = new HashMap(); - List> loops = LoopUtils.getAllLoopsInDiagram(graph, input); - map.put("", null); - for (List loop : loops) { - map.put(LoopUtils.cycleToString(graph, loop), loop); - } - return map; - } - }); - - // Initial selection to the combo - loopItemsDropdown.setSelectionFactory(new ReadFactoryImpl() { - - @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 itemList = ListUtils.toPossibleList(graph, itemListResource); - if (itemList == null) { - return ""; - } - - // See if the defined loop still exists. - List> loops = LoopUtils.getAllLoopsInDiagram(graph, input); - Resource first = itemList.get(0); - for (List 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() { - - @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 loop = (List)loopObject; - SimanticsUI.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 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 { - - private final String propertyURI; - - public OtherCommentStringPropertyFactory() { - this.propertyURI = SysdynResource.URIs.Loop_Comment; - } - - @Override - public Object getIdentity(Object inputContents) { - return new Triple((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 { - 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 { - private boolean clockwise; - - public ClockwiseRotationRadioSelectionFactory(boolean clockwise) { - this.clockwise = clockwise; - } - - @Override - public Object getIdentity(Object inputContents) { - return new Triple>(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 { - 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 { - private String comment; - - public CommentRadioSelectionFactory(String comment) { - this.comment = comment; - } - - @Override - public Object getIdentity(Object inputContents) { - return new Triple>(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 { - - String[] limits; - - public OtherCommentSelectionFactory(String[] limits) { - this.limits = limits; - } - - @Override - public Object getIdentity(Object inputContents) { - return new Pair>(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; - } - } -} +/******************************************************************************* + * 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>() { + + @Override + public Map perform(ReadGraph graph, final Resource input) throws DatabaseException { + + LoopTab.this.resource = input; + Map map = new HashMap(); + List> loops = LoopUtils.getAllLoopsInDiagram(graph, input); + map.put("", null); + for (List loop : loops) { + map.put(LoopUtils.cycleToString(graph, loop), loop); + } + return map; + } + }); + + // Initial selection to the combo + loopItemsDropdown.setSelectionFactory(new ReadFactoryImpl() { + + @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 itemList = ListUtils.toPossibleList(graph, itemListResource); + if (itemList == null) { + return ""; + } + + // See if the defined loop still exists. + List> loops = LoopUtils.getAllLoopsInDiagram(graph, input); + Resource first = itemList.get(0); + for (List 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() { + + @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 loop = (List)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 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 { + + private final String propertyURI; + + public OtherCommentStringPropertyFactory() { + this.propertyURI = SysdynResource.URIs.Loop_Comment; + } + + @Override + public Object getIdentity(Object inputContents) { + return new Triple((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 { + 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 { + private boolean clockwise; + + public ClockwiseRotationRadioSelectionFactory(boolean clockwise) { + this.clockwise = clockwise; + } + + @Override + public Object getIdentity(Object inputContents) { + return new Triple>(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 { + 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 { + private String comment; + + public CommentRadioSelectionFactory(String comment) { + this.comment = comment; + } + + @Override + public Object getIdentity(Object inputContents) { + return new Triple>(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 { + + String[] limits; + + public OtherCommentSelectionFactory(String[] limits) { + this.limits = limits; + } + + @Override + public Object getIdentity(Object inputContents) { + return new Pair>(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; + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SensitivityAnalysisExperimentTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SensitivityAnalysisExperimentTab.java index 60b3fdc2..e177402c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SensitivityAnalysisExperimentTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SensitivityAnalysisExperimentTab.java @@ -1,647 +1,647 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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> 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>() { - - @Override - public void execute(Collection 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 result = (Collection) getObject(); - if(result.size() > 1) - remove.getWidget().setEnabled(true); - else - remove.getWidget().setEnabled(false); - } - } - }); - - } - } - - @Override - public void exception(Throwable t) { - t.printStackTrace(); - } - }; - - SimanticsUI.getSession().asyncRequest(new Read> () { - - @SuppressWarnings("unchecked") - @Override - public Collection perform(ReadGraph graph) throws DatabaseException { - return (Collection) 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>() { - - @Override - public Map perform(ReadGraph graph, Resource input) throws DatabaseException { - SysdynResource SR = SysdynResource.getInstance(graph); - Map items = new HashMap(); - - items.put("Halton", SR.HaltonSequenceGenerator); - items.put("Random", SR.RandomGenerator); - - return items; - } - - }); - methodSelector.setSelectionFactory(new ReadFactoryImpl() { - - @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() { - - @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(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(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>() { - - @Override - public Map perform(ReadGraph graph, Resource input) throws DatabaseException { - SysdynResource SR = SysdynResource.getInstance(graph); - Map items = new HashMap(); - - items.put("Normal", SR.NormalDistribution); - items.put("Uniform", SR.UniformDistribution); - items.put("Interval", SR.Interval); - - return items; - } - - }); - - distributionSelector.setSelectionFactory(new ReadFactoryImpl() { - - @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() { - - @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); - - } - -} +/******************************************************************************* + * 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> 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>() { + + @Override + public void execute(Collection 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 result = (Collection) 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> () { + + @SuppressWarnings("unchecked") + @Override + public Collection perform(ReadGraph graph) throws DatabaseException { + return (Collection) 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>() { + + @Override + public Map perform(ReadGraph graph, Resource input) throws DatabaseException { + SysdynResource SR = SysdynResource.getInstance(graph); + Map items = new HashMap(); + + items.put("Halton", SR.HaltonSequenceGenerator); + items.put("Random", SR.RandomGenerator); + + return items; + } + + }); + methodSelector.setSelectionFactory(new ReadFactoryImpl() { + + @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() { + + @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(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(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>() { + + @Override + public Map perform(ReadGraph graph, Resource input) throws DatabaseException { + SysdynResource SR = SysdynResource.getInstance(graph); + Map items = new HashMap(); + + items.put("Normal", SR.NormalDistribution); + items.put("Uniform", SR.UniformDistribution); + items.put("Interval", SR.Interval); + + return items; + } + + }); + + distributionSelector.setSelectionFactory(new ReadFactoryImpl() { + + @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() { + + @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); + + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java index 7fec15f7..ec14b723 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java @@ -25,6 +25,7 @@ import org.eclipse.swt.SWT; 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; @@ -44,7 +45,6 @@ import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor; 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; @@ -88,7 +88,7 @@ public class SharedFunctionLibrariesTab extends LabelPropertyTabContributor impl 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 { @@ -197,7 +197,7 @@ public class SharedFunctionLibrariesTab extends LabelPropertyTabContributor impl 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 { diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/VariableInformationTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/VariableInformationTab.java index bb66b6e4..66524760 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/VariableInformationTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/VariableInformationTab.java @@ -1,445 +1,445 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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> 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() { - - @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>() { - - @Override - public Pair 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); - } - }; - - SimanticsUI.getSession().asyncRequest(fontAndColorRead, new Listener>() { - - @Override - public void execute(final Pair 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(context) { - - Font f; - Color color; - Object input; - - @Override - public void beforeApply() { - - Triple result = null; - - try { - result = SimanticsUI.getSession().syncRequest(new Read>(){ - - @Override - public Triple 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, 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); - } -} +/******************************************************************************* + * 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> 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() { + + @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>() { + + @Override + public Pair 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); + } + }; + + Simantics.getSession().asyncRequest(fontAndColorRead, new Listener>() { + + @Override + public void execute(final Pair 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(context) { + + Font f; + Color color; + Object input; + + @Override + public void beforeApply() { + + Triple result = null; + + try { + result = Simantics.getSession().syncRequest(new Read>(){ + + @Override + public Triple 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, 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartTableWidget.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartTableWidget.java index b600df86..7ebb22e6 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartTableWidget.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartTableWidget.java @@ -1,247 +1,247 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 { - SimanticsUI.getSession().syncRequest(new Read() { - - @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() { - - @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 xTokens = parser.getXTokens(); - ArrayList 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 inputOutputList = (ArrayList)table.getTableViewer().getInput(); - Collections.sort(inputOutputList, table.new InputOutputComparator()); - Iterator 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(); - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - SysdynResource sr = SysdynResource.getInstance(graph); - graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table); - } - }); - } - -} +/******************************************************************************* + * 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() { + + @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() { + + @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 xTokens = parser.getXTokens(); + ArrayList 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 inputOutputList = (ArrayList)table.getTableViewer().getInput(); + Collections.sort(inputOutputList, table.new InputOutputComparator()); + Iterator 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); + } + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartWidget.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartWidget.java index 2dd769dc..c12ffc6f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartWidget.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ChartWidget.java @@ -1,240 +1,240 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 { - SimanticsUI.getSession().syncRequest(new Read() { - - @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() { - - @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 xTokens = parser.getXTokens(); - ArrayList 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(); - - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - SysdynResource sr = SysdynResource.getInstance(graph); - graph.claimLiteral(expression, sr.WithLookupExpression_lookup, table); - } - }); - - } - } -} +/******************************************************************************* + * 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() { + + @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() { + + @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 xTokens = parser.getXTokens(); + ArrayList 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); + } + }); + + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionTypes.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionTypes.java index 7b3b20bf..dc8060af 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionTypes.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionTypes.java @@ -1,87 +1,87 @@ -/******************************************************************************* - * 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.db.ReadGraph; -import org.simantics.db.Resource; -import org.simantics.db.exception.DatabaseException; -import org.simantics.db.request.Read; -import org.simantics.sysdyn.SysdynResource; -import org.simantics.ui.SimanticsUI; - -/** - * 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 SimanticsUI.getSession().syncRequest(new Read() { - - @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; - } - -} +/******************************************************************************* + * 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() { + + @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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionWidget.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionWidget.java index 07b448bf..4b38a52a 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionWidget.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ExpressionWidget.java @@ -1,272 +1,272 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 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(); - - // 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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); - } - -} +/******************************************************************************* + * 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 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(); + + // 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() { + + @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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ShortcutTabWidget.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ShortcutTabWidget.java index 9b69fc07..f1f26c50 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ShortcutTabWidget.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/ShortcutTabWidget.java @@ -1,335 +1,335 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 dependencyListeners = - new CopyOnWriteArrayList(); - - 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 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 - SimanticsUI.getSession().asyncRequest(new Read>() { - - @Override - public HashSet perform(ReadGraph graph) - throws DatabaseException { - return ValidationUtils.getDependencies(graph, variable); - } - }, new AsyncListener>() { - - @Override - public void execute(AsyncReadGraph graph, - HashSet result) { - - final HashSet 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 itemStrings = new ArrayList(); - 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 = SimanticsUI.getSession().syncRequest(new Read() { - @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; - } - } -} +/******************************************************************************* + * 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 dependencyListeners = + new CopyOnWriteArrayList(); + + 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 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() { + + @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>() { + + @Override + public HashSet perform(ReadGraph graph) + throws DatabaseException { + return ValidationUtils.getDependencies(graph, variable); + } + }, new AsyncListener>() { + + @Override + public void execute(AsyncReadGraph graph, + HashSet result) { + + final HashSet 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 itemStrings = new ArrayList(); + 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() { + @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; + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/RedeclarationNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/RedeclarationNode.java index 6c2b6781..6c73907e 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/RedeclarationNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/arrays/RedeclarationNode.java @@ -1,172 +1,172 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class RedeclarationNode extends AbstractNode 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 cbm = null; - - try { - cbm = SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public ComboBoxModifier perform(ReadGraph graph) throws DatabaseException { - SysdynResource sr = SysdynResource.getInstance(graph); - Layer0 l0 = Layer0.getInstance(graph); - - ArrayList> values = new ArrayList>(); - - - 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(name, enumeration)); - } - - if(values.size() == 0) - return null; - - values.add(0, new EnumeratedValue("", null)); - Enumeration enumeration = new Enumeration(values); - - ComboBoxModifier cbm = new ComboBoxModifier(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; - } - - -} +/******************************************************************************* + * 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 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 cbm = null; + + try { + cbm = Simantics.getSession().syncRequest(new Read>() { + + @Override + public ComboBoxModifier perform(ReadGraph graph) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + Layer0 l0 = Layer0.getInstance(graph); + + ArrayList> values = new ArrayList>(); + + + 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(name, enumeration)); + } + + if(values.size() == 0) + return null; + + values.add(0, new EnumeratedValue("", null)); + Enumeration enumeration = new Enumeration(values); + + ComboBoxModifier cbm = new ComboBoxModifier(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; + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/AuxiliaryExpression.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/AuxiliaryExpression.java index 48a5e7d1..e01c7a78 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/AuxiliaryExpression.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/AuxiliaryExpression.java @@ -1,59 +1,59 @@ -/******************************************************************************* - * 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.db.ReadGraph; -import org.simantics.db.Resource; -import org.simantics.db.exception.DatabaseException; -import org.simantics.db.request.Read; -import org.simantics.sysdyn.SysdynResource; -import org.simantics.ui.SimanticsUI; - -public class AuxiliaryExpression extends BasicExpression { - - public AuxiliaryExpression(ExpressionWidgetInput input) { - super(input); - try { - this.expressionType = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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); - } -} +/******************************************************************************* + * 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() { + + @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 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); + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/BasicExpression.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/BasicExpression.java index a1c65495..f66a0c2f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/BasicExpression.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/BasicExpression.java @@ -1,246 +1,246 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 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 getExpressionFields() { - return Arrays.asList(this.expression); - } - - @Override - public void readData(final Resource expression, Map data) { - String equation = null; - if (expression != null && data.get("equation") == null) { - try { - equation = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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); - SimanticsUI.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 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; - } -} +/******************************************************************************* + * 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 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 getExpressionFields() { + return Arrays.asList(this.expression); + } + + @Override + public void readData(final Resource expression, Map data) { + String equation = null; + if (expression != null && data.get("equation") == null) { + try { + equation = Simantics.getSession().syncRequest(new Read() { + + @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 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 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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/CompletionProcessor.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/CompletionProcessor.java index d2d78a52..f0f79350 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/CompletionProcessor.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/CompletionProcessor.java @@ -1,348 +1,348 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - - -/** - * 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 functions; - private ArrayList variables = null; - private ArrayList 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 ALLOW_ALL_COMPLETIONS_LIST = new ArrayList(); - static { - ALLOW_ALL_COMPLETIONS_LIST.add(""); - } - - public CompletionProcessor(Table allowedVariables, boolean allowFunctions, ExpressionWidgetInput input) { - this.allowedVariables = allowedVariables; - this.input = input; - this.functions = new ArrayList(); - - if (allowFunctions) { - if (input != null && CompletionProcessor.this.input.variable != null) { - // Get the respective model - Resource model = null; - try { - model = SimanticsUI.getSession().syncRequest(new Read() { - - @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(); - timeAndSelfVariables = new ArrayList(); - 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 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 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 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 possibleLabelBeginnings, int offset) { - ArrayList resultArray = new ArrayList(); - - // 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(){ - @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 getPossibleLabelBeginnings(String[] tokens) { - ArrayList possibleLabelBeginnings = new ArrayList(); - 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; - } - -} +/******************************************************************************* + * 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 functions; + private ArrayList variables = null; + private ArrayList 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 ALLOW_ALL_COMPLETIONS_LIST = new ArrayList(); + static { + ALLOW_ALL_COMPLETIONS_LIST.add(""); + } + + public CompletionProcessor(Table allowedVariables, boolean allowFunctions, ExpressionWidgetInput input) { + this.allowedVariables = allowedVariables; + this.input = input; + this.functions = new ArrayList(); + + if (allowFunctions) { + if (input != null && CompletionProcessor.this.input.variable != null) { + // Get the respective model + Resource model = null; + try { + model = Simantics.getSession().syncRequest(new Read() { + + @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(); + timeAndSelfVariables = new ArrayList(); + 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 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 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 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 possibleLabelBeginnings, int offset) { + ArrayList resultArray = new ArrayList(); + + // 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(){ + @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 getPossibleLabelBeginnings(String[] tokens) { + ArrayList possibleLabelBeginnings = new ArrayList(); + 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ConstantExpression.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ConstantExpression.java index 28a502d2..b5adb45d 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ConstantExpression.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ConstantExpression.java @@ -1,60 +1,60 @@ -/******************************************************************************* - * 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.db.ReadGraph; -import org.simantics.db.Resource; -import org.simantics.db.exception.DatabaseException; -import org.simantics.db.request.Read; -import org.simantics.sysdyn.SysdynResource; -import org.simantics.ui.SimanticsUI; - -public class ConstantExpression extends BasicExpression { - - public ConstantExpression(ExpressionWidgetInput input) { - super(input); - try { - this.expressionType = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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); - - } +/******************************************************************************* + * 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() { + + @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 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/DelayExpression.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/DelayExpression.java index 5e778c92..62c1ddf3 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/DelayExpression.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/DelayExpression.java @@ -1,392 +1,392 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 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 = SimanticsUI.getSession().syncRequest(new Read(){ - - @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 getExpressionFields() { - return Arrays.asList(equation, delayTime, initialValue); - } - - @Override - public void readData(final Resource expression, Map data) { - class Auxiliary { - String equation, delayTime, initialValue; - Integer order; - Boolean isInformationDelay; - } - - Auxiliary results = null; - - try { - results = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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); - - SimanticsUI.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 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; - } - -} +/******************************************************************************* + * 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 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(){ + + @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 getExpressionFields() { + return Arrays.asList(equation, delayTime, initialValue); + } + + @Override + public void readData(final Resource expression, Map data) { + class Auxiliary { + String equation, delayTime, initialValue; + Integer order; + Boolean isInformationDelay; + } + + Auxiliary results = null; + + try { + results = Simantics.getSession().syncRequest(new Read() { + + @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 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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ParameterExpression.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ParameterExpression.java index 772f083b..363186db 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ParameterExpression.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/ParameterExpression.java @@ -1,182 +1,182 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class ParameterExpression extends BasicExpression { - - Variable variable; - - public ParameterExpression(ExpressionWidgetInput input) { - super(input); - try { - this.expressionType = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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 data) { - IExperimentManager manager = SimanticsUI.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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 data) { - - IExperimentManager manager = SimanticsUI.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 = SimanticsUI.getSession().syncRequest(new WriteResultRequest() { - - @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 = SimanticsUI.getSession().syncRequest(new Read() { - - @Override - public Resource perform(ReadGraph graph) throws DatabaseException { - return SysdynResource.getInstance(graph).ParameterExpression; - } - }); - } catch (DatabaseException e) { - e.printStackTrace(); - } - } - - -} +/******************************************************************************* + * 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() { + + @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 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 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() { + + @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 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() { + + @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() { + + @Override + public Resource perform(ReadGraph graph) throws DatabaseException { + return SysdynResource.getInstance(graph).ParameterExpression; + } + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/WithLookupExpression.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/WithLookupExpression.java index 5051f5c1..c78bd2bb 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/WithLookupExpression.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/expressions/WithLookupExpression.java @@ -1,469 +1,469 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -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 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(); - } - }); - - - SimanticsUI.getSession().asyncRequest(new Read() { - - @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() { - - @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 getExpressionFields() { - return Arrays.asList(this.expression, this.lookup); - } - - @Override - public void readData(final Resource expression, Map data) { - - class Auxiliary { - String equation, lookup; - } - - Auxiliary results = null; - - if (data.get("equation") == null) { - try { - results = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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); - SimanticsUI.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 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 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 dataPoints = new ArrayList(); - TableParser parser = new TableParser(new StringReader("")); - parser.ReInit(new StringReader(lookup.getExpression())); - try { - parser.table(); - ArrayList xTokens = parser.getXTokens(); - ArrayList 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 xTokens = parser.getXTokens(); - ArrayList 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; - } - -} +/******************************************************************************* + * 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 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() { + + @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() { + + @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 getExpressionFields() { + return Arrays.asList(this.expression, this.lookup); + } + + @Override + public void readData(final Resource expression, Map data) { + + class Auxiliary { + String equation, lookup; + } + + Auxiliary results = null; + + if (data.get("equation") == null) { + try { + results = Simantics.getSession().syncRequest(new Read() { + + @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 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 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 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 dataPoints = new ArrayList(); + TableParser parser = new TableParser(new StringReader("")); + parser.ReInit(new StringReader(lookup.getExpression())); + try { + parser.table(); + ArrayList xTokens = parser.getXTokens(); + ArrayList 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() { + + @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 xTokens = parser.getXTokens(); + ArrayList 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileNode.java index 1150817a..9f3224ce 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/externalFiles/ExternalFileNode.java @@ -1,77 +1,77 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class ExternalFileNode extends AbstractNode implements IModifiableNode, IDeletableNode { - - public ExternalFileNode(Resource data) { - super(data); - } - - @Override - public Modifier getModifier(String columnId) { - try { - final Resource hasName = Layer0.getInstance(SimanticsUI.getSession()).HasName; - LabelModifier modifier = new LabelModifier(SimanticsUI.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 { - SimanticsUI.getSession().asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - RemoverUtil.remove(graph, data); - } - }); - } - -} +/******************************************************************************* + * 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 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); + } + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/FunctionCodeWidget.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/FunctionCodeWidget.java index 18294955..aee15d9d 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/FunctionCodeWidget.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/functions/FunctionCodeWidget.java @@ -1,349 +1,349 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 inputs; - private ArrayList 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() { - - @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() { - - @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(); - - SimanticsUI.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 inputResources = new ArrayList(); - // 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 outputResources = new ArrayList(); - // 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)); - } - - } - - }); - } - -} +/******************************************************************************* + * 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 inputs; + private ArrayList 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() { + + @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() { + + @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 inputResources = new ArrayList(); + // 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 outputResources = new ArrayList(); + // 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)); + } + + } + + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleInputEditingSupport.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleInputEditingSupport.java index 42a751a1..6359400a 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleInputEditingSupport.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleInputEditingSupport.java @@ -1,143 +1,143 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class ModuleInputEditingSupport extends EditingSupport { - private CellEditor editor; - private int column; - private HashMap 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(); - try { - optionResources = SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public HashMap perform(ReadGraph graph) throws DatabaseException { - Layer0 l0 = Layer0.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - HashMap result = new HashMap(); - 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); - } - -} +/******************************************************************************* + * 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 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(); + try { + optionResources = Simantics.getSession().syncRequest(new Read>() { + + @Override + public HashMap perform(ReadGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + HashMap result = new HashMap(); + 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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleOutputEditingSupport.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleOutputEditingSupport.java index 4b64f3bc..5decb361 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleOutputEditingSupport.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ModuleOutputEditingSupport.java @@ -1,138 +1,138 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -public class ModuleOutputEditingSupport extends EditingSupport { - private CellEditor editor; - private int column; - private HashMap 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(); - try { - optionResources = SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public HashMap perform(ReadGraph graph) throws DatabaseException { - Layer0 l0 = Layer0.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - HashMap result = new HashMap(); - 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); - } - -} +/******************************************************************************* + * 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 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(); + try { + optionResources = Simantics.getSession().syncRequest(new Read>() { + + @Override + public HashMap perform(ReadGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + HashMap result = new HashMap(); + 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); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterModifierRule.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterModifierRule.java index a964c5b6..7f73c4a5 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterModifierRule.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ParameterModifierRule.java @@ -1,113 +1,113 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -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 request = - new Read() { - - @Override - public String perform(ReadGraph graph) throws DatabaseException { - String parameterExpression = ModuleParameterOverrideUtils.getParameterExpressionOrOverride( - graph, - node.getParent(), - node.getIndependentVariable()); - - return parameterExpression != null ? parameterExpression : ""; - } - - }; - try { - return SimanticsUI.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) { - SimanticsUI.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; - } - } - -} +/******************************************************************************* + * 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 request = + new Read() { + + @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; + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRow.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRow.java index e6685123..6d664fc4 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRow.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceRow.java @@ -1,118 +1,118 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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; - SimanticsUI.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; - } -} - +/******************************************************************************* + * 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() { + + @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() { + + @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; + } +} + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceTable.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceTable.java index aeb5dafd..6ec3aa5d 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceTable.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/modules/ReferenceTable.java @@ -1,132 +1,133 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 { - SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public ArrayList perform(ReadGraph graph) throws DatabaseException { - return rowProvider.getRows(graph, module); - } - } , new Listener>() { - - @Override - public boolean isDisposed() { - if(tableViewer != null && tableViewer.getTable() != null) - return getTableViewer().getTable().isDisposed(); - else - return true; - } - - @Override - public void execute(final ArrayList 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()); - } - } - -} +/******************************************************************************* + * 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>() { + + @Override + public ArrayList perform(ReadGraph graph) throws DatabaseException { + return rowProvider.getRows(graph, module); + } + } , new Listener>() { + + @Override + public boolean isDisposed() { + if(tableViewer != null && tableViewer.getTable() != null) + return getTableViewer().getTable().isDisposed(); + else + return true; + } + + @Override + public void execute(final ArrayList 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()); + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/DistributionPropertyWidget.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/DistributionPropertyWidget.java index 93a62b2d..81490e10 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/DistributionPropertyWidget.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/widgets/sensitivity/DistributionPropertyWidget.java @@ -1,118 +1,118 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -import org.simantics.utils.ui.AdaptionUtils; - -public class DistributionPropertyWidget extends Composite implements Widget { - - private IDistributionProperties distributionProperties = null; - private WidgetSupportImpl distributionSupport = new WidgetSupportImpl(); - private HashMap cache = new HashMap(); - 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @Override - public Resource perform(ReadGraph graph) throws DatabaseException { - Resource distribution = graph.getPossibleObject( - resource, - SysdynResource.getInstance(graph).SensitivityAnalysisExperiment_Parameter_propabilityDistribution - ); - - return distribution; - } - - }); - - newProperties = SimanticsUI.getSession().syncRequest(new Read() { - - @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; - - SimanticsUI.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(); - } - } -} +/******************************************************************************* + * 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 cache = new HashMap(); + 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() { + + @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() { + + @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(); + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Dependencies.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Dependencies.java index 02e052d8..8ee736d7 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Dependencies.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Dependencies.java @@ -1,113 +1,113 @@ -/******************************************************************************* - * 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.db.Resource; -import org.simantics.ui.SimanticsUI; - -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(); - SimanticsUI.getSession().asyncRequest(new DependencyGraphRequest( - resource, levels, isInverted), graphListener); - } - - protected String getJobLabel() { - return "Loading dependencies graph"; - } -} +/******************************************************************************* + * 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"; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Loops.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Loops.java index 798b5043..09e0f156 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Loops.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/Loops.java @@ -1,44 +1,44 @@ -/******************************************************************************* - * 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.db.Resource; -import org.simantics.ui.SimanticsUI; - -/** - * 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(); - SimanticsUI.getSession().asyncRequest(new LoopGraphRequest( - resource), graphListener); - } - - protected String getJobLabel() { - return "Loading loops graph"; - } - -} +/******************************************************************************* + * 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"; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructure.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructure.java index c3b27997..0a1975d9 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructure.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/structure/ModuleStructure.java @@ -1,135 +1,135 @@ -/******************************************************************************* - * 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.db.Resource; -import org.simantics.db.procedure.Listener; -import org.simantics.graphviz.Graph; -import org.simantics.graphviz.ui.GraphvizComponent; -import org.simantics.ui.SimanticsUI; -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 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(); - SimanticsUI.getSession().asyncRequest(new ModuleStructureGraphRequest(r), graphListener); - } - } - } - } - - /** - * Listener for updating hierarchical model graph - * @author Teemu Lempinen - * - */ - private class GraphListener implements Listener { - 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; - } - } -} +/******************************************************************************* + * 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 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 { + 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; + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllParametersOfModel.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllParametersOfModel.java index de84ecf5..a6f1f766 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllParametersOfModel.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/AllParametersOfModel.java @@ -1,132 +1,132 @@ -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.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.ui.SimanticsUI; -import org.simantics.utils.strings.AlphanumComparator; -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; - -/** - * 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> getVariablesQuery() { - return new VariableQuery(); - } - - - private class VariableQuery implements Read> { - @Override - public Collection perform(ReadGraph graph) throws DatabaseException { - Layer0 l0 = Layer0.getInstance(graph); - SimulationResource simu = SimulationResource.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - - List result = new ArrayList(); - // 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 items) throws DatabaseException { - SysdynResource sr = SysdynResource.getInstance(graph); - Layer0 l0 = Layer0.getInstance(graph); - StructuralResource2 sr2 = StructuralResource2.getInstance(graph); - - SysdynModelManager sdm = SysdynModelManager.getInstance(SimanticsUI.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('/', '.'); - } - -} - +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> getVariablesQuery() { + return new VariableQuery(); + } + + + private class VariableQuery implements Read> { + @Override + public Collection perform(ReadGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SimulationResource simu = SimulationResource.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + + List result = new ArrayList(); + // 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 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('/', '.'); + } + +} + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/CategoryDataset.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/CategoryDataset.java index 4a5f80f2..a16471fc 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/CategoryDataset.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/CategoryDataset.java @@ -1,315 +1,315 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * Class representing a JFreeChart.CategoryDataset - * - * @author Teemu Lempinen - * - */ -public class CategoryDataset extends AbstractDataset implements org.simantics.jfreechart.chart.CategoryDataset{ - - private List 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() || SimanticsUI.getSession() == null) - return null; - - if(dataset == null) { - dataset = new DefaultCategoryDataset(); - } - - if(listener == null || listener.isDisposed()) { - listener = new DatasetListener(); - SimanticsUI.getSession().asyncRequest(new Read>() { - - @Override - public ArrayList perform(ReadGraph graph) throws DatabaseException { - JFreeChartResource jfree = JFreeChartResource.getInstance(graph); - - ArrayList series = new ArrayList(); - // 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 datasets = new ArrayList(); - - for(Object o : (ArrayList)object) { - if(o instanceof SysdynDataSet) - datasets.add((SysdynDataSet)o); - } - - String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter); - if(filter != null) { - ArrayList 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> { - private boolean disposed = false; - - public void dispose() { - disposed = true; - } - - @Override - public void execute(final ArrayList 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; - } - } - -} +/******************************************************************************* + * 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 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>() { + + @Override + public ArrayList perform(ReadGraph graph) throws DatabaseException { + JFreeChartResource jfree = JFreeChartResource.getInstance(graph); + + ArrayList series = new ArrayList(); + // 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 datasets = new ArrayList(); + + for(Object o : (ArrayList)object) { + if(o instanceof SysdynDataSet) + datasets.add((SysdynDataSet)o); + } + + String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter); + if(filter != null) { + ArrayList 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> { + private boolean disposed = false; + + public void dispose() { + disposed = true; + } + + @Override + public void execute(final ArrayList 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; + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBoundWidget.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBoundWidget.java index b7d009b9..9770e8f0 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBoundWidget.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/ConfidenceBoundWidget.java @@ -1,116 +1,116 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 confidenceBounds = ListUtils.toList(graph, confidenceBoundsList); - return confidenceBounds.get(index); - } - -} +/******************************************************************************* + * 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() { + + @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 confidenceBounds = ListUtils.toList(graph, confidenceBoundsList); + return confidenceBounds.get(index); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PieDataset.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PieDataset.java index 81d73100..d56f564f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PieDataset.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/PieDataset.java @@ -1,333 +1,333 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * Class representing a PieDataset in JFreeChart ontology - * @author Teemu Lempinen - * - */ -public class PieDataset extends AbstractDataset implements org.simantics.jfreechart.chart.PieDataset { - - private List seriesList; - private String realizationURI; - private DefaultPieDataset dataset; - - private HashMap colorMap; - private HashMap 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 getColorMap() { - return colorMap; - } - - /** - * Map of exploded statuses for slices in a pie chart. Name - * indicates the key of the slice. - * @return - */ - public HashMap getExplodedMap() { - return explodedMap; - } - - @Override - public Dataset getDataset() { - if(seriesList == null || seriesList.isEmpty() || SimanticsUI.getSession() == null) - return null; - - if(dataset == null) { - dataset = new DefaultPieDataset(); - } - - if(listener == null) { - listener = new DatasetListener(); - SimanticsUI.getSession().asyncRequest(new Read>() { - - @Override - public ArrayList perform(ReadGraph graph) throws DatabaseException { - JFreeChartResource jfree = JFreeChartResource.getInstance(graph); - - ArrayList series = new ArrayList(); - // Get properties for all series - if(seriesList != null) { - - colorMap = new HashMap(); - explodedMap = new HashMap(); - - 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 datasets = new ArrayList(); - - for(Object o : (ArrayList)object) { - if(o instanceof SysdynDataSet) - datasets.add((SysdynDataSet)o); - } - - String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter); - if(filter != null) { - ArrayList 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> { - - private boolean disposed = false; - - @Override - public void execute(final ArrayList 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; - } - } -} +/******************************************************************************* + * 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 { + + private List seriesList; + private String realizationURI; + private DefaultPieDataset dataset; + + private HashMap colorMap; + private HashMap 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 getColorMap() { + return colorMap; + } + + /** + * Map of exploded statuses for slices in a pie chart. Name + * indicates the key of the slice. + * @return + */ + public HashMap 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>() { + + @Override + public ArrayList perform(ReadGraph graph) throws DatabaseException { + JFreeChartResource jfree = JFreeChartResource.getInstance(graph); + + ArrayList series = new ArrayList(); + // Get properties for all series + if(seriesList != null) { + + colorMap = new HashMap(); + explodedMap = new HashMap(); + + 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 datasets = new ArrayList(); + + for(Object o : (ArrayList)object) { + if(o instanceof SysdynDataSet) + datasets.add((SysdynDataSet)o); + } + + String[] filter = graph.getPossibleRelatedValue(r, jfree.variableFilter); + if(filter != null) { + ArrayList 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> { + + private boolean disposed = false; + + @Override + public void execute(final ArrayList 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; + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityChartAxisAndVariablesTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityChartAxisAndVariablesTab.java index c414bf94..b5ce2115 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityChartAxisAndVariablesTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityChartAxisAndVariablesTab.java @@ -1,162 +1,162 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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); - } - - -} +/******************************************************************************* + * 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() { + + @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); + } + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDataset.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDataset.java index c4aba21f..3ff3ec19 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDataset.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/SensitivityDataset.java @@ -1,292 +1,292 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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(); - SimanticsUI.getSession().asyncRequest( - new SensitivityDatasetRequest(resource), - (DisposableListener, SensitivityDatasetProperties>>) datasetListener); - } - - if(timeListener == null || timeListener.isDisposed()) { - SimanticsUI.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, SensitivityDatasetProperties>> { - - private Resource dataset; - - public SensitivityDatasetRequest(Resource dataset) { - this.dataset = dataset; - } - - @Override - public Pair, SensitivityDatasetProperties> perform(ReadGraph graph) throws DatabaseException { - - Pair, 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 confidenceBounds = new ArrayList(); - - if(confidenceBoundsList != null) { - List 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, 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, SensitivityDatasetProperties>> { - - @Override - public void execute(Pair, SensitivityDatasetProperties> result) { - final ArrayList 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 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 sorter = new ArrayList(); - 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(); - } - - - } -} +/******************************************************************************* + * 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, 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, SensitivityDatasetProperties>> { + + private Resource dataset; + + public SensitivityDatasetRequest(Resource dataset) { + this.dataset = dataset; + } + + @Override + public Pair, SensitivityDatasetProperties> perform(ReadGraph graph) throws DatabaseException { + + Pair, 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 confidenceBounds = new ArrayList(); + + if(confidenceBoundsList != null) { + List 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, 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, SensitivityDatasetProperties>> { + + @Override + public void execute(Pair, SensitivityDatasetProperties> result) { + final ArrayList 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 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 sorter = new ArrayList(); + 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(); + } + + + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendView.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendView.java index 32e2b695..80f07c93 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendView.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/TrendView.java @@ -1,299 +1,297 @@ -/******************************************************************************* - * 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.exception.DatabaseException; -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; - -/** - * Trend view that shows all active simulation results for selected variables. - * - * @author Teemu Lempinen - * @author Tuomas Miettinen - * - */ -public class TrendView extends ViewPart { - - 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 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 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.asyncRequest(new Read() { - - @Override - public JFreeChart perform(ReadGraph graph) throws DatabaseException { - if(graph.hasStatement(chartResource)) { - IJFreeChart chart = graph.adapt(chartResource, IJFreeChart.class); - if(chart != null) { - return chart.getChart(); - } - } - return null; - } - }, listener); - } - } - - private class CustomChartListener implements Listener { - - 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) { - t.printStackTrace(); - } - - @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(); - } - - - - -} +/******************************************************************************* + * 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 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 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) 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 { + + 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(); + } + + + + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDataset.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDataset.java index 4866e219..015d318e 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDataset.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/trend/XYDataset.java @@ -1,349 +1,349 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 timeListener; - - protected DisposableListener getTimeListener() { - if(timeListener == null || timeListener.isDisposed()) { - timeListener = new TimeListener(); - } - return timeListener; - } - - protected Read getTimeRequest() { - return new Read() { - @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 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(); - SimanticsUI.getSession().asyncRequest( - new XYDatasetRequest(resource), - (DisposableListener, IRenderer>>) datasetListener); - - } - - if(timeListener == null || timeListener.isDisposed()) { - SimanticsUI.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, IRenderer>> { - - @Override - public void execute(Pair, IRenderer> result) { - final ArrayList 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 { - - 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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; - } -} +/******************************************************************************* + * 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 timeListener; + + protected DisposableListener getTimeListener() { + if(timeListener == null || timeListener.isDisposed()) { + timeListener = new TimeListener(); + } + return timeListener; + } + + protected Read getTimeRequest() { + return new Read() { + @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 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, 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, IRenderer>> { + + @Override + public void execute(Pair, IRenderer> result) { + final ArrayList 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 { + + 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() { + + @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; + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java index 46fa9c5d..38e53086 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/ExpressionUtils.java @@ -1,655 +1,661 @@ -/******************************************************************************* - * 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.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.simantics.ui.SimanticsUI; - -public class ExpressionUtils { - - /** - * 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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) { - e.printStackTrace(); - return; - } - - if(configuration == null) - return; - - ExpressionParser parser = new ExpressionParser(new StringReader("")); - Set variables = new HashSet(); - HashMap>> references = new HashMap>>(); - final HashMap>>> ranges = new HashMap>>>(); - HashMap>> forIndices = new HashMap>>(); - HashMap>> enumerationReferences = new HashMap>>(); - HashMap>> functionReferences = new HashMap>>(); - - // 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> 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(SimanticsUI.getSession()); - SysdynModel model = sdm.getModel(configuration); -// try { -// model.update(); -// } catch (DatabaseException e1) { -// e1.printStackTrace(); -// } - Configuration conf = model.getConfiguration(); - - // Check variable references - final HashMap modelVariables = new HashMap(); - HashSet ignoreVariables = new HashSet(); - if(!variables.isEmpty() || !functionReferences.isEmpty()) { - Set noSuchVariables = new HashSet(); - ArrayList 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 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> 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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) { - e.printStackTrace(); - } - - // 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> positions = getPositionsForVariables(references, variables); - for(ExpressionField ef : positions.keySet()) { - ef.setMissingLinkAnnotations(positions.get(ef)); - } - - } - } - - for(final ExpressionField ef : ranges.keySet()) { - List errors = new ArrayList(); - // 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 examineArrayRanges( - final Configuration configuration, - final HashMap>> ranges, - final HashMap> forIndices) { - - List result = Collections.emptyList(); - try { - result = SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public List perform(ReadGraph graph) throws DatabaseException { - return examineArrayRanges(graph, configuration, ranges, forIndices); - } - }); - } catch (DatabaseException e) { - e.printStackTrace(); - } - return result; - } - - static public List examineEnumerationReferences(Configuration configuration, HashMap> enumRefList) { - ArrayList result = new ArrayList(); - 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 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 examineArrayRanges( - ReadGraph graph, - Configuration configuration, - HashMap>> ranges, - HashMap> forIndices) throws DatabaseException { - HashMap errors = new HashMap(); - for(String name : ranges.keySet()) { - if(ranges.get(name) != null) { - for(List 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 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 removes = new HashSet(); - 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(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 examineSheetReferences( - Configuration configuration, - String functionKey, - List functionTokens, - String expression, - HashMap> expressionReferences) { - - List result = new ArrayList(); - - 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 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> getPositionsForVariables(HashMap>> references, Set variables) { - HashMap> result = new HashMap>(); - for(String s : variables) { - List tlist = new ArrayList(); - for(ExpressionField ef : references.keySet()) { - ArrayList positions = new ArrayList(); - 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)positions.clone()); - } else { - result.put(ef, (ArrayList)positions.clone()); - } - } - } - return result; - } - -} +/******************************************************************************* + * 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() { + + @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 variables = new HashSet(); + HashMap>> references = new HashMap>>(); + final HashMap>>> ranges = new HashMap>>>(); + HashMap>> forIndices = new HashMap>>(); + HashMap>> enumerationReferences = new HashMap>>(); + HashMap>> functionReferences = new HashMap>>(); + + // 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> 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 modelVariables = new HashMap(); + HashSet ignoreVariables = new HashSet(); + if(!variables.isEmpty() || !functionReferences.isEmpty()) { + Set noSuchVariables = new HashSet(); + ArrayList 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 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> 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() { + + @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> positions = getPositionsForVariables(references, variables); + for(ExpressionField ef : positions.keySet()) { + ef.setMissingLinkAnnotations(positions.get(ef)); + } + + } + } + + for(final ExpressionField ef : ranges.keySet()) { + List errors = new ArrayList(); + // 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 examineArrayRanges( + final Configuration configuration, + final HashMap>> ranges, + final HashMap> forIndices) { + + List result = Collections.emptyList(); + try { + result = Simantics.getSession().syncRequest(new Read>() { + + @Override + public List 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 examineEnumerationReferences(Configuration configuration, HashMap> enumRefList) { + ArrayList result = new ArrayList(); + 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 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 examineArrayRanges( + ReadGraph graph, + Configuration configuration, + HashMap>> ranges, + HashMap> forIndices) throws DatabaseException { + HashMap errors = new HashMap(); + for(String name : ranges.keySet()) { + if(ranges.get(name) != null) { + for(List 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 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 removes = new HashSet(); + 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(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 examineSheetReferences( + Configuration configuration, + String functionKey, + List functionTokens, + String expression, + HashMap> expressionReferences) { + + List result = new ArrayList(); + + 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 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> getPositionsForVariables(HashMap>> references, Set variables) { + HashMap> result = new HashMap>(); + for(String s : variables) { + List tlist = new ArrayList(); + for(ExpressionField ef : references.keySet()) { + ArrayList positions = new ArrayList(); + 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)positions.clone()); + } else { + result.put(ef, (ArrayList)positions.clone()); + } + } + } + return result; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/NameValidator.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/NameValidator.java index ff352c72..4d22120a 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/NameValidator.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/NameValidator.java @@ -1,378 +1,378 @@ -package org.simantics.sysdyn.ui.utils; - -import java.util.Collection; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -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; -import org.simantics.ui.SimanticsUI; - - -/** - * 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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; - } - -} +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() { + + @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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/VariableNameValidator.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/VariableNameValidator.java index b818a50b..2c74dcf9 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/VariableNameValidator.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/VariableNameValidator.java @@ -1,267 +1,267 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * 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 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> allReferences = new HashMap>(); - allReferences.putAll(parser.getReferences()); - allReferences.putAll(parser.getFunctionCallReferences()); - allReferences.putAll(parser.getEnumerationReferences()); - - List 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @Override - public Boolean perform(ReadGraph graph) throws DatabaseException { - return isValid(graph, variable, name, hasRange); - } - - }); - } catch (DatabaseException e) { - e.printStackTrace(); - } - return result; - } - -} +/******************************************************************************* + * 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 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> allReferences = new HashMap>(); + allReferences.putAll(parser.getReferences()); + allReferences.putAll(parser.getFunctionCallReferences()); + allReferences.putAll(parser.getEnumerationReferences()); + + List 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() { + + @Override + public Boolean perform(ReadGraph graph) throws DatabaseException { + return isValid(graph, variable, name, hasRange); + } + + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + return result; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ParameterExistsValidator.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ParameterExistsValidator.java index 0fb44b63..a29d9d81 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ParameterExistsValidator.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/validation/ParameterExistsValidator.java @@ -1,50 +1,50 @@ -package org.simantics.sysdyn.ui.validation; - -import java.util.Collection; - -import org.simantics.browsing.ui.swt.widgets.TrackedText; -import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport; -import org.simantics.jfreechart.chart.properties.AllVariablesOfModel; -import org.simantics.jfreechart.chart.properties.ChartVariable; -import org.simantics.jfreechart.chart.properties.VariableExistsValidator; -import org.simantics.db.Resource; -import org.simantics.db.management.ISessionContext; -import org.simantics.db.procedure.Listener; -import org.simantics.ui.SimanticsUI; -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; - - SimanticsUI.getSession().asyncRequest( - new AllVariablesOfModel(resource) - , new Listener>() { - - @Override - public void execute(Collection variables) { - ParameterExistsValidator.this.variables = variables; - } - - @Override - public void exception(Throwable t) { - t.printStackTrace(); - } - - @Override - public boolean isDisposed() { - return ParameterExistsValidator.this.text.isDisposed(); - } - - }); - } - -} +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>() { + + @Override + public void execute(Collection variables) { + ParameterExistsValidator.this.variables = variables; + } + + @Override + public void exception(Throwable t) { + t.printStackTrace(); + } + + @Override + public boolean isDisposed() { + return ParameterExistsValidator.this.text.isDisposed(); + } + + }); + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/viewUtils/SysdynDatasetSelectionListener.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/viewUtils/SysdynDatasetSelectionListener.java index 688ba1f7..29802c00 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/viewUtils/SysdynDatasetSelectionListener.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/viewUtils/SysdynDatasetSelectionListener.java @@ -1,225 +1,225 @@ -/******************************************************************************* - * 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.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.ui.SimanticsUI; -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 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> 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 = SimanticsUI.peekSession(); - if (session == null) - return; - - if(listener != null) - listener.dispose(); - - listener = new DisposableListener>() { - - @Override - public void execute(ArrayList vars) { - if(vars != null) - selectionChanged(vars); - } - - @Override - public void exception(Throwable t) { - t.printStackTrace(); - } - }; - - try { - session.syncRequest(new Read>() { - @Override - public ArrayList perform(ReadGraph graph) throws DatabaseException { - - // Model browser provides variables - Collection vars = ISelectionUtils.filterSetSelection(selection, Variable.class); - - if(vars.isEmpty()) { - // Selection did not contain variables - Set ress = ISelectionUtils.filterSetSelection(selection, Resource.class); - List 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 getDatasets(ReadGraph graph, Collection variables) throws DatabaseException { - - ArrayList datasets = new ArrayList(); - 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; - } - -} +/******************************************************************************* + * 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 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> 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>() { + + @Override + public void execute(ArrayList vars) { + if(vars != null) + selectionChanged(vars); + } + + @Override + public void exception(Throwable t) { + t.printStackTrace(); + } + }; + + try { + session.syncRequest(new Read>() { + @Override + public ArrayList perform(ReadGraph graph) throws DatabaseException { + + // Model browser provides variables + Collection vars = ISelectionUtils.filterSetSelection(selection, Variable.class); + + if(vars.isEmpty()) { + // Selection did not contain variables + Set ress = ISelectionUtils.filterSetSelection(selection, Resource.class); + List 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 getDatasets(ReadGraph graph, Collection variables) throws DatabaseException { + + ArrayList datasets = new ArrayList(); + 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/SharedFunctionsFolderNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/SharedFunctionsFolderNode.java index 2658fb65..ad227f92 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/SharedFunctionsFolderNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/SharedFunctionsFolderNode.java @@ -1,60 +1,60 @@ -package org.simantics.sysdyn.ui.wizards.functions; - -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.SimanticsUI; -import org.simantics.ui.utils.ResourceAdaptionUtils; - -public class SharedFunctionsFolderNode extends FunctionLibraryNode implements IDropTargetNode { - - public SharedFunctionsFolderNode(Resource resource) { - super(resource); - } - - @Override - public void delete() throws DeleteException { - SimanticsUI.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) { - SimanticsUI.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); - } - } - } - }); - } - } - -} +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 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); + } + } + } + }); + } + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java index f007253e..78d27745 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java @@ -26,6 +26,7 @@ import org.eclipse.swt.widgets.Label; 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; @@ -44,7 +45,6 @@ import org.simantics.graph.db.TransferableGraphs; 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 { @@ -172,7 +172,7 @@ 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); @@ -267,7 +267,7 @@ public class WizardFunctionsExportPage extends WizardPage { String name = null; try { - name = SimanticsUI.getSession().syncRequest(new Read() { + name = Simantics.getSession().syncRequest(new Read() { @Override public String perform(ReadGraph graph) throws DatabaseException { @@ -286,7 +286,7 @@ public class WizardFunctionsExportPage extends WizardPage { } 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); @@ -314,7 +314,7 @@ public class WizardFunctionsExportPage extends WizardPage { String root = null; try { - root = SimanticsUI.getSession().syncRequest(new Read() { + root = Simantics.getSession().syncRequest(new Read() { @Override public String perform(ReadGraph graph) throws DatabaseException { diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java index 68cd42df..889d5eaa 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java @@ -26,6 +26,7 @@ import org.eclipse.swt.widgets.Label; 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; @@ -34,7 +35,6 @@ import org.simantics.db.exception.DatabaseException; 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{ @@ -170,12 +170,12 @@ public class WizardFunctionsImportPage extends WizardPage{ title.setText("Select import location:"); try { - Resource input = SimanticsUI.getSession().syncRequest(new Read() { + Resource input = Simantics.getSession().syncRequest(new Read() { @Override public Resource perform(ReadGraph graph) throws DatabaseException { - Resource model = SimanticsUI.getProject().get(); + Resource model = Simantics.getProject().get(); return model; } @@ -302,7 +302,7 @@ public class WizardFunctionsImportPage extends WizardPage{ try { Boolean hasSharedOntologies; - hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read() { + hasSharedOntologies = Simantics.getSession().syncRequest(new Read() { @Override public Boolean perform(ReadGraph graph) throws DatabaseException { @@ -316,7 +316,7 @@ public class WizardFunctionsImportPage extends WizardPage{ }); if(!hasSharedOntologies) { - SimanticsUI.getSession().syncRequest(new WriteRequest() { + Simantics.getSession().syncRequest(new WriteRequest() { @Override public void perform(WriteGraph graph) throws DatabaseException { @@ -344,7 +344,7 @@ public class WizardFunctionsImportPage extends WizardPage{ final Resource root = ia.getRoot(); try { - SimanticsUI.getSession().syncRequest(new WriteRequest() { + Simantics.getSession().syncRequest(new WriteRequest() { @Override public void perform(WriteGraph graph) throws DatabaseException { diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/WizardMdlImportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/WizardMdlImportPage.java index d4679f7d..f763a135 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/WizardMdlImportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/mdl/WizardMdlImportPage.java @@ -1,213 +1,213 @@ -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.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.ui.SimanticsUI; - -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 = SimanticsUI.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; - } - - SimanticsUI.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); - } -} +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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java index 0dab6289..4163395c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java @@ -26,6 +26,7 @@ import org.eclipse.swt.widgets.Label; 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; @@ -39,7 +40,6 @@ import org.simantics.graph.db.TransferableGraphSource; 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 { @@ -171,7 +171,7 @@ 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); @@ -264,7 +264,7 @@ public class WizardModelsExportPage extends WizardPage { // 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 { diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java index a4c69b9c..1b2eb665 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java @@ -1,456 +1,456 @@ -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.db.Resource; -import org.simantics.db.exception.DatabaseException; -import org.simantics.sysdyn.ui.Activator; -import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI; -import org.simantics.ui.SimanticsUI; - -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 = SimanticsUI.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, SimanticsUI.getProject().get(), ia); - - // Check that imported resource was actually a model - //and fix changes made to old ontology versions - final Resource root = ia.getRoot(); - SimanticsUI.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 configurations = new HashSet(); - - 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); - } +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 configurations = new HashSet(); + + 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleComponentTypeNode.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleComponentTypeNode.java index 7b501811..d9a191a8 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleComponentTypeNode.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/ModuleComponentTypeNode.java @@ -1,161 +1,161 @@ -package org.simantics.sysdyn.ui.wizards.modules; - -import java.util.Collection; - -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; -import org.simantics.ui.SimanticsUI; - -public class ModuleComponentTypeNode extends AbstractNode implements IDeletableNode, IModifiableNode { - - - Listener configurationNameSynchronizer; - private boolean disposed = false; - private Resource configuration; - - public ModuleComponentTypeNode(Resource resource) { - super(resource); - - SimanticsUI.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() { - - @Override - public void execute(final String result) { - SimanticsUI.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; - } - }; - - SimanticsUI.getSession().asyncRequest(new Read() { - - @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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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(SimanticsUI.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 { - SimanticsUI.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 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); - } +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 implements IDeletableNode, IModifiableNode { + + + Listener 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() { + + @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() { + + @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() { + + @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 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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java index 69ec0fb6..a24c3d4f 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java @@ -28,6 +28,7 @@ import org.eclipse.swt.widgets.Label; 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; @@ -50,7 +51,6 @@ 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.ui.SimanticsUI; import org.simantics.utils.datastructures.ArrayMap; import org.simantics.utils.datastructures.Pair; @@ -178,7 +178,7 @@ public class WizardModulesExportPage extends WizardPage { 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); @@ -275,7 +275,7 @@ public class WizardModulesExportPage extends WizardPage { String name = null; try { - name = SimanticsUI.getSession().syncRequest(new Read() { + name = Simantics.getSession().syncRequest(new Read() { @Override public String perform(ReadGraph graph) throws DatabaseException { @@ -314,7 +314,7 @@ public class WizardModulesExportPage extends WizardPage { } if(name == null) return false; - SimanticsUI.getSession().asyncRequest(new ReadRequest() { + Simantics.getSession().asyncRequest(new ReadRequest() { @Override public void run(ReadGraph graph) throws DatabaseException { @@ -430,7 +430,7 @@ public class WizardModulesExportPage extends WizardPage { String root = null; try { - root = SimanticsUI.getSession().syncRequest(new Read() { + root = Simantics.getSession().syncRequest(new Read() { @Override public String perform(ReadGraph graph) throws DatabaseException { diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java index fa92bae2..5f13024c 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java @@ -26,6 +26,7 @@ import org.eclipse.swt.widgets.Label; 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; @@ -34,7 +35,6 @@ import org.simantics.db.exception.DatabaseException; 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; @@ -171,12 +171,12 @@ public class WizardModulesImportPage extends WizardPage{ title.setText("Select import location:"); try { - Resource input = SimanticsUI.getSession().syncRequest(new Read() { + Resource input = Simantics.getSession().syncRequest(new Read() { @Override public Resource perform(ReadGraph graph) throws DatabaseException { - Resource model = SimanticsUI.getProject().get(); + Resource model = Simantics.getProject().get(); return model; } @@ -313,7 +313,7 @@ public class WizardModulesImportPage extends WizardPage{ final Resource root = ia.getRoot(); try { - SimanticsUI.getSession().syncRequest(new WriteRequest() { + Simantics.getSession().syncRequest(new WriteRequest() { @Override public void perform(WriteGraph graph) throws DatabaseException { diff --git a/bundles/org.simantics.sysdyn/META-INF/MANIFEST.MF b/bundles/org.simantics.sysdyn/META-INF/MANIFEST.MF index 3e314909..0f836451 100644 --- a/bundles/org.simantics.sysdyn/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.sysdyn/META-INF/MANIFEST.MF @@ -34,7 +34,8 @@ Require-Bundle: org.simantics.objmap;bundle-version="0.1.0", 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, diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java index a0cb37d2..298b0279 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/OldSysdynExperiment.java @@ -1,892 +1,874 @@ -/******************************************************************************* - * 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 gnu.trove.set.hash.THashSet; - -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.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.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 org.simantics.ui.SimanticsUI; - -public class OldSysdynExperiment extends SysdynExperiment { - - protected Session session; - protected Runnable modificationListener; - protected SysdynModel sysdynModel; - protected boolean toggled = false; - @SuppressWarnings("rawtypes") - protected THashSet variableValueSubscriptions = new THashSet(); - @SuppressWarnings("rawtypes") - protected volatile VariableValueSubscription[] variableValueSubscriptionsSnapshot = null; - - protected HashMap 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 { - - private int value = 0; - private Listener listener = null; - - public PublishExternalRead(OldSysdynExperiment parameter) { - super(parameter); - } - - @Override - public void register(ReadGraph graph, Listener 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 getActiveResults() { - ArrayList result = new ArrayList(); - 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 result.saveToFile(file, progressMonitor); - } } - }; - } - - /** - * 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 getExperimentParameters(IModelicaMonitor monitor) { - Configuration configuration = sysdynModel.getConfiguration(); - HashMap parameters = new HashMap(); - 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 experimentParameters, HashMap 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 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 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 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 = SimanticsUI.getSession().syncRequest(new Read() { - - @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 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 parameterChanges = new HashMap(); - if(!structureChanged && defaultParameters != null) { - HashMap 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 - public void refresh(RequestProcessor session) { - session.asyncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - init(graph); - } - - }); - } - - @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; - 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) { - - } - -} - +/******************************************************************************* + * 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 variableValueSubscriptions = new THashSet(); + @SuppressWarnings("rawtypes") + protected volatile VariableValueSubscription[] variableValueSubscriptionsSnapshot = null; + + protected HashMap 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 { + + private int value = 0; + private Listener listener = null; + + public PublishExternalRead(OldSysdynExperiment parameter) { + super(parameter); + } + + @Override + public void register(ReadGraph graph, Listener 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 getActiveResults() { + ArrayList result = new ArrayList(); + 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 result.saveToFile(file, progressMonitor); + } } + }; + } + + /** + * 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 getExperimentParameters(IModelicaMonitor monitor) { + Configuration configuration = sysdynModel.getConfiguration(); + HashMap parameters = new HashMap(); + 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 experimentParameters, HashMap 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 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 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 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() { + + @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 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 parameterChanges = new HashMap(); + if(!structureChanged && defaultParameters != null) { + HashMap 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) { + + } + +} + diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java index 852153bc..b8269d4b 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynExperiment.java @@ -1,445 +1,453 @@ -/******************************************************************************* - * 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.simantics.sysdyn.solver.SolverSettings; -import org.simantics.sysdyn.solver.SolverSettings.SolverType; - -public class SysdynExperiment extends Experiment implements IDynamicExperiment, VariableSubscriptionManager { - - // 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 variableValueSubscriptions = new THashSet(); - @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 getActiveResults() { - ArrayList result = new ArrayList(); - 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 result.saveToFile(file, progressMonitor); - } } - }; - } - - @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) { - session.asyncRequest(new ReadRequest() { - - @Override - public void run(ReadGraph graph) throws DatabaseException { - init(graph); - } - - }); - } - - @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 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(); - } - -} - +/******************************************************************************* + * 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 variableValueSubscriptions = new THashSet(); + @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 getActiveResults() { + ArrayList result = new ArrayList(); + 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 result.saveToFile(file, progressMonitor); + } } + }; + } + + @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 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(); + } + +} + diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java index e97d6663..511f7452 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModel.java @@ -19,15 +19,18 @@ import java.util.HashSet; 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; @@ -70,6 +73,8 @@ import org.simantics.sysdyn.representation.expressions.StockExpression; 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; @@ -79,6 +84,8 @@ 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; @@ -177,80 +184,83 @@ public class SysdynModel implements IModel, IMappingListener, VariableSubscripti * @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> () { - @Override - public ArrayList perform(ReadGraph graph) throws DatabaseException { - ArrayList displayedResults = new ArrayList(); - // TODO: this can be done automatically with a listener + g.syncRequest(new AsyncReadRequest() { + + @Override + public void run(AsyncReadGraph g2) { + + g2.asyncRequest((Read>) graph -> { + ArrayList 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 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 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> () { - @Override - public void execute(ArrayList result) { - // Add the current result if there is one - displayedResults = result; - resultChanged(); - } + @Override + public void execute(ArrayList 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 @@ -421,10 +431,9 @@ public class SysdynModel implements IModel, IMappingListener, VariableSubscripti 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; } } diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java index c902f9cc..6afb2c3e 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynModelManager.java @@ -1,84 +1,95 @@ -/******************************************************************************* - * 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; - -/** - * Manages system dynamic models. - * @author Hannu Niemistö - */ -public class SysdynModelManager { - WeakHashMap models = - new WeakHashMap(); // 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) { - 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) { - e.printStackTrace(); - } - - model = models.get(resource); - } - return model; - } - } - - /** - * Should be used if called inside a transaction - */ - public SysdynModel getModel(ReadGraph g, Resource resource) { - synchronized(models) { - SysdynModel model = models.get(resource); - if(model == null) { - model = new SysdynModel(g, resource); - 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; - } -} +/******************************************************************************* + * 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 models = + new WeakHashMap(); // 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; + } +} diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java index ec9ff751..21da77fd 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/Function.java @@ -1,572 +1,572 @@ -package org.simantics.sysdyn.utils; - -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; - -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.ui.SimanticsUI; -import org.simantics.utils.datastructures.Pair; - - -/** - * Class to store function name, type, and parameters. - * - * @author Tuomas Miettinen - * - */ -public class Function implements Comparable{ - - private final String name; - private final Type type; - private final ArrayList inputList; - private final ArrayList 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 units, - Function f, - ArrayList functions, - boolean allowEquivalents, - HashMap 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 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 variableLengthLabels; - } - - public static class Output extends Parameter { - } - - public enum Type { - USER_DEFINED, - SHARED, - SYSDYN, - MODELICA, - MODELICA_ARRAY, - VENSIM, - XMILE - } - - public Function( - String name, - ArrayList inputList, - ArrayList outputList, - Type type, - String description){ - - this.name = new String(name); - - this.type = type; - - if (inputList != null) - this.inputList = inputList; - else - this.inputList = new ArrayList(); - - if (outputList != null) - this.outputList = outputList; - else - this.outputList = new ArrayList(); - - 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 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 getInputList() { - return inputList; - } - - public ArrayList 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 getFunctionInputs(ReadGraph graph, SysdynResource sr, Resource r) throws DatabaseException { - Resource inputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_inputs); - ArrayList inputParameters = new ArrayList(); - 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(); - 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 getFunctionOutputs(ReadGraph graph, - SysdynResource sr, Resource r) throws DatabaseException { - Resource outputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_outputs); - ArrayList outputParameters = new ArrayList(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 getFunctionsOfType(ReadGraph graph, String functionTypeUri, Type functionType) throws DatabaseException { - SysdynResource sr = SysdynResource.getInstance(graph); - Layer0 l0 = Layer0.getInstance(graph); - ArrayList functions = new ArrayList(); - - // 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 inputs = getFunctionInputs(graph, sr, r); - ArrayList 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 getAllBuiltInFunctions(ReadGraph graph) throws DatabaseException { - ArrayList functions = new ArrayList(); - - // 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 getAllBuiltInFunctions() { - ArrayList result = null; - - //Finding functions - try { - result = SimanticsUI.getSession().syncRequest(new Read>() { - @Override - public ArrayList 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 getSharedFunctions(final Resource model) { - ArrayList functions = new ArrayList(); - if (model == null) { - return functions; - } - - try { - functions = SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public ArrayList perform(ReadGraph graph) throws DatabaseException { - Layer0 l0 = Layer0.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - - // Full names of the collected functions - ArrayList sharedFunctions = new ArrayList(); - - Collection 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 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 getUserDefinedFunctions(final Resource model) { - ArrayList functions = new ArrayList(); - if (model == null) { - return functions; - } - - try { - functions = SimanticsUI.getSession().syncRequest(new Read>() { - - @Override - public ArrayList perform(ReadGraph graph) throws DatabaseException { - Layer0 l0 = Layer0.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - - // Full names of the collected functions - ArrayList userFunctions = new ArrayList(); - - // Get all function resources under model recursively - Collection 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 getFunctionsInside(ReadGraph graph, Resource r) throws DatabaseException { - Layer0 l0 = Layer0.getInstance(graph); - SysdynResource sr = SysdynResource.getInstance(graph); - ArrayList functions = new ArrayList(); - functions.addAll(graph.syncRequest(new ObjectsWithType( - r, - l0.ConsistsOf, - sr.SysdynModelicaFunction))); - Collection 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", "
"); - } - - /** - * 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> argumentUnits, - HashMap correspondences, - ArrayList functions, - boolean allowEquivalents, - HashMap units) throws UnitCheckingException { - ArrayList inputMatches = new ArrayList(); // 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; - } -} +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{ + + private final String name; + private final Type type; + private final ArrayList inputList; + private final ArrayList 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 units, + Function f, + ArrayList functions, + boolean allowEquivalents, + HashMap 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 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 variableLengthLabels; + } + + public static class Output extends Parameter { + } + + public enum Type { + USER_DEFINED, + SHARED, + SYSDYN, + MODELICA, + MODELICA_ARRAY, + VENSIM, + XMILE + } + + public Function( + String name, + ArrayList inputList, + ArrayList outputList, + Type type, + String description){ + + this.name = new String(name); + + this.type = type; + + if (inputList != null) + this.inputList = inputList; + else + this.inputList = new ArrayList(); + + if (outputList != null) + this.outputList = outputList; + else + this.outputList = new ArrayList(); + + 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 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 getInputList() { + return inputList; + } + + public ArrayList 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 getFunctionInputs(ReadGraph graph, SysdynResource sr, Resource r) throws DatabaseException { + Resource inputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_inputs); + ArrayList inputParameters = new ArrayList(); + 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(); + 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 getFunctionOutputs(ReadGraph graph, + SysdynResource sr, Resource r) throws DatabaseException { + Resource outputs = graph.getPossibleObject(r, sr.SysdynModelicaFunction_outputs); + ArrayList outputParameters = new ArrayList(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 getFunctionsOfType(ReadGraph graph, String functionTypeUri, Type functionType) throws DatabaseException { + SysdynResource sr = SysdynResource.getInstance(graph); + Layer0 l0 = Layer0.getInstance(graph); + ArrayList functions = new ArrayList(); + + // 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 inputs = getFunctionInputs(graph, sr, r); + ArrayList 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 getAllBuiltInFunctions(ReadGraph graph) throws DatabaseException { + ArrayList functions = new ArrayList(); + + // 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 getAllBuiltInFunctions() { + ArrayList result = null; + + //Finding functions + try { + result = Simantics.getSession().syncRequest(new Read>() { + @Override + public ArrayList 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 getSharedFunctions(final Resource model) { + ArrayList functions = new ArrayList(); + if (model == null) { + return functions; + } + + try { + functions = Simantics.getSession().syncRequest(new Read>() { + + @Override + public ArrayList perform(ReadGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + + // Full names of the collected functions + ArrayList sharedFunctions = new ArrayList(); + + Collection 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 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 getUserDefinedFunctions(final Resource model) { + ArrayList functions = new ArrayList(); + if (model == null) { + return functions; + } + + try { + functions = Simantics.getSession().syncRequest(new Read>() { + + @Override + public ArrayList perform(ReadGraph graph) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + + // Full names of the collected functions + ArrayList userFunctions = new ArrayList(); + + // Get all function resources under model recursively + Collection 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 getFunctionsInside(ReadGraph graph, Resource r) throws DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + SysdynResource sr = SysdynResource.getInstance(graph); + ArrayList functions = new ArrayList(); + functions.addAll(graph.syncRequest(new ObjectsWithType( + r, + l0.ConsistsOf, + sr.SysdynModelicaFunction))); + Collection 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", "
"); + } + + /** + * 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> argumentUnits, + HashMap correspondences, + ArrayList functions, + boolean allowEquivalents, + HashMap units) throws UnitCheckingException { + ArrayList inputMatches = new ArrayList(); // 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; + } +} diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java index b87ce839..38157193 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/LoopUtils.java @@ -1,336 +1,336 @@ -/******************************************************************************* - * 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.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; -import org.simantics.ui.SimanticsUI; - -/** - * Utils for loops - * @author Tuomas Miettinen - * - */ -public class LoopUtils { - - private static class ElementaryLoopItem { - public int mapping; - ArrayList dependencies; - - public ElementaryLoopItem(int mapping, ArrayList 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> getLoops(final Resource r) { - List> loops = Collections.emptyList(); - try { - loops = SimanticsUI.getSession().syncRequest(new Read>>() { - - @Override - public List> perform(ReadGraph graph) - throws DatabaseException { - return getLoops(graph, r); - } - }); - } catch (DatabaseException e) { - e.printStackTrace(); - } - return loops; - } - - @SuppressWarnings({ "rawtypes", "unchecked", "unused" }) - public static List> getLoops(ReadGraph g, Resource r) throws DatabaseException, ServiceException { - // Get all loops in the diagram. - List> cycles = getAllLoopsInDiagram(g, r); - - // Collect all those loops in which the original resource exists. - List> loops = new ArrayList>(); - 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> 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 variables = g.getObjects(configuration, l0.ConsistsOf); - ArrayList shadows = new ArrayList(); - - // Leave only independent variables and shadows (and modules) - Iterator 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 elementaryLoopItems = new HashMap(); - for (Resource variable : variables) { - ArrayList dependingVariables = new ArrayList(); - // Add forward dependencies and flows from valves. - Collection 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 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 dependingVariables = new ArrayList(); - Collection 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 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> 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 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.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 loop = ListUtils.toPossibleList(graph, loopResource); - for (int i = 0; i < loop.size(); ++i) { - boolean skipBackwardFlows = false; - - // Go through forward dependencies and flows - Collection forwardDependencies = graph.getObjects(loop.get(i), sr.Variable_isTailOf); - - // And also through the forward dependencies of possible shadows. - Collection 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 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; - } -} +/******************************************************************************* + * 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 dependencies; + + public ElementaryLoopItem(int mapping, ArrayList 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> getLoops(final Resource r) { + List> loops = Collections.emptyList(); + try { + loops = Simantics.getSession().syncRequest(new Read>>() { + + @Override + public List> perform(ReadGraph graph) + throws DatabaseException { + return getLoops(graph, r); + } + }); + } catch (DatabaseException e) { + e.printStackTrace(); + } + return loops; + } + + @SuppressWarnings({ "rawtypes", "unchecked", "unused" }) + public static List> getLoops(ReadGraph g, Resource r) throws DatabaseException, ServiceException { + // Get all loops in the diagram. + List> cycles = getAllLoopsInDiagram(g, r); + + // Collect all those loops in which the original resource exists. + List> loops = new ArrayList>(); + 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> 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 variables = g.getObjects(configuration, l0.ConsistsOf); + ArrayList shadows = new ArrayList(); + + // Leave only independent variables and shadows (and modules) + Iterator 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 elementaryLoopItems = new HashMap(); + for (Resource variable : variables) { + ArrayList dependingVariables = new ArrayList(); + // Add forward dependencies and flows from valves. + Collection 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 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 dependingVariables = new ArrayList(); + Collection 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 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> 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 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.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 loop = ListUtils.toPossibleList(graph, loopResource); + for (int i = 0; i < loop.size(); ++i) { + boolean skipBackwardFlows = false; + + // Go through forward dependencies and flows + Collection forwardDependencies = graph.getObjects(loop.get(i), sr.Variable_isTailOf); + + // And also through the forward dependencies of possible shadows. + Collection 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 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; + } +} diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java index 442dbe19..96c37507 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/ModelUtils.java @@ -1,213 +1,210 @@ -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.resource.SpreadsheetResource; -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); - SpreadsheetResource SHEET = SpreadsheetResource.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, "Diagrammi") - ); - - g.claim(model, mu.SIMU.HasConfiguration, conf); - - Resource book = g.newResource(); - g.claim(book, l0.InstanceOf, null, SHEET.Book); - g.addLiteral(book, l0.HasName, l0.NameOf, l0.String, "Book" + UUID.randomUUID().toString(), Bindings.STRING); - g.claim(conf, l0.ConsistsOf, l0.PartOf, book); - - SheetUtils.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); - - } -} +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); + + } +} diff --git a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java index 5525cc8d..ed42af9b 100644 --- a/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java +++ b/bundles/org.simantics.sysdyn/src/org/simantics/sysdyn/utils/SheetUtils.java @@ -1,126 +1,84 @@ -/******************************************************************************* - * 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.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.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 { - - public static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException { - Layer0 L0 = Layer0.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, L0.ConsistsOf); - } - 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.Headers); - 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, L0.HasChildVariables, L0.HasChildVariables_Inverse, newCell); -// -// } - return result; - - } - - 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(); - } - } -} +/******************************************************************************* + * 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(); + } + } +} diff --git a/releng/org.simantics.sysdyn.repository/pom.xml b/releng/org.simantics.sysdyn.repository/pom.xml index 9d54b1fa..515ad56a 100644 --- a/releng/org.simantics.sysdyn.repository/pom.xml +++ b/releng/org.simantics.sysdyn.repository/pom.xml @@ -1,72 +1,89 @@ - - 4.0.0 - org.simantics.sysdyn.repository - 1.10.0-SNAPSHOT - eclipse-repository - - - org.simantics - org.simantics.sysdyn.root.releng - 1.0.0-SNAPSHOT - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-clean-plugin - - - [2.5,) - - - clean - - - - - - - - - - org.eclipse.tycho - - - tycho-packaging-plugin - - - [0.26.0,) - - - - build-qualifier-aggregator - - - - - - - - - - - - - - - + + 4.0.0 + org.simantics.sysdyn.repository + 1.10.0-SNAPSHOT + eclipse-repository + + + org.simantics + org.simantics.sysdyn.root.releng + 1.0.0-SNAPSHOT + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-clean-plugin + + + [2.5,) + + + clean + + + + + + + + + + org.eclipse.tycho + + + tycho-packaging-plugin + + + [0.26.0,) + + + + build-qualifier-aggregator + + + + + + + + + + org.simantics + + graph-builder-maven-plugin + + + [0.0.9,) + + + compile-graphs + + + + + + + + + + + + + +