-/*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.browser;\r
-\r
-import java.util.Arrays;\r
-import java.util.Collections;\r
-import java.util.HashSet;\r
-import java.util.Set;\r
-\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.simantics.browsing.ui.GraphExplorer;\r
-import org.simantics.browsing.ui.NodeContext;\r
-import org.simantics.browsing.ui.platform.GraphExplorerView;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.ContextMenuInitializer;\r
-import org.simantics.browsing.ui.swt.DefaultSelectionDataResolver;\r
-import org.simantics.browsing.ui.swt.GraphExplorerFactory;\r
-import org.simantics.browsing.ui.swt.IContextMenuInitializer;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ResourceRead;\r
-import org.simantics.db.common.utils.Logger;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.SelectionHints;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.db.layer0.variable.Variables;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.browser.nodes.VariableNode;\r
-import org.simantics.sysdyn.ui.properties.SysdynPropertyPage;\r
-import org.simantics.ui.selection.AnyResource;\r
-import org.simantics.ui.selection.AnyVariable;\r
-import org.simantics.ui.selection.WorkbenchSelectionContentType;\r
-import org.simantics.ui.workbench.IPropertyPage;\r
-import org.simantics.utils.datastructures.BinaryFunction;\r
-import org.simantics.utils.datastructures.hints.IHintContext;\r
-\r
-\r
-public class SysdynBrowser extends GraphExplorerView {\r
- \r
- private static final Set<String> browseContexts = new HashSet<String>(Arrays.asList(\r
- "http://www.simantics.org/Sysdyn-1.1/Browser", \r
- "http://www.semantum.fi/SimupediaWorkbench-1.0/OldBrowser",\r
- "http://www.simantics.org/Image-1.1/Browser")); \r
-\r
- private BinaryFunction<Object[], GraphExplorer, Object[]> selectionTransformation = new BinaryFunction<Object[], GraphExplorer, Object[]>() {\r
-\r
- \r
- /*\r
- private Key[] KEYS = new Key[] { SelectionHints.KEY_MAIN };\r
- \r
- @Override\r
- public Object[] call(GraphExplorer explorer, Object[] objects) {\r
- Object[] result = new Object[objects.length];\r
- for (int i = 0; i < objects.length; i++) {\r
- SelectionElement context = new SelectionElement(KEYS, objects[i]);\r
- context.setHint(SelectionHints.KEY_MAIN, objects[i]);\r
- result[i] = context;\r
- }\r
- return result;\r
- }\r
- */\r
- \r
- class SelectionElement extends AdaptableHintContext {\r
-\r
- private Variable variable;\r
- private Resource resource;\r
- \r
- public SelectionElement(Variable variable, Resource resource, Key... keys) {\r
- super(keys);\r
- this.variable = variable;\r
- this.resource = resource;\r
- }\r
-\r
- @SuppressWarnings("unchecked")\r
- @Override\r
- public <T> T getContent(WorkbenchSelectionContentType<T> contentType) {\r
- if(contentType instanceof AnyResource) return (T)resource;\r
- else if(contentType instanceof AnyVariable) {\r
- AnyVariable type = (AnyVariable)contentType;\r
- try {\r
- \r
- if(variable != null) return (T)variable;\r
- \r
- if(resource == null) return null;\r
- \r
- return (T) type.processor.sync(new ResourceRead<Variable>(resource) {\r
- @Override\r
- public Variable perform(ReadGraph graph) throws DatabaseException {\r
- return Variables.getPossibleVariable(graph, resource);\r
- }\r
- \r
- });\r
- } catch (DatabaseException e) {\r
- Logger.defaultLogError(e);\r
- }\r
- } \r
- return null;\r
- } \r
-\r
- }\r
-\r
- @Override\r
- public Object[] call(GraphExplorer explorer, Object[] objects) {\r
- Object[] result = new Object[objects.length];\r
- for (int i = 0; i < objects.length; i++) {\r
- \r
- NodeContext ctx = (NodeContext)objects[i]; \r
- @SuppressWarnings("unchecked")\r
- VariableNode<Variable> vn = (VariableNode<Variable>) ctx.getAdapter(VariableNode.class);\r
- IHintContext context;\r
- if(vn != null && vn.getVariable() != null) {\r
- context = new SelectionElement(vn.getVariable(),vn.data, SelectionHints.KEY_MAIN, SelectionHints.KEY_SELECTION_PROPERTY);\r
- context.setHint(SelectionHints.KEY_MAIN, new BrowserSelection(objects[i], vn));\r
- context.setHint(SelectionHints.KEY_SELECTION_PROPERTY, vn.getVariable());\r
- } else {\r
- Object resource = ctx.getAdapter(Resource.class);\r
- context = new SelectionElement(null, resource == null ? null : (Resource)resource, SelectionHints.KEY_MAIN);\r
- context.setHint(SelectionHints.KEY_MAIN, objects[i]);\r
- }\r
- result[i] = context;\r
- }\r
- return result;\r
- }\r
- \r
- };\r
- \r
- protected GraphExplorer createExplorerControl(Composite parent) {\r
- return GraphExplorerFactory.getInstance()\r
- .selectionDataResolver(new DefaultSelectionDataResolver())\r
- .selectionTransformation(selectionTransformation)\r
- .create(parent, getStyle());\r
- }\r
- \r
- @Override\r
- protected IContextMenuInitializer getContextMenuInitializer() {\r
- return new ContextMenuInitializer("#SysdynBrowserPopup");\r
- }\r
- \r
- @Override\r
- protected Set<String> getBrowseContexts() {\r
- return browseContexts;\r
- }\r
- \r
- @Override\r
- protected void createControls(Composite parent) {\r
- // Make sure the resource manager of this plug-in is initialized\r
- // properly before using it in this browser.\r
- Activator.initializeResourceManager(parent.getDisplay());\r
-\r
- super.createControls(parent);\r
- //IToolBarManager toolBar = getViewSite().getActionBars().getToolBarManager();\r
- //toolBar.add(new HomeAction());\r
- }\r
- \r
- @SuppressWarnings("rawtypes")\r
- @Override\r
- public Object getAdapter(Class adapter) {\r
- if (adapter == IPropertyPage.class)\r
- return new SysdynPropertyPage(getSite(), Collections.singleton(SysdynResource.URIs.Browser));\r
- return super.getAdapter(adapter);\r
- }\r
- \r
- public SysdynBrowser() {\r
- hideComparatorSelector = true;\r
- hideViewpointSelector = true;\r
- }\r
- \r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2010 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.browser;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.eclipse.swt.widgets.Composite;
+import org.simantics.browsing.ui.GraphExplorer;
+import org.simantics.browsing.ui.NodeContext;
+import org.simantics.browsing.ui.platform.GraphExplorerView;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+import org.simantics.browsing.ui.swt.ContextMenuInitializer;
+import org.simantics.browsing.ui.swt.DefaultSelectionDataResolver;
+import org.simantics.browsing.ui.swt.GraphExplorerFactory;
+import org.simantics.browsing.ui.swt.IContextMenuInitializer;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ResourceRead;
+import org.simantics.db.common.utils.Logger;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.SelectionHints;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.Activator;
+import org.simantics.sysdyn.ui.browser.nodes.VariableNode;
+import org.simantics.sysdyn.ui.properties.SysdynPropertyPage;
+import org.simantics.ui.selection.AnyResource;
+import org.simantics.ui.selection.AnyVariable;
+import org.simantics.ui.selection.WorkbenchSelectionContentType;
+import org.simantics.ui.workbench.IPropertyPage;
+import org.simantics.utils.datastructures.BinaryFunction;
+import org.simantics.utils.datastructures.hints.IHintContext;
+
+
+public class SysdynBrowser extends GraphExplorerView {
+
+ private static final Set<String> browseContexts = new HashSet<String>(Arrays.asList(
+ "http://www.simantics.org/Sysdyn-1.1/Browser",
+ "http://www.semantum.fi/SimupediaWorkbench-1.0/OldBrowser",
+ "http://www.simantics.org/Image-1.1/Browser"));
+
+ private BinaryFunction<Object[], GraphExplorer, Object[]> selectionTransformation = new BinaryFunction<Object[], GraphExplorer, Object[]>() {
+
+
+ /*
+ private Key[] KEYS = new Key[] { SelectionHints.KEY_MAIN };
+
+ @Override
+ public Object[] call(GraphExplorer explorer, Object[] objects) {
+ Object[] result = new Object[objects.length];
+ for (int i = 0; i < objects.length; i++) {
+ SelectionElement context = new SelectionElement(KEYS, objects[i]);
+ context.setHint(SelectionHints.KEY_MAIN, objects[i]);
+ result[i] = context;
+ }
+ return result;
+ }
+ */
+
+ class SelectionElement extends AdaptableHintContext {
+
+ private Variable variable;
+ private Resource resource;
+
+ public SelectionElement(Variable variable, Resource resource, Key... keys) {
+ super(keys);
+ this.variable = variable;
+ this.resource = resource;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T getContent(WorkbenchSelectionContentType<T> contentType) {
+ if(contentType instanceof AnyResource) return (T)resource;
+ else if(contentType instanceof AnyVariable) {
+ AnyVariable type = (AnyVariable)contentType;
+ try {
+
+ if(variable != null) return (T)variable;
+
+ if(resource == null) return null;
+
+ return (T) type.processor.sync(new ResourceRead<Variable>(resource) {
+ @Override
+ public Variable perform(ReadGraph graph) throws DatabaseException {
+ return Variables.getPossibleVariable(graph, resource);
+ }
+
+ });
+ } catch (DatabaseException e) {
+ Logger.defaultLogError(e);
+ }
+ }
+ return null;
+ }
+
+ }
+
+ @Override
+ public Object[] call(GraphExplorer explorer, Object[] objects) {
+ Object[] result = new Object[objects.length];
+ for (int i = 0; i < objects.length; i++) {
+
+ NodeContext ctx = (NodeContext)objects[i];
+ @SuppressWarnings("unchecked")
+ VariableNode<Variable> vn = (VariableNode<Variable>) ctx.getAdapter(VariableNode.class);
+ IHintContext context;
+ if(vn != null && vn.getVariable() != null) {
+ context = new SelectionElement(vn.getVariable(),vn.data, SelectionHints.KEY_MAIN, SelectionHints.KEY_SELECTION_PROPERTY);
+ context.setHint(SelectionHints.KEY_MAIN, new BrowserSelection(objects[i], vn));
+ context.setHint(SelectionHints.KEY_SELECTION_PROPERTY, vn.getVariable());
+ } else {
+ Object resource = ctx.getAdapter(Resource.class);
+ context = new SelectionElement(null, resource == null ? null : (Resource)resource, SelectionHints.KEY_MAIN);
+ context.setHint(SelectionHints.KEY_MAIN, objects[i]);
+ }
+ result[i] = context;
+ }
+ return result;
+ }
+
+ };
+
+ protected GraphExplorer createExplorerControl(Composite parent) {
+ return GraphExplorerFactory.getInstance()
+ .selectionDataResolver(new DefaultSelectionDataResolver())
+ .selectionTransformation(selectionTransformation)
+ .create(parent, getStyle());
+ }
+
+ @Override
+ protected IContextMenuInitializer getContextMenuInitializer() {
+ return new ContextMenuInitializer("#SysdynBrowserPopup");
+ }
+
+ @Override
+ protected Set<String> getBrowseContexts() {
+ return browseContexts;
+ }
+
+ @Override
+ protected void createControls(Composite parent) {
+ // Make sure the resource manager of this plug-in is initialized
+ // properly before using it in this browser.
+ Activator.initializeResourceManager(parent.getDisplay());
+
+ super.createControls(parent);
+ //IToolBarManager toolBar = getViewSite().getActionBars().getToolBarManager();
+ //toolBar.add(new HomeAction());
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public Object getAdapter(Class adapter) {
+ if (adapter == IPropertyPage.class)
+ return new SysdynPropertyPage(getSite(), Collections.singleton(SysdynResource.URIs.Browser));
+ return super.getAdapter(adapter);
+ }
+
+ public SysdynBrowser() {
+ hideComparatorSelector = true;
+ hideViewpointSelector = true;
+ }
+
+}
-package org.simantics.sysdyn.ui.properties;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashSet;\r
-import java.util.List;\r
-import java.util.Set;\r
-\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.viewers.StructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.eclipse.swt.widgets.TreeItem;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupportImpl;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.ResourceArray;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.utils.ListUtils;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;\r
-import org.simantics.utils.RunnableWithObject;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.threads.SWTThread;\r
-\r
-public class ArrayIndexesTab extends LabelPropertyTabContributor implements Widget{\r
-\r
- GraphExplorerComposite availableEnumerationsExplorer;\r
- GraphExplorerComposite usedEnumerationsExplorer;\r
- private WidgetSupportImpl buttonSupport;\r
- private org.simantics.browsing.ui.swt.widgets.Label usedEnumerationsLabel;\r
- private Button down;\r
- private Button up;\r
- private Button remove;\r
- \r
- public ArrayIndexesTab(Object variables) {\r
- super(variables);\r
- }\r
-\r
-\r
- @Override\r
- public void createControls(Composite body, IWorkbenchSite site,\r
- ISessionContext context, WidgetSupport support) {\r
- support.register(this);\r
- \r
- buttonSupport = new WidgetSupportImpl();\r
- \r
- GridLayoutFactory.fillDefaults().numColumns(4).applyTo(body);\r
- \r
- \r
- Composite available = new Composite(body, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().applyTo(available);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(available);\r
- Label label = new Label(available, SWT.None);\r
- label.setText("Available Enumerations");\r
- availableEnumerationsExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), site, available, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);\r
- \r
- availableEnumerationsExplorer\r
- .setBrowseContexts(SysdynResource.URIs.AvailableVariableIndexes);\r
- availableEnumerationsExplorer.setColumns(ColumnKeys.ENUMERATION_TABLE_COLUMNS);\r
- availableEnumerationsExplorer.setInputSource(new SingleSelectionInputSource(\r
- ResourceArray.class));\r
-\r
- availableEnumerationsExplorer.finish();\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- availableEnumerationsExplorer);\r
- \r
- Control c = availableEnumerationsExplorer.getExplorerControl();\r
- if (c instanceof Tree)\r
- ((Tree) c).setLinesVisible(true);\r
- \r
- \r
- Button add = new Button(body, buttonSupport, SWT.NONE);\r
- add.setText(" -> ");\r
- \r
- add.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
-\r
- List<Resource> enumerationResources;\r
-\r
- @Override\r
- public void beforeApply() { \r
- enumerationResources = getSelectedResources(availableEnumerationsExplorer);\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, ResourceArray input)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- for(Resource r : input.resources) {\r
- Resource arrayIndexes = graph.getPossibleObject(r, sr.Variable_arrayIndexesList);\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Added new enumeration(s) ");\r
- if(arrayIndexes == null) {\r
- arrayIndexes = ListUtils.create(graph, enumerationResources);\r
- graph.claim(r, sr.Variable_arrayIndexesList, arrayIndexes);\r
- sb.append(enumerationResources.toString() + " ");\r
- } else {\r
- ArrayList<Resource> filtered = new ArrayList<Resource>();\r
- for(Resource enumeration : enumerationResources) {\r
- if(ListUtils.getNode(graph, arrayIndexes, enumeration) == null) {\r
- filtered.add(enumeration);\r
- sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");\r
- }\r
- }\r
- if (filtered.isEmpty())\r
- return;\r
- ListUtils.insertBack(graph, arrayIndexes, filtered);\r
- }\r
- sb.append("to " + graph.getPossibleRelatedValue2(r, Layer0.getInstance(graph).HasName, Bindings.STRING));\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- updateUsedButtons(graph, arrayIndexes);\r
- }\r
- }\r
- });\r
- \r
- Composite used = new Composite(body, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().applyTo(used);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(used);\r
- usedEnumerationsLabel = new org.simantics.browsing.ui.swt.widgets.Label(used, buttonSupport, SWT.None);\r
- usedEnumerationsLabel.setTextFactory(new ReadFactoryImpl<ResourceArray, String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph, ResourceArray input) throws DatabaseException {\r
- if(input.size() < 2)\r
- return "Used Enumerations";\r
- else {\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Enumerations in: ");\r
- boolean first = true;\r
- for(Resource r : input) {\r
- if(!first)\r
- sb.append(", ");\r
- first = false;\r
- \r
- String name = NameUtils.getSafeName(graph, r);\r
- sb.append(name);\r
- }\r
- return sb.toString();\r
- }\r
- }\r
-\r
- });\r
- \r
- usedEnumerationsExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), site, used, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);\r
- \r
- usedEnumerationsExplorer\r
- .setBrowseContexts(SysdynResource.URIs.UsedVariableIndexes);\r
- usedEnumerationsExplorer.setColumns(ColumnKeys.ENUMERATION_TABLE_COLUMNS);\r
- usedEnumerationsExplorer.setInputSource(new SingleSelectionInputSource(\r
- ResourceArray.class));\r
-\r
- usedEnumerationsExplorer.finish();\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- usedEnumerationsExplorer);\r
- \r
- Control c2 = usedEnumerationsExplorer.getExplorerControl();\r
- if (c2 instanceof Tree)\r
- ((Tree) c2).setLinesVisible(true);\r
- \r
- Composite buttons = new Composite(body, SWT.None);\r
- GridLayoutFactory.fillDefaults().applyTo(buttons);\r
- \r
- up = new Button(buttons, buttonSupport, SWT.NONE);\r
- up.setText("Up");\r
- up.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
-\r
- List<Integer> selectedIndexes;\r
-\r
- @Override\r
- public void beforeApply() {\r
- selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, ResourceArray input)\r
- throws DatabaseException {\r
- \r
- Layer0 L0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- for(Resource variable : input) {\r
- Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
- if(arrayIndexes != null) {\r
- List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);\r
- List<Resource> toBeMoved = new ArrayList<Resource>();\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Moved enumeration(s) ");\r
- for(Integer index : selectedIndexes) {\r
- if(index < enumerations.size()) {\r
- Resource enumeration = enumerations.get(index);\r
- toBeMoved.add(enumeration);\r
- }\r
-\r
- }\r
- boolean moved = false;\r
- for(Resource enumeration : toBeMoved) {\r
- Resource node = ListUtils.getNode(graph, arrayIndexes, enumeration);\r
- Resource prev = graph.getSingleObject(node, L0.List_Previous);\r
- if(!arrayIndexes.equals(prev) && !toBeMoved.contains(graph.getPossibleObject(prev, L0.List_Element))) {\r
- sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");\r
- moved = ListUtils.swapWithPrevious(graph, arrayIndexes, enumeration);\r
- }\r
- }\r
- if (moved) {\r
- sb.append("up");\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- }\r
-\r
- }\r
- }\r
- \r
- // Move selection\r
- usedEnumerationsExplorer.getDisplay().asyncExec(new RunnableWithObject(usedEnumerationsExplorer, selectedIndexes) {\r
- @Override\r
- public void run() {\r
- Control c = ((GraphExplorerComposite)object).getExplorerControl();\r
- if(c != null && c instanceof Tree && object2 instanceof List<?>) {\r
- Tree tree = (Tree) c;\r
- tree.deselectAll();\r
- \r
- @SuppressWarnings("unchecked")\r
- List<Integer> list = (List<Integer>) object2;\r
- Set<TreeItem> selection = new HashSet<TreeItem>();\r
- for(Integer i : list) {\r
- TreeItem item = null;\r
- if(i - 1 >= 0)\r
- item = tree.getItem(i - 1);\r
- if(item == null || selection.contains(item))\r
- item = tree.getItem(i);\r
- if(item != null && !selection.contains(item))\r
- selection.add(item);\r
- }\r
- tree.setSelection(selection.toArray(new TreeItem[selection.size()]));\r
- }\r
- }\r
- });\r
- }\r
- });\r
-\r
- down = new Button(buttons, buttonSupport, SWT.NONE);\r
- down.setText("Down");\r
- down.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
-\r
- List<Integer> selectedIndexes;\r
-\r
- @Override\r
- public void beforeApply() {\r
- selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);\r
- }\r
-\r
-\r
- @Override\r
- public void apply(WriteGraph graph, ResourceArray input)\r
- throws DatabaseException {\r
-\r
- Layer0 L0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- for(Resource variable : input) {\r
- Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
- if(arrayIndexes != null) {\r
- List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);\r
- List<Resource> toBeMoved = new ArrayList<Resource>();\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Moved enumeration(s) ");\r
- for(Integer index : selectedIndexes) {\r
- if(index < enumerations.size()) {\r
- Resource enumeration = enumerations.get(index);\r
- toBeMoved.add(0, enumeration); // Make an inverted list. \r
- }\r
- }\r
- boolean moved = false;\r
- for(Resource enumeration : toBeMoved) {\r
- Resource node = ListUtils.getNode(graph, arrayIndexes, enumeration);\r
- Resource next = graph.getSingleObject(node, L0.List_Next);\r
- \r
- if(!arrayIndexes.equals(next) && !toBeMoved.contains(graph.getPossibleObject(next, L0.List_Element))) {\r
- sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");\r
- moved = ListUtils.swapWithNext(graph, arrayIndexes, enumeration);\r
- }\r
- }\r
- if (moved) {\r
- sb.append("down");\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- }\r
- }\r
- }\r
- \r
- // Move selection\r
- usedEnumerationsExplorer.getDisplay().asyncExec(new RunnableWithObject(usedEnumerationsExplorer, selectedIndexes) {\r
- @Override\r
- public void run() {\r
- Control c = ((GraphExplorerComposite)object).getExplorerControl();\r
- if(c != null && c instanceof Tree && object2 instanceof List<?>) {\r
- Tree tree = (Tree) c;\r
- tree.deselectAll();\r
- \r
- @SuppressWarnings("unchecked")\r
- List<Integer> list = (List<Integer>) object2;\r
- Set<TreeItem> selection = new HashSet<TreeItem>();\r
- Collections.reverse(list);\r
- for(Integer i : list) {\r
- TreeItem item = null;\r
- if(i + 1 < tree.getItemCount())\r
- item = tree.getItem(i + 1);\r
- if(item == null || selection.contains(item))\r
- item = tree.getItem(i);\r
- if(item != null && !selection.contains(item))\r
- selection.add(item);\r
- }\r
- tree.setSelection(selection.toArray(new TreeItem[selection.size()]));\r
- }\r
- }\r
- });\r
- }\r
- });\r
-\r
- \r
- remove = new Button(buttons, buttonSupport, SWT.NONE);\r
- remove.setText("Remove");\r
- remove.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {\r
- \r
- List<Integer> selectedIndexes;\r
-\r
- @Override\r
- public void beforeApply() {\r
- selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, ResourceArray input)\r
- throws DatabaseException {\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
-\r
- for(Resource variable : input) {\r
- Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);\r
- if(arrayIndexes != null) {\r
- List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);\r
- List<Resource> toBeRemoved = new ArrayList<Resource>();\r
- for(Integer index : selectedIndexes) {\r
- if(index < enumerations.size()) {\r
- Resource enumeration = enumerations.get(index);\r
- toBeRemoved.add(enumeration);\r
- }\r
-\r
- }\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Removed enumeration(s) ");\r
- for(Resource enumeration : toBeRemoved) {\r
- ListUtils.removeElement(graph, arrayIndexes, enumeration);\r
- sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");\r
- }\r
- sb.append("from " + graph.getPossibleRelatedValue2(variable, Layer0.getInstance(graph).HasName, Bindings.STRING));\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- updateUsedButtons(graph, arrayIndexes);\r
- }\r
- }\r
- }\r
- });\r
- }\r
-\r
- \r
- protected void updateUsedButtons(ReadGraph graph, Resource arrayIndexes) {\r
- boolean enabled = false;\r
- if (arrayIndexes == null)\r
- enabled = false;\r
- else {\r
- try {\r
- List<Resource> currEnumerations = ListUtils.toList(graph, arrayIndexes);\r
- if (!currEnumerations.isEmpty()) {\r
- enabled = true;\r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- final boolean finalEnabled = enabled;\r
- SWTThread.getThreadAccess().asyncExec(new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- if (!up.getControl().isDisposed())\r
- up.getControl().setEnabled(finalEnabled);\r
- if (!down.getControl().isDisposed())\r
- down.getControl().setEnabled(finalEnabled);\r
- if (!remove.getControl().isDisposed())\r
- remove.getControl().setEnabled(finalEnabled); \r
- }\r
- });\r
- }\r
-\r
-\r
- private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {\r
- List<Resource> result = new ArrayList<Resource>();\r
- \r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return result;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- @SuppressWarnings("unchecked")\r
- List<AdaptableHintContext> selections = iss.toList();\r
- for(AdaptableHintContext ahc : selections) {\r
- Resource resource = (Resource) ahc.getAdapter(Resource.class);\r
- result.add(resource);\r
- }\r
- return result;\r
- }\r
- \r
- private List<Integer> getSelectedIndexes(final GraphExplorerComposite explorer) {\r
- final List<Integer> result = new ArrayList<Integer>();\r
-\r
- explorer.getDisplay().syncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- Control c = explorer.getExplorerControl();\r
- if (c instanceof Tree) {\r
- Tree tree = (Tree) c;\r
- TreeItem[] selection = tree.getSelection();\r
- \r
- for(TreeItem item : selection) {\r
- result.add(tree.indexOf(item));\r
- }\r
- }\r
- }\r
- });\r
-\r
- return result;\r
- }\r
-\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- \r
- if(input != null && input instanceof IStructuredSelection) {\r
- Object first = ((IStructuredSelection)input).getFirstElement();\r
- ResourceArray resourceArray = null;\r
- if(first instanceof Resource)\r
- resourceArray = new ResourceArray((Resource)first);\r
- else if( first instanceof Collection<?>)\r
- resourceArray = new ResourceArray(((Collection<?>)first).toArray(new Resource[((Collection<?>)first).size()]));\r
- final ResourceArray finalResourceArray = resourceArray;\r
- if(resourceArray != null) {\r
- StructuredSelection selection = new StructuredSelection(finalResourceArray);\r
- availableEnumerationsExplorer.setInput(context, selection);\r
- usedEnumerationsExplorer.setInput(context, selection); \r
- buttonSupport.fireInput(context, selection);\r
- \r
- try {\r
- context.getSession().syncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- Resource r = finalResourceArray.resources[0];\r
- Resource arrayIndexes = graph.getPossibleObject(r, SysdynResource.getInstance(graph).Variable_arrayIndexesList);\r
- updateUsedButtons(graph, arrayIndexes);\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- }\r
- }\r
-}\r
+package org.simantics.sysdyn.ui.properties;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.ISelection;
+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.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+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.ReadFactoryImpl;
+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.browsing.ui.swt.widgets.impl.WidgetSupportImpl;
+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.ResourceArray;
+import org.simantics.db.common.request.ReadRequest;
+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.db.management.ISessionContext;
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;
+import org.simantics.layer0.Layer0;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.properties.widgets.ColumnKeys;
+import org.simantics.utils.RunnableWithObject;
+import org.simantics.utils.datastructures.ArrayMap;
+import org.simantics.utils.threads.SWTThread;
+
+public class ArrayIndexesTab extends LabelPropertyTabContributor implements Widget{
+
+ GraphExplorerComposite availableEnumerationsExplorer;
+ GraphExplorerComposite usedEnumerationsExplorer;
+ private WidgetSupportImpl buttonSupport;
+ private org.simantics.browsing.ui.swt.widgets.Label usedEnumerationsLabel;
+ private Button down;
+ private Button up;
+ private Button remove;
+
+ public ArrayIndexesTab(Object variables) {
+ super(variables);
+ }
+
+
+ @Override
+ public void createControls(Composite body, IWorkbenchSite site,
+ ISessionContext context, WidgetSupport support) {
+ support.register(this);
+
+ buttonSupport = new WidgetSupportImpl();
+
+ GridLayoutFactory.fillDefaults().numColumns(4).applyTo(body);
+
+
+ Composite available = new Composite(body, SWT.NONE);
+ GridLayoutFactory.fillDefaults().applyTo(available);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(available);
+ Label label = new Label(available, SWT.None);
+ label.setText("Available Enumerations");
+ availableEnumerationsExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), site, available, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);
+
+ availableEnumerationsExplorer
+ .setBrowseContexts(SysdynResource.URIs.AvailableVariableIndexes);
+ availableEnumerationsExplorer.setColumns(ColumnKeys.ENUMERATION_TABLE_COLUMNS);
+ availableEnumerationsExplorer.setInputSource(new SingleSelectionInputSource(
+ ResourceArray.class));
+
+ availableEnumerationsExplorer.finish();
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ availableEnumerationsExplorer);
+
+ Control c = availableEnumerationsExplorer.getExplorerControl();
+ if (c instanceof Tree)
+ ((Tree) c).setLinesVisible(true);
+
+
+ Button add = new Button(body, buttonSupport, SWT.NONE);
+ add.setText(" -> ");
+
+ add.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {
+
+ List<Resource> enumerationResources;
+
+ @Override
+ public void beforeApply() {
+ enumerationResources = getSelectedResources(availableEnumerationsExplorer);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, ResourceArray input)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ for(Resource r : input.resources) {
+ Resource arrayIndexes = graph.getPossibleObject(r, sr.Variable_arrayIndexesList);
+ StringBuilder sb = new StringBuilder();
+ sb.append("Added new enumeration(s) ");
+ if(arrayIndexes == null) {
+ arrayIndexes = ListUtils.create(graph, enumerationResources);
+ graph.claim(r, sr.Variable_arrayIndexesList, arrayIndexes);
+ sb.append(enumerationResources.toString() + " ");
+ } else {
+ ArrayList<Resource> filtered = new ArrayList<Resource>();
+ for(Resource enumeration : enumerationResources) {
+ if(ListUtils.getNode(graph, arrayIndexes, enumeration) == null) {
+ filtered.add(enumeration);
+ sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");
+ }
+ }
+ if (filtered.isEmpty())
+ return;
+ ListUtils.insertBack(graph, arrayIndexes, filtered);
+ }
+ sb.append("to " + graph.getPossibleRelatedValue2(r, Layer0.getInstance(graph).HasName, Bindings.STRING));
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+ updateUsedButtons(graph, arrayIndexes);
+ }
+ }
+ });
+
+ Composite used = new Composite(body, SWT.NONE);
+ GridLayoutFactory.fillDefaults().applyTo(used);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(used);
+ usedEnumerationsLabel = new org.simantics.browsing.ui.swt.widgets.Label(used, buttonSupport, SWT.None);
+ usedEnumerationsLabel.setTextFactory(new ReadFactoryImpl<ResourceArray, String>() {
+
+ @Override
+ public String perform(ReadGraph graph, ResourceArray input) throws DatabaseException {
+ if(input.size() < 2)
+ return "Used Enumerations";
+ else {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Enumerations in: ");
+ boolean first = true;
+ for(Resource r : input) {
+ if(!first)
+ sb.append(", ");
+ first = false;
+
+ String name = NameUtils.getSafeName(graph, r);
+ sb.append(name);
+ }
+ return sb.toString();
+ }
+ }
+
+ });
+
+ usedEnumerationsExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), site, used, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);
+
+ usedEnumerationsExplorer
+ .setBrowseContexts(SysdynResource.URIs.UsedVariableIndexes);
+ usedEnumerationsExplorer.setColumns(ColumnKeys.ENUMERATION_TABLE_COLUMNS);
+ usedEnumerationsExplorer.setInputSource(new SingleSelectionInputSource(
+ ResourceArray.class));
+
+ usedEnumerationsExplorer.finish();
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ usedEnumerationsExplorer);
+
+ Control c2 = usedEnumerationsExplorer.getExplorerControl();
+ if (c2 instanceof Tree)
+ ((Tree) c2).setLinesVisible(true);
+
+ Composite buttons = new Composite(body, SWT.None);
+ GridLayoutFactory.fillDefaults().applyTo(buttons);
+
+ up = new Button(buttons, buttonSupport, SWT.NONE);
+ up.setText("Up");
+ up.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {
+
+ List<Integer> selectedIndexes;
+
+ @Override
+ public void beforeApply() {
+ selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, ResourceArray input)
+ throws DatabaseException {
+
+ Layer0 L0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ for(Resource variable : input) {
+ Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);
+ if(arrayIndexes != null) {
+ List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);
+ List<Resource> toBeMoved = new ArrayList<Resource>();
+ StringBuilder sb = new StringBuilder();
+ sb.append("Moved enumeration(s) ");
+ for(Integer index : selectedIndexes) {
+ if(index < enumerations.size()) {
+ Resource enumeration = enumerations.get(index);
+ toBeMoved.add(enumeration);
+ }
+
+ }
+ boolean moved = false;
+ for(Resource enumeration : toBeMoved) {
+ Resource node = ListUtils.getNode(graph, arrayIndexes, enumeration);
+ Resource prev = graph.getSingleObject(node, L0.List_Previous);
+ if(!arrayIndexes.equals(prev) && !toBeMoved.contains(graph.getPossibleObject(prev, L0.List_Element))) {
+ sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");
+ moved = ListUtils.swapWithPrevious(graph, arrayIndexes, enumeration);
+ }
+ }
+ if (moved) {
+ sb.append("up");
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+ }
+
+ }
+ }
+
+ // Move selection
+ usedEnumerationsExplorer.getDisplay().asyncExec(new RunnableWithObject(usedEnumerationsExplorer, selectedIndexes) {
+ @Override
+ public void run() {
+ Control c = ((GraphExplorerComposite)object).getExplorerControl();
+ if(c != null && c instanceof Tree && object2 instanceof List<?>) {
+ Tree tree = (Tree) c;
+ tree.deselectAll();
+
+ @SuppressWarnings("unchecked")
+ List<Integer> list = (List<Integer>) object2;
+ Set<TreeItem> selection = new HashSet<TreeItem>();
+ for(Integer i : list) {
+ TreeItem item = null;
+ if(i - 1 >= 0)
+ item = tree.getItem(i - 1);
+ if(item == null || selection.contains(item))
+ item = tree.getItem(i);
+ if(item != null && !selection.contains(item))
+ selection.add(item);
+ }
+ tree.setSelection(selection.toArray(new TreeItem[selection.size()]));
+ }
+ }
+ });
+ }
+ });
+
+ down = new Button(buttons, buttonSupport, SWT.NONE);
+ down.setText("Down");
+ down.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {
+
+ List<Integer> selectedIndexes;
+
+ @Override
+ public void beforeApply() {
+ selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);
+ }
+
+
+ @Override
+ public void apply(WriteGraph graph, ResourceArray input)
+ throws DatabaseException {
+
+ Layer0 L0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ for(Resource variable : input) {
+ Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);
+ if(arrayIndexes != null) {
+ List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);
+ List<Resource> toBeMoved = new ArrayList<Resource>();
+ StringBuilder sb = new StringBuilder();
+ sb.append("Moved enumeration(s) ");
+ for(Integer index : selectedIndexes) {
+ if(index < enumerations.size()) {
+ Resource enumeration = enumerations.get(index);
+ toBeMoved.add(0, enumeration); // Make an inverted list.
+ }
+ }
+ boolean moved = false;
+ for(Resource enumeration : toBeMoved) {
+ Resource node = ListUtils.getNode(graph, arrayIndexes, enumeration);
+ Resource next = graph.getSingleObject(node, L0.List_Next);
+
+ if(!arrayIndexes.equals(next) && !toBeMoved.contains(graph.getPossibleObject(next, L0.List_Element))) {
+ sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");
+ moved = ListUtils.swapWithNext(graph, arrayIndexes, enumeration);
+ }
+ }
+ if (moved) {
+ sb.append("down");
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+ }
+ }
+ }
+
+ // Move selection
+ usedEnumerationsExplorer.getDisplay().asyncExec(new RunnableWithObject(usedEnumerationsExplorer, selectedIndexes) {
+ @Override
+ public void run() {
+ Control c = ((GraphExplorerComposite)object).getExplorerControl();
+ if(c != null && c instanceof Tree && object2 instanceof List<?>) {
+ Tree tree = (Tree) c;
+ tree.deselectAll();
+
+ @SuppressWarnings("unchecked")
+ List<Integer> list = (List<Integer>) object2;
+ Set<TreeItem> selection = new HashSet<TreeItem>();
+ Collections.reverse(list);
+ for(Integer i : list) {
+ TreeItem item = null;
+ if(i + 1 < tree.getItemCount())
+ item = tree.getItem(i + 1);
+ if(item == null || selection.contains(item))
+ item = tree.getItem(i);
+ if(item != null && !selection.contains(item))
+ selection.add(item);
+ }
+ tree.setSelection(selection.toArray(new TreeItem[selection.size()]));
+ }
+ }
+ });
+ }
+ });
+
+
+ remove = new Button(buttons, buttonSupport, SWT.NONE);
+ remove.setText("Remove");
+ remove.addSelectionListener(new SelectionListenerImpl<ResourceArray>(context) {
+
+ List<Integer> selectedIndexes;
+
+ @Override
+ public void beforeApply() {
+ selectedIndexes = getSelectedIndexes(usedEnumerationsExplorer);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, ResourceArray input)
+ throws DatabaseException {
+ SysdynResource sr = SysdynResource.getInstance(graph);
+
+ for(Resource variable : input) {
+ Resource arrayIndexes = graph.getPossibleObject(variable, sr.Variable_arrayIndexesList);
+ if(arrayIndexes != null) {
+ List<Resource> enumerations = ListUtils.toList(graph, arrayIndexes);
+ List<Resource> toBeRemoved = new ArrayList<Resource>();
+ for(Integer index : selectedIndexes) {
+ if(index < enumerations.size()) {
+ Resource enumeration = enumerations.get(index);
+ toBeRemoved.add(enumeration);
+ }
+
+ }
+ StringBuilder sb = new StringBuilder();
+ sb.append("Removed enumeration(s) ");
+ for(Resource enumeration : toBeRemoved) {
+ ListUtils.removeElement(graph, arrayIndexes, enumeration);
+ sb.append(graph.getPossibleRelatedValue2(enumeration, Layer0.getInstance(graph).HasName, Bindings.STRING) + " ");
+ }
+ sb.append("from " + graph.getPossibleRelatedValue2(variable, Layer0.getInstance(graph).HasName, Bindings.STRING));
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+ updateUsedButtons(graph, arrayIndexes);
+ }
+ }
+ }
+ });
+ }
+
+
+ protected void updateUsedButtons(ReadGraph graph, Resource arrayIndexes) {
+ boolean enabled = false;
+ if (arrayIndexes == null)
+ enabled = false;
+ else {
+ try {
+ List<Resource> currEnumerations = ListUtils.toList(graph, arrayIndexes);
+ if (!currEnumerations.isEmpty()) {
+ enabled = true;
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+ final boolean finalEnabled = enabled;
+ SWTThread.getThreadAccess().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ if (!up.getControl().isDisposed())
+ up.getControl().setEnabled(finalEnabled);
+ if (!down.getControl().isDisposed())
+ down.getControl().setEnabled(finalEnabled);
+ if (!remove.getControl().isDisposed())
+ remove.getControl().setEnabled(finalEnabled);
+ }
+ });
+ }
+
+
+ private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {
+ List<Resource> result = new ArrayList<Resource>();
+
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return result;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ @SuppressWarnings("unchecked")
+ List<AdaptableHintContext> selections = iss.toList();
+ for(AdaptableHintContext ahc : selections) {
+ Resource resource = (Resource) ahc.getAdapter(Resource.class);
+ result.add(resource);
+ }
+ return result;
+ }
+
+ private List<Integer> getSelectedIndexes(final GraphExplorerComposite explorer) {
+ final List<Integer> result = new ArrayList<Integer>();
+
+ explorer.getDisplay().syncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ Control c = explorer.getExplorerControl();
+ if (c instanceof Tree) {
+ Tree tree = (Tree) c;
+ TreeItem[] selection = tree.getSelection();
+
+ for(TreeItem item : selection) {
+ result.add(tree.indexOf(item));
+ }
+ }
+ }
+ });
+
+ return result;
+ }
+
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+
+ if(input != null && input instanceof IStructuredSelection) {
+ Object first = ((IStructuredSelection)input).getFirstElement();
+ ResourceArray resourceArray = null;
+ if(first instanceof Resource)
+ resourceArray = new ResourceArray((Resource)first);
+ else if( first instanceof Collection<?>)
+ resourceArray = new ResourceArray(((Collection<?>)first).toArray(new Resource[((Collection<?>)first).size()]));
+ final ResourceArray finalResourceArray = resourceArray;
+ if(resourceArray != null) {
+ StructuredSelection selection = new StructuredSelection(finalResourceArray);
+ availableEnumerationsExplorer.setInput(context, selection);
+ usedEnumerationsExplorer.setInput(context, selection);
+ buttonSupport.fireInput(context, selection);
+
+ try {
+ context.getSession().syncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ Resource r = finalResourceArray.resources[0];
+ Resource arrayIndexes = graph.getPossibleObject(r, SysdynResource.getInstance(graph).Variable_arrayIndexesList);
+ updateUsedButtons(graph, arrayIndexes);
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Arrays;\r
-import java.util.List;\r
-\r
-import org.eclipse.jface.dialogs.MessageDialog;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Event;\r
-import org.eclipse.swt.widgets.Listener;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.handlers.exports.ExportExternalFunctionFilesHandler;\r
-import org.simantics.sysdyn.ui.handlers.imports.ImportExternalFunctionFilesHandler;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.datastructures.Pair;\r
-import org.simantics.utils.threads.SWTThread;\r
-\r
-/**\r
- * Tab for properties of a SysdynModelicaFunction containing all external files added to that function \r
- * \r
- * @author Teemu Lempinen\r
- *\r
- */\r
-public class ExternalFilesTab extends LabelPropertyTabContributor implements Widget {\r
-\r
- public ExternalFilesTab(Object id) {\r
- super(id);\r
- }\r
-\r
- GraphExplorerComposite externalFilesExplorer;\r
- Button importButton, exportButton, removeButton; \r
- \r
- @Override\r
- public void createControls(Composite body, IWorkbenchSite site,\r
- final ISessionContext context, WidgetSupport support) {\r
- support.register(this);\r
- \r
- Composite composite = new Composite(body, SWT.NONE);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
- GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
- \r
- // Create the graph explorer displaying external files \r
- externalFilesExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), site, composite, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);\r
- \r
- externalFilesExplorer\r
- .setBrowseContexts(SysdynResource.URIs.ExternalFiles);\r
- externalFilesExplorer.setInputSource(new SingleSelectionInputSource(\r
- Resource.class));\r
-\r
- externalFilesExplorer.setContextMenuId("#ExternalFunctionFileBrowser");\r
- \r
- externalFilesExplorer.addListenerToControl(SWT.Selection, new Listener() {\r
- \r
- @Override\r
- public void handleEvent(Event event) {\r
- updateButtons(externalFilesExplorer);\r
- }\r
- });\r
- \r
- externalFilesExplorer.finish();\r
- \r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- externalFilesExplorer);\r
- \r
- Control c = externalFilesExplorer.getExplorerControl();\r
- if (c instanceof Tree)\r
- ((Tree) c).setLinesVisible(true);\r
- \r
- \r
- // Create controls for importing, exporting and removing external files\r
- Composite buttonRow = new Composite(composite, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonRow);\r
- GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonRow);\r
- \r
- importButton = new Button(buttonRow, support, SWT.NONE);\r
- importButton.setText("Import");\r
- importButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- private Pair<String, String[]> importedFiles; \r
- \r
- @Override\r
- public void beforeApply() {\r
- Shell shell = importButton.getWidget().getShell();\r
- importedFiles = ImportExternalFunctionFilesHandler.importFiles(shell, "Import files", ImportExternalFunctionFilesHandler.C_EXTENSIONS); \r
- }\r
- \r
- @Override\r
- public void apply(WriteGraph graph, final Resource input) throws DatabaseException {\r
- graph.markUndoPoint();\r
- ImportExternalFunctionFilesHandler.addFilesToFunction(graph, input, importedFiles);\r
- Layer0Utils.addCommentMetadata(graph, "Imported External File(s) " + Arrays.toString(importedFiles.second) + " to " + NameUtils.getSafeName(graph, input));\r
- updateButtons(externalFilesExplorer);\r
- }\r
- });\r
-\r
- exportButton = new Button(buttonRow, support, SWT.NONE);\r
- exportButton.setText("Export");\r
- exportButton.getControl().setEnabled(false);\r
- exportButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- @Override\r
- public void apply(WriteGraph graph, final Resource input)\r
- throws DatabaseException {\r
-\r
- exportButton.getWidget().getDisplay().asyncExec(new Runnable() {\r
-\r
- @Override\r
- public void run() {\r
- Shell shell = exportButton.getWidget().getShell();\r
- List<Resource> resourceList = getSelectedResources(externalFilesExplorer);\r
- Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);\r
- if (resources.length > 0)\r
- ExportExternalFunctionFilesHandler.exportFiles(shell, resources);\r
- }\r
- });\r
- }\r
- });\r
-\r
- removeButton = new Button(buttonRow, support, SWT.NONE);\r
- removeButton.setText("Remove");\r
- removeButton.getControl().setEnabled(false);\r
- removeButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- private int delete;\r
- private List<Resource> resourceList;\r
- \r
- @Override\r
- public void beforeApply() {\r
- Shell shell = removeButton.getWidget().getShell();\r
-\r
- resourceList = getSelectedResources(externalFilesExplorer);\r
- Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);\r
- if(resources.length > 0) {\r
- MessageDialog dialog = new MessageDialog(shell, resources.length > 1 ? "Remove selected items" : "Remove selected item" , null, "Are you sure?", 0,\r
- new String[] { "OK", "Cancel" }, 0);\r
- dialog.create();\r
- delete = dialog.open();\r
- }\r
- }\r
- \r
- @Override\r
- public void apply(WriteGraph graph, final Resource input) throws DatabaseException {\r
- if (delete == 0) {\r
- Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Removed External File(s) ");\r
- for (Resource resource : resources) {\r
- RemoverUtil.remove(graph, resource);\r
- sb.append(NameUtils.getSafeName(graph, resource) + " ");\r
- }\r
- sb.append("from " + NameUtils.getSafeName(graph, input));\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- \r
- updateButtons(externalFilesExplorer);\r
- }\r
- }\r
- });\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- externalFilesExplorer.setInput(context, input);\r
- updateButtons(externalFilesExplorer);\r
- }\r
-\r
- /**\r
- * Method for retreiving selected resources from a GraphExplorerComposite\r
- * @param explorer\r
- * @return\r
- */\r
- private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {\r
- List<Resource> result = new ArrayList<Resource>();\r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return result;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- @SuppressWarnings("unchecked")\r
- List<AdaptableHintContext> selections = iss.toList();\r
- for(AdaptableHintContext ahc : selections) {\r
- Resource resource = (Resource) ahc.getAdapter(Resource.class);\r
- result.add(resource);\r
- }\r
- return result;\r
- }\r
- \r
- protected void updateButtons(final GraphExplorerComposite explorer) {\r
- if (SWTThread.getThreadAccess().currentThreadAccess()) {\r
- runnable.run();\r
- } else {\r
- SWTThread.getThreadAccess().asyncExec(runnable);\r
- }\r
- }\r
- \r
- Runnable runnable = new Runnable() {\r
- \r
- @Override\r
- public void run() {\r
- ISelection selection = ((ISelectionProvider) externalFilesExplorer.getAdapter(ISelectionProvider.class)).getSelection();\r
- \r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- @SuppressWarnings("unchecked")\r
- List<AdaptableHintContext> selections = iss.toList();\r
- \r
- boolean enabled = false;\r
- if (!selections.isEmpty()) \r
- enabled = true;\r
- removeButton.getControl().setEnabled(enabled);\r
- exportButton.getControl().setEnabled(enabled);\r
- }\r
- };\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.properties;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.ui.IWorkbenchSite;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+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.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+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.layer0.util.RemoverUtil;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;
+import org.simantics.sysdyn.SysdynResource;
+import org.simantics.sysdyn.ui.handlers.exports.ExportExternalFunctionFilesHandler;
+import org.simantics.sysdyn.ui.handlers.imports.ImportExternalFunctionFilesHandler;
+import org.simantics.utils.datastructures.ArrayMap;
+import org.simantics.utils.datastructures.Pair;
+import org.simantics.utils.threads.SWTThread;
+
+/**
+ * Tab for properties of a SysdynModelicaFunction containing all external files added to that function
+ *
+ * @author Teemu Lempinen
+ *
+ */
+public class ExternalFilesTab extends LabelPropertyTabContributor implements Widget {
+
+ public ExternalFilesTab(Object id) {
+ super(id);
+ }
+
+ GraphExplorerComposite externalFilesExplorer;
+ Button importButton, exportButton, removeButton;
+
+ @Override
+ public void createControls(Composite body, IWorkbenchSite site,
+ final ISessionContext context, WidgetSupport support) {
+ support.register(this);
+
+ Composite composite = new Composite(body, SWT.NONE);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
+ GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);
+
+ // Create the graph explorer displaying external files
+ externalFilesExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), site, composite, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);
+
+ externalFilesExplorer
+ .setBrowseContexts(SysdynResource.URIs.ExternalFiles);
+ externalFilesExplorer.setInputSource(new SingleSelectionInputSource(
+ Resource.class));
+
+ externalFilesExplorer.setContextMenuId("#ExternalFunctionFileBrowser");
+
+ externalFilesExplorer.addListenerToControl(SWT.Selection, new Listener() {
+
+ @Override
+ public void handleEvent(Event event) {
+ updateButtons(externalFilesExplorer);
+ }
+ });
+
+ externalFilesExplorer.finish();
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ externalFilesExplorer);
+
+ Control c = externalFilesExplorer.getExplorerControl();
+ if (c instanceof Tree)
+ ((Tree) c).setLinesVisible(true);
+
+
+ // Create controls for importing, exporting and removing external files
+ Composite buttonRow = new Composite(composite, SWT.NONE);
+ GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonRow);
+ GridDataFactory.fillDefaults().grab(true, false).applyTo(buttonRow);
+
+ importButton = new Button(buttonRow, support, SWT.NONE);
+ importButton.setText("Import");
+ importButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ private Pair<String, String[]> importedFiles;
+
+ @Override
+ public void beforeApply() {
+ Shell shell = importButton.getWidget().getShell();
+ importedFiles = ImportExternalFunctionFilesHandler.importFiles(shell, "Import files", ImportExternalFunctionFilesHandler.C_EXTENSIONS);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, final Resource input) throws DatabaseException {
+ graph.markUndoPoint();
+ ImportExternalFunctionFilesHandler.addFilesToFunction(graph, input, importedFiles);
+ Layer0Utils.addCommentMetadata(graph, "Imported External File(s) " + Arrays.toString(importedFiles.second) + " to " + NameUtils.getSafeName(graph, input));
+ updateButtons(externalFilesExplorer);
+ }
+ });
+
+ exportButton = new Button(buttonRow, support, SWT.NONE);
+ exportButton.setText("Export");
+ exportButton.getControl().setEnabled(false);
+ exportButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ @Override
+ public void apply(WriteGraph graph, final Resource input)
+ throws DatabaseException {
+
+ exportButton.getWidget().getDisplay().asyncExec(new Runnable() {
+
+ @Override
+ public void run() {
+ Shell shell = exportButton.getWidget().getShell();
+ List<Resource> resourceList = getSelectedResources(externalFilesExplorer);
+ Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);
+ if (resources.length > 0)
+ ExportExternalFunctionFilesHandler.exportFiles(shell, resources);
+ }
+ });
+ }
+ });
+
+ removeButton = new Button(buttonRow, support, SWT.NONE);
+ removeButton.setText("Remove");
+ removeButton.getControl().setEnabled(false);
+ removeButton.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ private int delete;
+ private List<Resource> resourceList;
+
+ @Override
+ public void beforeApply() {
+ Shell shell = removeButton.getWidget().getShell();
+
+ resourceList = getSelectedResources(externalFilesExplorer);
+ Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);
+ if(resources.length > 0) {
+ MessageDialog dialog = new MessageDialog(shell, resources.length > 1 ? "Remove selected items" : "Remove selected item" , null, "Are you sure?", 0,
+ new String[] { "OK", "Cancel" }, 0);
+ dialog.create();
+ delete = dialog.open();
+ }
+ }
+
+ @Override
+ public void apply(WriteGraph graph, final Resource input) throws DatabaseException {
+ if (delete == 0) {
+ Resource[] resources = resourceList.toArray(new Resource[resourceList.size()]);
+ StringBuilder sb = new StringBuilder();
+ sb.append("Removed External File(s) ");
+ for (Resource resource : resources) {
+ RemoverUtil.remove(graph, resource);
+ sb.append(NameUtils.getSafeName(graph, resource) + " ");
+ }
+ sb.append("from " + NameUtils.getSafeName(graph, input));
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+
+ updateButtons(externalFilesExplorer);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ externalFilesExplorer.setInput(context, input);
+ updateButtons(externalFilesExplorer);
+ }
+
+ /**
+ * Method for retreiving selected resources from a GraphExplorerComposite
+ * @param explorer
+ * @return
+ */
+ private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {
+ List<Resource> result = new ArrayList<Resource>();
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return result;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ @SuppressWarnings("unchecked")
+ List<AdaptableHintContext> selections = iss.toList();
+ for(AdaptableHintContext ahc : selections) {
+ Resource resource = (Resource) ahc.getAdapter(Resource.class);
+ result.add(resource);
+ }
+ return result;
+ }
+
+ protected void updateButtons(final GraphExplorerComposite explorer) {
+ if (SWTThread.getThreadAccess().currentThreadAccess()) {
+ runnable.run();
+ } else {
+ SWTThread.getThreadAccess().asyncExec(runnable);
+ }
+ }
+
+ Runnable runnable = new Runnable() {
+
+ @Override
+ public void run() {
+ ISelection selection = ((ISelectionProvider) externalFilesExplorer.getAdapter(ISelectionProvider.class)).getSelection();
+
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ @SuppressWarnings("unchecked")
+ List<AdaptableHintContext> selections = iss.toList();
+
+ boolean enabled = false;
+ if (!selections.isEmpty())
+ enabled = true;
+ removeButton.getControl().setEnabled(enabled);
+ exportButton.getControl().setEnabled(enabled);
+ }
+ };
+}
-/*******************************************************************************\r
- * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.sysdyn.ui.properties;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-\r
-import org.eclipse.core.runtime.IAdaptable;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.GridLayoutFactory;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.ui.IWorkbenchSite;\r
-import org.simantics.browsing.ui.NodeContext;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.SingleSelectionInputSource;\r
-import org.simantics.browsing.ui.swt.widgets.Button;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
-import org.simantics.browsing.ui.swt.widgets.impl.Widget;\r
-import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.Layer0Utils;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.jfreechart.chart.properties.LabelPropertyTabContributor;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.browser.nodes.SharedFunctionLibraryNode;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.ui.AdaptionUtils;\r
-\r
-public class SharedFunctionLibrariesTab extends LabelPropertyTabContributor implements Widget {\r
- \r
- public SharedFunctionLibrariesTab(Object id) {\r
- super(id);\r
- }\r
-\r
- GraphExplorerComposite availableSharedFunctionLibraries;\r
- GraphExplorerComposite usedSharedFunctionLibraries;\r
- Resource model;\r
-\r
- @Override\r
- public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
- support.register(this);\r
- \r
- GridLayoutFactory.fillDefaults().numColumns(4).applyTo(body);\r
- \r
- \r
- Composite available = new Composite(body, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().applyTo(available);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(available);\r
- Label label = new Label(available, SWT.None);\r
- label.setText("Available Shared Function Libraries");\r
- availableSharedFunctionLibraries = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), site, available, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI) {\r
- \r
- @Override\r
- protected void handleDrop(Object data, NodeContext target) {\r
- if (!(data instanceof IStructuredSelection))\r
- return;\r
- \r
- IStructuredSelection iss = (IStructuredSelection)data;\r
- if (iss == null || iss.isEmpty())\r
- return;\r
- \r
- for (Iterator<?> iterator = iss.iterator(); iterator.hasNext();) {\r
- Object o = iterator.next();\r
- if(o instanceof IAdaptable) {\r
- IAdaptable a = (IAdaptable)o;\r
- final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);\r
- if(node != null) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- if(getModel() != null && node.data != null)\r
- graph.deny(getModel(), Layer0.getInstance(graph).IsLinkedTo, node.data); \r
- }\r
- });\r
- }\r
- }\r
- }\r
- }\r
- };\r
- \r
- availableSharedFunctionLibraries\r
- .setBrowseContexts(SysdynResource.URIs.AvailableSharedFunctionLibraries);\r
- availableSharedFunctionLibraries.setInputSource(new SingleSelectionInputSource(\r
- Resource.class));\r
-\r
- availableSharedFunctionLibraries.finish();\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- availableSharedFunctionLibraries);\r
- \r
- Composite middleButtons = new Composite(body, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().applyTo(middleButtons);\r
- GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, true).applyTo(middleButtons);\r
- \r
- Button add = new Button(middleButtons, support, SWT.NONE);\r
- add.setText(" -> ");\r
- \r
- add.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
-\r
- List<Resource> selectedLibraries;\r
-\r
- public void beforeApply() {\r
- selectedLibraries = getSelectedResources(availableSharedFunctionLibraries);\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource input)\r
- throws DatabaseException {\r
- if(selectedLibraries != null) {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Added Shared Function Library ");\r
- for(Resource library : selectedLibraries) {\r
- graph.claim(input, l0.IsLinkedTo, library);\r
- sb.append(NameUtils.getSafeName(graph, library) + " ");\r
- }\r
- sb.append("to " + NameUtils.getSafeName(graph, input));\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- }\r
- }\r
- });\r
-\r
- Button remove = new Button(middleButtons, support, SWT.NONE);\r
- remove.setText(" <- ");\r
- \r
- remove.addSelectionListener(new SelectionListenerImpl<Resource>(context) {\r
- \r
- List<Resource> selectedLibraries;\r
- \r
- public void beforeApply() {\r
- selectedLibraries = getSelectedResources(usedSharedFunctionLibraries);\r
- }\r
-\r
- @Override\r
- public void apply(WriteGraph graph, Resource input)\r
- throws DatabaseException {\r
- if(selectedLibraries != null) {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("Removed Shared Function Library ");\r
- for(Resource library : selectedLibraries) {\r
- graph.deny(input, l0.IsLinkedTo, library);\r
- sb.append(NameUtils.getSafeName(graph, library) + " ");\r
- }\r
- sb.append("from " + NameUtils.getSafeName(graph, input));\r
- Layer0Utils.addCommentMetadata(graph, sb.toString());\r
- }\r
- }\r
- });\r
- \r
- \r
- Composite used = new Composite(body, SWT.NONE);\r
- GridLayoutFactory.fillDefaults().applyTo(used);\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(used);\r
- label = new Label(used, SWT.None);\r
- label.setText("Selected Shared Function Libraries");\r
- \r
- usedSharedFunctionLibraries = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), site, used, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI) {\r
- \r
- @Override\r
- protected void handleDrop(Object data, NodeContext target) {\r
- if (!(data instanceof IStructuredSelection))\r
- return;\r
- \r
- IStructuredSelection iss = (IStructuredSelection)data;\r
- if (iss == null || iss.isEmpty())\r
- return;\r
- \r
- for (Iterator<?> iterator = iss.iterator(); iterator.hasNext();) {\r
- Object o = iterator.next();\r
- if(o instanceof IAdaptable) {\r
- IAdaptable a = (IAdaptable)o;\r
- final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);\r
- if(node != null) {\r
- SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- if(getModel() != null && node.data != null)\r
- graph.claim(getModel(), Layer0.getInstance(graph).IsLinkedTo, node.data); \r
- }\r
- });\r
- }\r
- }\r
- }\r
- }\r
- };\r
- \r
- usedSharedFunctionLibraries\r
- .setBrowseContexts(SysdynResource.URIs.SelectedSharedFunctionLibraries);\r
- usedSharedFunctionLibraries.setInputSource(new SingleSelectionInputSource(\r
- Resource.class));\r
-\r
- usedSharedFunctionLibraries.finish();\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- usedSharedFunctionLibraries);\r
- }\r
- \r
- \r
- private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {\r
- List<Resource> result = new ArrayList<Resource>();\r
- \r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return result;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- @SuppressWarnings("unchecked")\r
- List<AdaptableHintContext> selections = iss.toList();\r
- for(AdaptableHintContext ahc : selections) {\r
- Resource resource = (Resource) ahc.getAdapter(Resource.class);\r
- result.add(resource);\r
- }\r
- return result;\r
- }\r
-\r
- private Resource getModel() {\r
- return model;\r
- }\r
-\r
- @Override\r
- public void setInput(ISessionContext context, Object input) {\r
- availableSharedFunctionLibraries.setInput(context, input);\r
- usedSharedFunctionLibraries.setInput(context, input);\r
- this.model = AdaptionUtils.adaptToSingle(input, Resource.class);\r
- }\r
-}\r
-\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2011, 2014 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.sysdyn.ui.properties;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.GridLayoutFactory;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+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.browsing.ui.NodeContext;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+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.Widget;
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;
+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.management.ISessionContext;
+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;
+
+public class SharedFunctionLibrariesTab extends LabelPropertyTabContributor implements Widget {
+
+ public SharedFunctionLibrariesTab(Object id) {
+ super(id);
+ }
+
+ GraphExplorerComposite availableSharedFunctionLibraries;
+ GraphExplorerComposite usedSharedFunctionLibraries;
+ Resource model;
+
+ @Override
+ public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {
+ support.register(this);
+
+ GridLayoutFactory.fillDefaults().numColumns(4).applyTo(body);
+
+
+ Composite available = new Composite(body, SWT.NONE);
+ GridLayoutFactory.fillDefaults().applyTo(available);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(available);
+ Label label = new Label(available, SWT.None);
+ label.setText("Available Shared Function Libraries");
+ availableSharedFunctionLibraries = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), site, available, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI) {
+
+ @Override
+ protected void handleDrop(Object data, NodeContext target) {
+ if (!(data instanceof IStructuredSelection))
+ return;
+
+ IStructuredSelection iss = (IStructuredSelection)data;
+ if (iss == null || iss.isEmpty())
+ return;
+
+ for (Iterator<?> iterator = iss.iterator(); iterator.hasNext();) {
+ Object o = iterator.next();
+ if(o instanceof IAdaptable) {
+ IAdaptable a = (IAdaptable)o;
+ final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);
+ if(node != null) {
+ SimanticsUI.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ if(getModel() != null && node.data != null)
+ graph.deny(getModel(), Layer0.getInstance(graph).IsLinkedTo, node.data);
+ }
+ });
+ }
+ }
+ }
+ }
+ };
+
+ availableSharedFunctionLibraries
+ .setBrowseContexts(SysdynResource.URIs.AvailableSharedFunctionLibraries);
+ availableSharedFunctionLibraries.setInputSource(new SingleSelectionInputSource(
+ Resource.class));
+
+ availableSharedFunctionLibraries.finish();
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ availableSharedFunctionLibraries);
+
+ Composite middleButtons = new Composite(body, SWT.NONE);
+ GridLayoutFactory.fillDefaults().applyTo(middleButtons);
+ GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, true).applyTo(middleButtons);
+
+ Button add = new Button(middleButtons, support, SWT.NONE);
+ add.setText(" -> ");
+
+ add.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ List<Resource> selectedLibraries;
+
+ public void beforeApply() {
+ selectedLibraries = getSelectedResources(availableSharedFunctionLibraries);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, Resource input)
+ throws DatabaseException {
+ if(selectedLibraries != null) {
+ Layer0 l0 = Layer0.getInstance(graph);
+ StringBuilder sb = new StringBuilder();
+ sb.append("Added Shared Function Library ");
+ for(Resource library : selectedLibraries) {
+ graph.claim(input, l0.IsLinkedTo, library);
+ sb.append(NameUtils.getSafeName(graph, library) + " ");
+ }
+ sb.append("to " + NameUtils.getSafeName(graph, input));
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+ }
+ }
+ });
+
+ Button remove = new Button(middleButtons, support, SWT.NONE);
+ remove.setText(" <- ");
+
+ remove.addSelectionListener(new SelectionListenerImpl<Resource>(context) {
+
+ List<Resource> selectedLibraries;
+
+ public void beforeApply() {
+ selectedLibraries = getSelectedResources(usedSharedFunctionLibraries);
+ }
+
+ @Override
+ public void apply(WriteGraph graph, Resource input)
+ throws DatabaseException {
+ if(selectedLibraries != null) {
+ Layer0 l0 = Layer0.getInstance(graph);
+ StringBuilder sb = new StringBuilder();
+ sb.append("Removed Shared Function Library ");
+ for(Resource library : selectedLibraries) {
+ graph.deny(input, l0.IsLinkedTo, library);
+ sb.append(NameUtils.getSafeName(graph, library) + " ");
+ }
+ sb.append("from " + NameUtils.getSafeName(graph, input));
+ Layer0Utils.addCommentMetadata(graph, sb.toString());
+ }
+ }
+ });
+
+
+ Composite used = new Composite(body, SWT.NONE);
+ GridLayoutFactory.fillDefaults().applyTo(used);
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(used);
+ label = new Label(used, SWT.None);
+ label.setText("Selected Shared Function Libraries");
+
+ usedSharedFunctionLibraries = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), site, used, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI) {
+
+ @Override
+ protected void handleDrop(Object data, NodeContext target) {
+ if (!(data instanceof IStructuredSelection))
+ return;
+
+ IStructuredSelection iss = (IStructuredSelection)data;
+ if (iss == null || iss.isEmpty())
+ return;
+
+ for (Iterator<?> iterator = iss.iterator(); iterator.hasNext();) {
+ Object o = iterator.next();
+ if(o instanceof IAdaptable) {
+ IAdaptable a = (IAdaptable)o;
+ final SharedFunctionLibraryNode node = (SharedFunctionLibraryNode)a.getAdapter(SharedFunctionLibraryNode.class);
+ if(node != null) {
+ SimanticsUI.getSession().asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ if(getModel() != null && node.data != null)
+ graph.claim(getModel(), Layer0.getInstance(graph).IsLinkedTo, node.data);
+ }
+ });
+ }
+ }
+ }
+ }
+ };
+
+ usedSharedFunctionLibraries
+ .setBrowseContexts(SysdynResource.URIs.SelectedSharedFunctionLibraries);
+ usedSharedFunctionLibraries.setInputSource(new SingleSelectionInputSource(
+ Resource.class));
+
+ usedSharedFunctionLibraries.finish();
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ usedSharedFunctionLibraries);
+ }
+
+
+ private List<Resource> getSelectedResources(GraphExplorerComposite explorer) {
+ List<Resource> result = new ArrayList<Resource>();
+
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return result;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ @SuppressWarnings("unchecked")
+ List<AdaptableHintContext> selections = iss.toList();
+ for(AdaptableHintContext ahc : selections) {
+ Resource resource = (Resource) ahc.getAdapter(Resource.class);
+ result.add(resource);
+ }
+ return result;
+ }
+
+ private Resource getModel() {
+ return model;
+ }
+
+ @Override
+ public void setInput(ISessionContext context, Object input) {
+ availableSharedFunctionLibraries.setInput(context, input);
+ usedSharedFunctionLibraries.setInput(context, input);
+ this.model = AdaptionUtils.adaptToSingle(input, Resource.class);
+ }
+}
+
-package org.simantics.sysdyn.ui.wizards.functions;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Path;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.PixelConverter;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.primitiverequest.PossibleRelatedValue;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
-import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.graph.db.TGStatusMonitor;\r
-import org.simantics.graph.db.TransferableGraphSource;\r
-import org.simantics.graph.db.TransferableGraphs;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-\r
-public class WizardFunctionsExportPage extends WizardPage {\r
- \r
- // dialog store id constants\r
- private Text filePathField;\r
- \r
- // Keep track of the archive that we browsed to last time\r
- // the wizard was invoked.\r
- private static String previouslyBrowsedFile = "";\r
-\r
- private Button browseDirectoriesButton;\r
- \r
- //private IStructuredSelection currentSelection;\r
- \r
- GraphExplorerComposite functionLibraryExplorer;\r
- \r
- private boolean selectionMade = false;\r
- \r
- /**\r
- * Creates a new project creation wizard page.\r
- * \r
- */\r
- public WizardFunctionsExportPage() {\r
- this("wizardFunctionsExportPage", null, null); //$NON-NLS-1$\r
- }\r
-\r
- /**\r
- * Create a new instance of the receiver.\r
- * \r
- * @param pageName\r
- */\r
- public WizardFunctionsExportPage(String pageName) {\r
- this(pageName,null, null);\r
- }\r
- \r
- /**\r
- * More (many more) parameters.\r
- * \r
- * @param pageName\r
- * @param initialPath\r
- * @param currentSelection\r
- * @since 3.5\r
- */\r
- public WizardFunctionsExportPage(String pageName,String initialPath,\r
- IStructuredSelection currentSelection) {\r
- super(pageName);\r
- //this.currentSelection = currentSelection;\r
- setPageComplete(false);\r
- setTitle("Export Function Library");\r
- setDescription("Choose the Function Library and the export location, then press Finish.");\r
- }\r
- \r
- public void createControl(Composite parent) {\r
- \r
- initializeDialogUnits(parent);\r
-\r
- Composite workArea = new Composite(parent, SWT.NONE);\r
- setControl(workArea);\r
-\r
- workArea.setLayout(new GridLayout());\r
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
-\r
- createProjectsRoot(workArea);\r
- createTree(workArea);\r
- \r
- }\r
- \r
- private void createProjectsRoot(Composite workArea) {\r
- \r
- // set label for field\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select the export location for Function Library:");\r
- \r
- Composite projectGroup = new Composite(workArea, SWT.NONE);\r
- GridLayout layout = new GridLayout();\r
- layout.numColumns = 2;\r
- layout.makeColumnsEqualWidth = false;\r
- layout.marginWidth = 0;\r
-\r
- projectGroup.setLayout(layout);\r
- projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
- \r
- // function library location entry field\r
- this.filePathField = new Text(projectGroup, SWT.BORDER);\r
-\r
- GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
- directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
- filePathField.setLayoutData(directoryPathData);\r
- \r
- filePathField.addModifyListener(new ModifyListener(){\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- previouslyBrowsedFile = filePathField.getText(); \r
- }\r
- });\r
- if (previouslyBrowsedFile != null){\r
- filePathField.setText(previouslyBrowsedFile);\r
- validatePage();\r
- }\r
- \r
- // browse button\r
- browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
- browseDirectoriesButton.setText("Browse");\r
- setButtonLayoutData(browseDirectoriesButton);\r
- \r
- browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
- * elected(org.eclipse.swt.events.SelectionEvent)\r
- */\r
- public void widgetSelected(SelectionEvent e) {\r
- handleLocationDirectoryButtonPressed();\r
- }\r
- });\r
- \r
- }\r
- \r
- private void createTree(Composite workArea){\r
- \r
- //set label for tree\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select Function Library to export:");\r
-\r
- Resource input = SimanticsUI.getProject().get();\r
-\r
- functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
-\r
- functionLibraryExplorer\r
- .setBrowseContexts(SysdynResource.URIs.FunctionTree);\r
-\r
- functionLibraryExplorer.finish();\r
-\r
- functionLibraryExplorer.setInput(null, input);\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- functionLibraryExplorer);\r
-\r
- ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
-\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- setMessage(null);\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- setMessage(null);\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- });\r
- }\r
- \r
- //Set filePathField active\r
- public void setVisible(boolean visible) {\r
- super.setVisible(visible);\r
- this.filePathField.setFocus();\r
- }\r
- \r
- \r
- //Open dialog for choosing the file\r
- protected void handleLocationDirectoryButtonPressed() {\r
- \r
- final Shell shell = filePathField.getShell();\r
- \r
- FileDialog dialog = new FileDialog(shell, SWT.SAVE);\r
- \r
- String[] ext = {"*.sysdynFunctions"};\r
- dialog.setFilterExtensions(ext);\r
- \r
- dialog.setText("Export Function Library");\r
-\r
- String dirName = filePathField.getText().trim();\r
- \r
- File path = new File(dirName);\r
- if (path.exists()) {\r
- dialog.setFilterPath(new Path(dirName).toOSString()); \r
- }\r
- \r
- String selectedFile = dialog.open();\r
- if (selectedFile != null) {\r
- filePathField.setText(selectedFile);\r
- validatePage();\r
- } \r
-\r
- }\r
- \r
- //Get selection from the tree\r
- @SuppressWarnings("unchecked")\r
- public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
- Class<T> clazz) {\r
- if(explorer == null)\r
- return null;\r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return null;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
- if (inc == null)\r
- return null;\r
- final T resource = (T) inc.getAdapter(clazz);\r
-\r
- return resource;\r
- }\r
- \r
- public boolean createProjects(Resource selection) {\r
- \r
- final String selected = previouslyBrowsedFile;\r
- if(selected == null) return false;\r
- \r
- final Resource functionLibrary = getExplorerResource(functionLibraryExplorer, Resource.class);\r
- if(functionLibrary == null) return false;\r
- \r
- String name = null;\r
- try {\r
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf))\r
- return null;\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));\r
- return name;\r
- \r
- }\r
- \r
- });\r
- } catch (DatabaseException ex) {\r
- Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,\r
- "Failed to read name of function library " + functionLibrary + ", see exception for details.", ex));\r
- }\r
- if(name == null) return false;\r
-\r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, functionLibrary);\r
- try (TransferableGraphSource tgs = graph.syncRequest( new ModelTransferableGraphSourceRequest(conf) )) {\r
- TransferableGraphs.writeTransferableGraph(graph, tgs, new File(selected), TGStatusMonitor.NULL_MONITOR);\r
- } catch (Exception e) {\r
- Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,\r
- "Failed to export function library, see exception for details.", e));\r
- }\r
- }\r
- });\r
- \r
- return true;\r
- }\r
- \r
- void validatePage() {\r
- \r
- if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
- setPageComplete(false);\r
- return;\r
- }\r
- \r
- if (functionLibraryExplorer != null){\r
- final Resource selectedResource = getExplorerResource(functionLibraryExplorer, Resource.class);\r
-\r
- String root = null;\r
- try {\r
- root = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource model = graph.getPossibleObject(selectedResource, l0.PartOf);\r
- String rootName = NameUtils.getSafeName(graph, model);\r
-\r
- return rootName;\r
- }\r
-\r
- });\r
- if (root != null && root.equalsIgnoreCase("Development Project")){\r
- setPageComplete(false);\r
- setMessage("Select Function Library folder under the Model or from the Shared Functions folder.");\r
- return;\r
- }\r
- } catch (DatabaseException e) {\r
- Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,\r
- "Failed to validate wizard page contents, see exception for details.", e));\r
- }\r
- }\r
- \r
- setPageComplete(true);\r
- \r
- }\r
- \r
+package org.simantics.sysdyn.ui.wizards.functions;
+
+import java.io.File;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.PixelConverter;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+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.events.SelectionListener;
+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.eclipse.swt.widgets.Tree;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+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.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.TGStatusMonitor;
+import org.simantics.graph.db.TransferableGraphSource;
+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 {
+
+ // 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;
+
+ //private IStructuredSelection currentSelection;
+
+ GraphExplorerComposite functionLibraryExplorer;
+
+ private boolean selectionMade = false;
+
+ /**
+ * Creates a new project creation wizard page.
+ *
+ */
+ public WizardFunctionsExportPage() {
+ this("wizardFunctionsExportPage", null, null); //$NON-NLS-1$
+ }
+
+ /**
+ * Create a new instance of the receiver.
+ *
+ * @param pageName
+ */
+ public WizardFunctionsExportPage(String pageName) {
+ this(pageName,null, null);
+ }
+
+ /**
+ * More (many more) parameters.
+ *
+ * @param pageName
+ * @param initialPath
+ * @param currentSelection
+ * @since 3.5
+ */
+ public WizardFunctionsExportPage(String pageName,String initialPath,
+ IStructuredSelection currentSelection) {
+ super(pageName);
+ //this.currentSelection = currentSelection;
+ setPageComplete(false);
+ setTitle("Export Function Library");
+ setDescription("Choose the Function Library and the export location, 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);
+ createTree(workArea);
+
+ }
+
+ private void createProjectsRoot(Composite workArea) {
+
+ // set label for field
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select the export location for Function Library:");
+
+ 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));
+
+ // function library 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();
+ }
+ });
+
+ }
+
+ private void createTree(Composite workArea){
+
+ //set label for tree
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select Function Library to export:");
+
+ Resource input = SimanticsUI.getProject().get();
+
+ functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
+
+ functionLibraryExplorer
+ .setBrowseContexts(SysdynResource.URIs.FunctionTree);
+
+ functionLibraryExplorer.finish();
+
+ functionLibraryExplorer.setInput(null, input);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ functionLibraryExplorer);
+
+ ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ setMessage(null);
+ selectionMade = true;
+ validatePage();
+ }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ setMessage(null);
+ selectionMade = true;
+ validatePage();
+ }
+ });
+ }
+
+ //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.SAVE);
+
+ String[] ext = {"*.sysdynFunctions"};
+ dialog.setFilterExtensions(ext);
+
+ dialog.setText("Export Function Library");
+
+ 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();
+ }
+
+ }
+
+ //Get selection from the tree
+ @SuppressWarnings("unchecked")
+ public static <T> T getExplorerResource(GraphExplorerComposite explorer,
+ Class<T> clazz) {
+ if(explorer == null)
+ return null;
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return null;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();
+ if (inc == null)
+ return null;
+ final T resource = (T) inc.getAdapter(clazz);
+
+ return resource;
+ }
+
+ public boolean createProjects(Resource selection) {
+
+ final String selected = previouslyBrowsedFile;
+ if(selected == null) return false;
+
+ final Resource functionLibrary = getExplorerResource(functionLibraryExplorer, Resource.class);
+ if(functionLibrary == null) return false;
+
+ String name = null;
+ try {
+ name = SimanticsUI.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf))
+ return null;
+ Layer0 l0 = Layer0.getInstance(graph);
+ String name = graph.syncRequest(new PossibleRelatedValue<String>(functionLibrary, l0.HasName, Bindings.STRING ));
+ return name;
+
+ }
+
+ });
+ } catch (DatabaseException ex) {
+ Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ "Failed to read name of function library " + functionLibrary + ", see exception for details.", ex));
+ }
+ if(name == null) return false;
+
+ SimanticsUI.getSession().asyncRequest(new ReadRequest() {
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, functionLibrary);
+ try (TransferableGraphSource tgs = graph.syncRequest( new ModelTransferableGraphSourceRequest(conf) )) {
+ TransferableGraphs.writeTransferableGraph(graph, tgs, new File(selected), TGStatusMonitor.NULL_MONITOR);
+ } catch (Exception e) {
+ Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ "Failed to export function library, see exception for details.", e));
+ }
+ }
+ });
+
+ return true;
+ }
+
+ void validatePage() {
+
+ if (previouslyBrowsedFile.isEmpty() || selectionMade == false){
+ setPageComplete(false);
+ return;
+ }
+
+ if (functionLibraryExplorer != null){
+ final Resource selectedResource = getExplorerResource(functionLibraryExplorer, Resource.class);
+
+ String root = null;
+ try {
+ root = SimanticsUI.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource model = graph.getPossibleObject(selectedResource, l0.PartOf);
+ String rootName = NameUtils.getSafeName(graph, model);
+
+ return rootName;
+ }
+
+ });
+ if (root != null && root.equalsIgnoreCase("Development Project")){
+ setPageComplete(false);
+ setMessage("Select Function Library folder under the Model or from the Shared Functions folder.");
+ return;
+ }
+ } catch (DatabaseException e) {
+ Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ "Failed to validate wizard page contents, see exception for details.", e));
+ }
+ }
+
+ setPageComplete(true);
+
+ }
+
}
\ No newline at end of file
-package org.simantics.sysdyn.ui.wizards.functions;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Path;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.PixelConverter;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-\r
-public class WizardFunctionsImportPage extends WizardPage{\r
-\r
- // dialog store id constants\r
- private Text filePathField;\r
-\r
- // Keep track of the archive that we browsed to last time\r
- // the wizard was invoked.\r
- private static String previouslyBrowsedFile = "";\r
-\r
- private Button browseDirectoriesButton;\r
-\r
- private Shell shell;\r
-\r
- //private IStructuredSelection currentSelection;\r
-\r
- private Resource selectedModel;\r
-\r
- GraphExplorerComposite functionLibraryExplorer;\r
- \r
- private boolean selectionMade = false;\r
- \r
- /**\r
- * Creates a new project creation wizard page.\r
- * \r
- */\r
- public WizardFunctionsImportPage() {\r
- this("wizardFunctionsImportPage", null, null); //$NON-NLS-1$\r
- }\r
-\r
- /**\r
- * Create a new instance of the receiver.\r
- * \r
- * @param pageName\r
- */\r
- public WizardFunctionsImportPage(String pageName) {\r
- this(pageName,null, null);\r
- }\r
-\r
- /**\r
- * More (many more) parameters.\r
- * \r
- * @param pageName\r
- * @param initialPath\r
- * @param currentSelection\r
- * @since 3.5\r
- */\r
- public WizardFunctionsImportPage(String pageName,String initialPath,\r
- IStructuredSelection currentSelection) {\r
- super(pageName);\r
- setPageComplete(false);\r
- //this.currentSelection = currentSelection;\r
- setTitle("Import Function Library");\r
- setDescription("Choose the Function Library file and the import location, then press Finish.");\r
- }\r
-\r
- public void createControl(Composite parent) {\r
-\r
- initializeDialogUnits(parent);\r
-\r
- Composite workArea = new Composite(parent, SWT.NONE);\r
- setControl(workArea);\r
-\r
- workArea.setLayout(new GridLayout());\r
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
-\r
- createProjectsRoot(workArea);\r
-\r
- createTree(workArea);\r
- \r
- \r
- }\r
-\r
- private void createProjectsRoot(Composite workArea) {\r
-\r
- //set label for field\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select Function Library source:");\r
-\r
- Composite projectGroup = new Composite(workArea, SWT.NONE);\r
- GridLayout layout = new GridLayout();\r
- layout.numColumns = 2;\r
- layout.makeColumnsEqualWidth = false;\r
- layout.marginWidth = 0;\r
-\r
- projectGroup.setLayout(layout);\r
- projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
-\r
- // module location entry field\r
- this.filePathField = new Text(projectGroup, SWT.BORDER);\r
-\r
- GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
- directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
- filePathField.setLayoutData(directoryPathData);\r
- \r
-\r
- filePathField.addModifyListener(new ModifyListener(){\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- previouslyBrowsedFile = filePathField.getText(); \r
- }\r
- });\r
- if (previouslyBrowsedFile != null){\r
- filePathField.setText(previouslyBrowsedFile);\r
- validatePage();\r
- }\r
-\r
- // browse button\r
- browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
- browseDirectoriesButton.setText("Browse");\r
- setButtonLayoutData(browseDirectoriesButton);\r
-\r
- browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
- * elected(org.eclipse.swt.events.SelectionEvent)\r
- */\r
- public void widgetSelected(SelectionEvent e) {\r
- handleLocationDirectoryButtonPressed();\r
- }\r
- });\r
-\r
- }\r
-\r
- private void createTree(Composite workArea){\r
- \r
- //set label for tree\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select import location:");\r
-\r
- try {\r
- Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph)\r
- throws DatabaseException {\r
- Resource model = SimanticsUI.getProject().get();\r
- return model;\r
- }\r
-\r
- });\r
-\r
- functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
-\r
- functionLibraryExplorer\r
- .setBrowseContexts(SysdynResource.URIs.FunctionTree);\r
-\r
- functionLibraryExplorer.finish();\r
-\r
- functionLibraryExplorer.setInput(null, input);\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- functionLibraryExplorer);\r
- \r
- ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
- \r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- });\r
-\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- }\r
-\r
- //Set filePathField active\r
- public void setVisible(boolean visible) {\r
- super.setVisible(visible);\r
- this.filePathField.setFocus();\r
- }\r
-\r
- //Open dialog for choosing the file\r
- protected void handleLocationDirectoryButtonPressed() {\r
-\r
- shell = filePathField.getShell();\r
-\r
- FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
-\r
- String[] ext = {"*.sysdynFunctions; *.tg", "*.*"};\r
- dialog.setFilterExtensions(ext);\r
-\r
- dialog.setText("Import Function Library");\r
-\r
- String dirName = filePathField.getText().trim();\r
-\r
- File path = new File(dirName);\r
- if (path.exists()) {\r
- dialog.setFilterPath(new Path(dirName).toOSString()); \r
- }\r
-\r
- String selectedFile = dialog.open();\r
- if (selectedFile != null) {\r
- filePathField.setText(selectedFile);\r
- validatePage();\r
- } \r
- }\r
-\r
- //Get selection from the tree\r
- @SuppressWarnings("unchecked")\r
- public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
- Class<T> clazz) {\r
- \r
- if(explorer == null)\r
- return null;\r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return null;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
- if (inc == null)\r
- return null;\r
- final T resource = (T) inc.getAdapter(clazz);\r
-\r
- return resource;\r
- }\r
-\r
- //Create project after finish is pressed.\r
- public boolean createProjects() {\r
- \r
- selectedModel= getExplorerResource(functionLibraryExplorer, Resource.class);\r
- if(selectedModel == null){\r
- setErrorMessage("Error when retrieving resource");\r
- return false;\r
- }\r
- \r
- String selected = previouslyBrowsedFile;\r
- if(selected == null){\r
- setErrorMessage("No file selected");\r
- return false;\r
- }\r
- \r
- IStatus status = ImportUtilsUI.importFunctionLibrary(selectedModel, selected, null);\r
-\r
- /*\r
- TransferableGraph1 tg = null;\r
- try {\r
- tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
- } catch (RuntimeBindingConstructionException e) {\r
- e.printStackTrace();\r
- return false;\r
- } catch (IOException e) {\r
- setErrorMessage("The imported file is not of type: Function Library");\r
- return false;\r
- } \r
- if(tg == null){\r
- setErrorMessage("The imported file is not of type: Function Library");\r
- return false;\r
- }\r
-\r
-\r
- try {\r
- Boolean hasSharedOntologies;\r
- hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
-\r
- @Override\r
- public Boolean perform(ReadGraph graph) throws DatabaseException {\r
- try {\r
- graph.getResource("http://SharedOntologies");\r
- } catch (ResourceNotFoundException e) {\r
- return false;\r
- } \r
- return true;\r
- }\r
- });\r
-\r
- if(!hasSharedOntologies) {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- GraphUtils.create2(graph, l0.Library, \r
- l0.HasName, "SharedOntologies",\r
- l0.PartOf, graph.getResource("http:/"));\r
- }\r
- });\r
-\r
- }\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- return false;\r
- }\r
-\r
-\r
- SysdynFunctionLibraryImportAdvisor ia = new SysdynFunctionLibraryImportAdvisor(selectedModel);\r
- try {\r
- DefaultPasteHandler.defaultExecute(tg, selectedModel, ia);\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
-\r
- final Resource root = ia.getRoot();\r
-\r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- if(graph.isInstanceOf(root, SysdynResource.getInstance(graph).SharedFunctionOntology)) {\r
- Resource library = graph.getResource("http://SharedOntologies");\r
- if(!graph.hasStatement(library, l0.ConsistsOf, root)) {\r
- graph.claim(library, l0.ConsistsOf, root);\r
- }\r
-\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Resource model = selectedModel;\r
- while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))\r
- model = graph.getSingleObject(model, l0.PartOf);\r
- if(graph.isInstanceOf(model, sr.SysdynModel)) {\r
- graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, root);\r
- }\r
-\r
- } else if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {\r
- Resource instanceOf = graph.getPossibleObject(root,l0.InstanceOf);\r
- String type = "...";\r
- if(instanceOf != null)\r
- type = NameUtils.getSafeName(graph, instanceOf);\r
- else {\r
- Resource inheritedFrom = graph.getPossibleObject(root, l0.Inherits);\r
- if(inheritedFrom != null)\r
- type = NameUtils.getSafeName(graph, inheritedFrom);\r
- } \r
- graph.deny(root, l0.PartOf);\r
- error = type;\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- if (!error.isEmpty()){\r
- setErrorMessage("The imported file is not of type: Function Library (" + error +")");\r
- error = "";\r
- return false;\r
- }\r
- */\r
- if(status == null || !status.equals(Status.OK_STATUS)) {\r
- setErrorMessage(status.getMessage());\r
- return false;\r
- }\r
- return true;\r
- }\r
- /*\r
-\r
- private class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
-\r
- public SysdynFunctionLibraryImportAdvisor(Resource library) {\r
- super(library);\r
- }\r
-\r
- @Override\r
- public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {\r
- if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {\r
- try {\r
- library = graph.getResource("http://SharedOntologies");\r
- } catch (ResourceNotFoundException e) {\r
- e.printStackTrace();\r
- }\r
- }\r
- }\r
-\r
- @Override\r
- public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {\r
- Layer0 l0 = graph.getService(Layer0.class);\r
- this.root = graph.newResource();\r
- graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);\r
- String name = root.name;\r
- String newName = nameMappings.get(name);\r
- graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);\r
- return this.root;\r
-\r
- }\r
-\r
- }\r
- */\r
- \r
- void validatePage() {\r
-\r
- if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
- setPageComplete(false);\r
- return;\r
- }\r
- setErrorMessage(null);\r
- setPageComplete(true);\r
-\r
- }\r
-\r
+package org.simantics.sysdyn.ui.wizards.functions;
+
+import java.io.File;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.PixelConverter;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+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.events.SelectionListener;
+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.eclipse.swt.widgets.Tree;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+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.sysdyn.ui.utils.imports.ImportUtilsUI;
+import org.simantics.ui.SimanticsUI;
+import org.simantics.utils.datastructures.ArrayMap;
+
+public class WizardFunctionsImportPage 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;
+
+ private Shell shell;
+
+ //private IStructuredSelection currentSelection;
+
+ private Resource selectedModel;
+
+ GraphExplorerComposite functionLibraryExplorer;
+
+ private boolean selectionMade = false;
+
+ /**
+ * Creates a new project creation wizard page.
+ *
+ */
+ public WizardFunctionsImportPage() {
+ this("wizardFunctionsImportPage", null, null); //$NON-NLS-1$
+ }
+
+ /**
+ * Create a new instance of the receiver.
+ *
+ * @param pageName
+ */
+ public WizardFunctionsImportPage(String pageName) {
+ this(pageName,null, null);
+ }
+
+ /**
+ * More (many more) parameters.
+ *
+ * @param pageName
+ * @param initialPath
+ * @param currentSelection
+ * @since 3.5
+ */
+ public WizardFunctionsImportPage(String pageName,String initialPath,
+ IStructuredSelection currentSelection) {
+ super(pageName);
+ setPageComplete(false);
+ //this.currentSelection = currentSelection;
+ setTitle("Import Function Library");
+ setDescription("Choose the Function Library file and the import location, 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);
+
+ createTree(workArea);
+
+
+ }
+
+ private void createProjectsRoot(Composite workArea) {
+
+ //set label for field
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select Function Library 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));
+
+ // module 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();
+ }
+ });
+
+ }
+
+ private void createTree(Composite workArea){
+
+ //set label for tree
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select import location:");
+
+ try {
+ Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph)
+ throws DatabaseException {
+ Resource model = SimanticsUI.getProject().get();
+ return model;
+ }
+
+ });
+
+ functionLibraryExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
+
+ functionLibraryExplorer
+ .setBrowseContexts(SysdynResource.URIs.FunctionTree);
+
+ functionLibraryExplorer.finish();
+
+ functionLibraryExplorer.setInput(null, input);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ functionLibraryExplorer);
+
+ ((Tree)functionLibraryExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ selectionMade = true;
+ validatePage();
+ }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ selectionMade = true;
+ validatePage();
+ }
+ });
+
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ //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 = {"*.sysdynFunctions; *.tg", "*.*"};
+ dialog.setFilterExtensions(ext);
+
+ dialog.setText("Import Function Library");
+
+ 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();
+ }
+ }
+
+ //Get selection from the tree
+ @SuppressWarnings("unchecked")
+ public static <T> T getExplorerResource(GraphExplorerComposite explorer,
+ Class<T> clazz) {
+
+ if(explorer == null)
+ return null;
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return null;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();
+ if (inc == null)
+ return null;
+ final T resource = (T) inc.getAdapter(clazz);
+
+ return resource;
+ }
+
+ //Create project after finish is pressed.
+ public boolean createProjects() {
+
+ selectedModel= getExplorerResource(functionLibraryExplorer, Resource.class);
+ if(selectedModel == null){
+ setErrorMessage("Error when retrieving resource");
+ return false;
+ }
+
+ String selected = previouslyBrowsedFile;
+ if(selected == null){
+ setErrorMessage("No file selected");
+ return false;
+ }
+
+ IStatus status = ImportUtilsUI.importFunctionLibrary(selectedModel, selected, null);
+
+ /*
+ TransferableGraph1 tg = null;
+ try {
+ tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));
+ } catch (RuntimeBindingConstructionException e) {
+ e.printStackTrace();
+ return false;
+ } catch (IOException e) {
+ setErrorMessage("The imported file is not of type: Function Library");
+ return false;
+ }
+ if(tg == null){
+ setErrorMessage("The imported file is not of type: Function Library");
+ return false;
+ }
+
+
+ try {
+ Boolean hasSharedOntologies;
+ hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {
+
+ @Override
+ public Boolean perform(ReadGraph graph) throws DatabaseException {
+ try {
+ graph.getResource("http://SharedOntologies");
+ } catch (ResourceNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
+ });
+
+ if(!hasSharedOntologies) {
+ SimanticsUI.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ GraphUtils.create2(graph, l0.Library,
+ l0.HasName, "SharedOntologies",
+ l0.PartOf, graph.getResource("http:/"));
+ }
+ });
+
+ }
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ return false;
+ }
+
+
+ SysdynFunctionLibraryImportAdvisor ia = new SysdynFunctionLibraryImportAdvisor(selectedModel);
+ try {
+ DefaultPasteHandler.defaultExecute(tg, selectedModel, ia);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ final Resource root = ia.getRoot();
+
+ try {
+ SimanticsUI.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ if(graph.isInstanceOf(root, SysdynResource.getInstance(graph).SharedFunctionOntology)) {
+ Resource library = graph.getResource("http://SharedOntologies");
+ if(!graph.hasStatement(library, l0.ConsistsOf, root)) {
+ graph.claim(library, l0.ConsistsOf, root);
+ }
+
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Resource model = selectedModel;
+ while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))
+ model = graph.getSingleObject(model, l0.PartOf);
+ if(graph.isInstanceOf(model, sr.SysdynModel)) {
+ graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, root);
+ }
+
+ } else if(!graph.isInstanceOf(root, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {
+ Resource instanceOf = graph.getPossibleObject(root,l0.InstanceOf);
+ String type = "...";
+ if(instanceOf != null)
+ type = NameUtils.getSafeName(graph, instanceOf);
+ else {
+ Resource inheritedFrom = graph.getPossibleObject(root, l0.Inherits);
+ if(inheritedFrom != null)
+ type = NameUtils.getSafeName(graph, inheritedFrom);
+ }
+ graph.deny(root, l0.PartOf);
+ error = type;
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+ if (!error.isEmpty()){
+ setErrorMessage("The imported file is not of type: Function Library (" + error +")");
+ error = "";
+ return false;
+ }
+ */
+ if(status == null || !status.equals(Status.OK_STATUS)) {
+ setErrorMessage(status.getMessage());
+ return false;
+ }
+ return true;
+ }
+ /*
+
+ private class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {
+
+ public SysdynFunctionLibraryImportAdvisor(Resource library) {
+ super(library);
+ }
+
+ @Override
+ public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {
+ if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {
+ try {
+ library = graph.getResource("http://SharedOntologies");
+ } catch (ResourceNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {
+ Layer0 l0 = graph.getService(Layer0.class);
+ this.root = graph.newResource();
+ graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);
+ String name = root.name;
+ String newName = nameMappings.get(name);
+ graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);
+ return this.root;
+
+ }
+
+ }
+ */
+
+ void validatePage() {
+
+ if (previouslyBrowsedFile.isEmpty() || selectionMade == false){
+ setPageComplete(false);
+ return;
+ }
+ setErrorMessage(null);
+ setPageComplete(true);
+
+ }
+
}
\ No newline at end of file
-package org.simantics.sysdyn.ui.wizards.models;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Path;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.PixelConverter;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
-import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
-import org.simantics.graph.db.TGStatusMonitor;\r
-import org.simantics.graph.db.TransferableGraphSource;\r
-import org.simantics.graph.db.TransferableGraphs;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-\r
-public class WizardModelsExportPage extends WizardPage {\r
- \r
- // dialog store id constants\r
- private Text filePathField;\r
- \r
- // Keep track of the archive that we browsed to last time\r
- // the wizard was invoked.\r
-\r
- private static String previouslyBrowsedFile = "";\r
-\r
- private Button browseDirectoriesButton;\r
- \r
- //private IStructuredSelection currentSelection;\r
- \r
- private Resource selectedModel;\r
- \r
- GraphExplorerComposite modelExplorer;\r
- \r
- private boolean selectionMade = false;\r
- \r
- \r
- \r
- /**\r
- * Creates a new project creation wizard page.\r
- * \r
- */\r
- public WizardModelsExportPage() {\r
- this("wizardModelsExportPage", null, null); //$NON-NLS-1$\r
- }\r
-\r
- /**\r
- * Create a new instance of the receiver.\r
- * \r
- * @param pageName\r
- */\r
- public WizardModelsExportPage(String pageName) {\r
- this(pageName,null, null);\r
- }\r
- \r
- /**\r
- * More (many more) parameters.\r
- * \r
- * @param pageName\r
- * @param initialPath\r
- * @param currentSelection\r
- * @since 3.5\r
- */\r
- public WizardModelsExportPage(String pageName,String initialPath,\r
- IStructuredSelection currentSelection) {\r
- super(pageName);\r
- //this.currentSelection = currentSelection;\r
- setPageComplete(false);\r
- setTitle("Export Model");\r
- setDescription("Choose the Model and the export location, then press Finish.");\r
- }\r
- \r
- public void createControl(Composite parent) {\r
- \r
- initializeDialogUnits(parent);\r
-\r
- Composite workArea = new Composite(parent, SWT.NONE);\r
- setControl(workArea);\r
-\r
- workArea.setLayout(new GridLayout());\r
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
- \r
- createProjectsRoot(workArea);\r
- createTree (workArea);\r
- }\r
- \r
- private void createProjectsRoot(Composite workArea) {\r
- \r
- // set label for field\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select the export location for Model:");\r
- \r
- Composite projectGroup = new Composite(workArea, SWT.NONE);\r
- GridLayout layout = new GridLayout();\r
- layout.numColumns = 2;\r
- layout.makeColumnsEqualWidth = false;\r
- layout.marginWidth = 0;\r
-\r
- projectGroup.setLayout(layout);\r
- projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
- \r
- // model location entry field\r
- this.filePathField = new Text(projectGroup, SWT.BORDER);\r
-\r
- GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
- directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
- filePathField.setLayoutData(directoryPathData);\r
- \r
- filePathField.addModifyListener(new ModifyListener(){\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- previouslyBrowsedFile = filePathField.getText(); \r
- }\r
- });\r
- if (previouslyBrowsedFile != null){\r
- filePathField.setText(previouslyBrowsedFile);\r
- validatePage();\r
- }\r
-\r
- // browse button\r
- browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
- browseDirectoriesButton.setText("Browse");\r
- setButtonLayoutData(browseDirectoriesButton);\r
- \r
- browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
- * elected(org.eclipse.swt.events.SelectionEvent)\r
- */\r
- public void widgetSelected(SelectionEvent e) {\r
- handleLocationDirectoryButtonPressed();\r
- }\r
- });\r
- \r
- }\r
-\r
- private void createTree(Composite workArea){\r
-\r
- //set label for tree\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select Model to export:");\r
-\r
- Resource input = SimanticsUI.getProject().get();\r
-\r
- modelExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
-\r
- modelExplorer\r
- .setBrowseContexts(SysdynResource.URIs.ImportModuleTree);\r
-\r
- modelExplorer.finish();\r
-\r
- modelExplorer.setInput(null, input);\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- modelExplorer);\r
-\r
- ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
-\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- });\r
- }\r
-\r
- //Set filePathField active\r
- public void setVisible(boolean visible) {\r
- super.setVisible(visible);\r
- this.filePathField.setFocus();\r
- }\r
- \r
- //Open dialog for choosing the file\r
- protected void handleLocationDirectoryButtonPressed() {\r
- final Shell shell = filePathField.getShell();\r
- \r
- FileDialog dialog = new FileDialog(shell, SWT.SAVE);\r
- \r
- String[] ext = {"*.sysdyn"};\r
- dialog.setFilterExtensions(ext);\r
- \r
- dialog.setText("Export Model");\r
-\r
- String dirName = filePathField.getText().trim();\r
- \r
- File path = new File(dirName);\r
- if (path.exists()) {\r
- dialog.setFilterPath(new Path(dirName).toOSString());\r
- }\r
- \r
- String selectedFile = dialog.open();\r
- if (selectedFile != null) {\r
- filePathField.setText(selectedFile);\r
- validatePage();\r
- } \r
-\r
- }\r
- //Get selection from the tree\r
- @SuppressWarnings("unchecked")\r
- public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
- Class<T> clazz) {\r
- \r
- if(explorer == null)\r
- return null;\r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return null;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
- if (inc == null)\r
- return null;\r
- final T resource = (T) inc.getAdapter(clazz);\r
-\r
- return resource;\r
- }\r
- \r
- public boolean createProjects() {\r
- \r
- final String selected = previouslyBrowsedFile;\r
- if(selected == null) return false;\r
- \r
- selectedModel = getExplorerResource(modelExplorer, Resource.class);\r
- if(selectedModel == null)\r
- return false;\r
- \r
- // FIXME: Model browser doesn't change its selection even if the selected object is removed,\r
- // so you can try to export a removed model \r
- \r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, selectedModel);\r
- try (TransferableGraphSource tgs = graph.syncRequest( new ModelTransferableGraphSourceRequest(conf) )) {\r
- TransferableGraphs.writeTransferableGraph(graph, tgs, new File(selected), TGStatusMonitor.NULL_MONITOR);\r
- } catch (Exception e) {\r
- Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,\r
- "Failed to export model, see exception for details.", e));\r
- }\r
- }\r
- });\r
-\r
- return true;\r
- }\r
- \r
- void validatePage() {\r
- \r
- if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
- setPageComplete(false);\r
- return;\r
- }\r
- \r
- setPageComplete(true);\r
- \r
- }\r
-}\r
+package org.simantics.sysdyn.ui.wizards.models;
+
+import java.io.File;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.PixelConverter;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+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.events.SelectionListener;
+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.eclipse.swt.widgets.Tree;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+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.util.ModelTransferableGraphSourceRequest;
+import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
+import org.simantics.graph.db.TGStatusMonitor;
+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 {
+
+ // 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;
+
+ //private IStructuredSelection currentSelection;
+
+ private Resource selectedModel;
+
+ GraphExplorerComposite modelExplorer;
+
+ private boolean selectionMade = false;
+
+
+
+ /**
+ * Creates a new project creation wizard page.
+ *
+ */
+ public WizardModelsExportPage() {
+ this("wizardModelsExportPage", null, null); //$NON-NLS-1$
+ }
+
+ /**
+ * Create a new instance of the receiver.
+ *
+ * @param pageName
+ */
+ public WizardModelsExportPage(String pageName) {
+ this(pageName,null, null);
+ }
+
+ /**
+ * More (many more) parameters.
+ *
+ * @param pageName
+ * @param initialPath
+ * @param currentSelection
+ * @since 3.5
+ */
+ public WizardModelsExportPage(String pageName,String initialPath,
+ IStructuredSelection currentSelection) {
+ super(pageName);
+ //this.currentSelection = currentSelection;
+ setPageComplete(false);
+ setTitle("Export Model");
+ setDescription("Choose the Model and the export location, 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);
+ createTree (workArea);
+ }
+
+ private void createProjectsRoot(Composite workArea) {
+
+ // set label for field
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select the export location for Model:");
+
+ 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();
+ }
+ });
+
+ }
+
+ private void createTree(Composite workArea){
+
+ //set label for tree
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select Model to export:");
+
+ Resource input = SimanticsUI.getProject().get();
+
+ modelExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
+
+ modelExplorer
+ .setBrowseContexts(SysdynResource.URIs.ImportModuleTree);
+
+ modelExplorer.finish();
+
+ modelExplorer.setInput(null, input);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ modelExplorer);
+
+ ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ selectionMade = true;
+ validatePage();
+ }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ selectionMade = true;
+ validatePage();
+ }
+ });
+ }
+
+ //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.SAVE);
+
+ String[] ext = {"*.sysdyn"};
+ dialog.setFilterExtensions(ext);
+
+ dialog.setText("Export Model");
+
+ 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();
+ }
+
+ }
+ //Get selection from the tree
+ @SuppressWarnings("unchecked")
+ public static <T> T getExplorerResource(GraphExplorerComposite explorer,
+ Class<T> clazz) {
+
+ if(explorer == null)
+ return null;
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return null;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();
+ if (inc == null)
+ return null;
+ final T resource = (T) inc.getAdapter(clazz);
+
+ return resource;
+ }
+
+ public boolean createProjects() {
+
+ final String selected = previouslyBrowsedFile;
+ if(selected == null) return false;
+
+ selectedModel = getExplorerResource(modelExplorer, Resource.class);
+ if(selectedModel == null)
+ return false;
+
+ // 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() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, selectedModel);
+ try (TransferableGraphSource tgs = graph.syncRequest( new ModelTransferableGraphSourceRequest(conf) )) {
+ TransferableGraphs.writeTransferableGraph(graph, tgs, new File(selected), TGStatusMonitor.NULL_MONITOR);
+ } catch (Exception e) {
+ Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ "Failed to export model, see exception for details.", e));
+ }
+ }
+ });
+
+ return true;
+ }
+
+ void validatePage() {
+
+ if (previouslyBrowsedFile.isEmpty() || selectionMade == false){
+ setPageComplete(false);
+ return;
+ }
+
+ setPageComplete(true);
+
+ }
+}
-package org.simantics.sysdyn.ui.wizards.modules;\r
-\r
-import java.io.File;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Path;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.PixelConverter;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;\r
-import org.simantics.db.layer0.util.TransferableGraphConfiguration2;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.graph.db.TGStatusMonitor;\r
-import org.simantics.graph.db.TransferableGraphSource;\r
-import org.simantics.graph.db.TransferableGraphs;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-public class WizardModulesExportPage extends WizardPage {\r
- \r
- // dialog store id constants\r
- private Text filePathField;\r
- \r
- // Keep track of the archive that we browsed to last time\r
- // the wizard was invoked.\r
- private static String previouslyBrowsedFile = "";\r
-\r
- private Button browseDirectoriesButton;\r
- \r
- private Resource selectedModule;\r
- \r
- GraphExplorerComposite modelExplorer;\r
-\r
- private boolean selectionMade = false;\r
- \r
- /**\r
- * Creates a new project creation wizard page.\r
- * \r
- */\r
- public WizardModulesExportPage() {\r
- this("wizardModulesExportPage", null, null); //$NON-NLS-1$\r
- }\r
-\r
- /**\r
- * Create a new instance of the receiver.\r
- * \r
- * @param pageName\r
- */\r
- public WizardModulesExportPage(String pageName) {\r
- this(pageName,null, null);\r
- }\r
- \r
- /**\r
- * More (many more) parameters.\r
- * \r
- * @param pageName\r
- * @param initialPath\r
- * @param currentSelection\r
- * @since 3.5\r
- */\r
- public WizardModulesExportPage(String pageName,String initialPath,\r
- IStructuredSelection currentSelection) {\r
- super(pageName);\r
- //this.currentSelection = currentSelection;\r
- setPageComplete(false);\r
- setTitle("Export Module");\r
- setDescription("Choose the Module and the export location, then press Finish.");\r
- }\r
- \r
- public void createControl(Composite parent) {\r
- \r
- initializeDialogUnits(parent);\r
-\r
- Composite workArea = new Composite(parent, SWT.NONE);\r
- setControl(workArea);\r
-\r
- workArea.setLayout(new GridLayout());\r
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
-\r
- createProjectsRoot(workArea);\r
- createTree(workArea);\r
- }\r
- \r
- private void createProjectsRoot(Composite workArea) {\r
- \r
- // set label for field\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select the export location for Module:");\r
- \r
- Composite projectGroup = new Composite(workArea, SWT.NONE);\r
- GridLayout layout = new GridLayout();\r
- layout.numColumns = 2;\r
- layout.makeColumnsEqualWidth = false;\r
- layout.marginWidth = 0;\r
-\r
- projectGroup.setLayout(layout);\r
- projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
- \r
- // module location entry field\r
- this.filePathField = new Text(projectGroup, SWT.BORDER);\r
-\r
- GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
- directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
- filePathField.setLayoutData(directoryPathData);\r
- \r
- filePathField.addModifyListener(new ModifyListener(){\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- previouslyBrowsedFile = filePathField.getText(); \r
- }\r
- });\r
- if (previouslyBrowsedFile != null){\r
- filePathField.setText(previouslyBrowsedFile);\r
- validatePage();\r
- }\r
- \r
- // browse button\r
- browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
- browseDirectoriesButton.setText("Browse");\r
- setButtonLayoutData(browseDirectoriesButton);\r
- \r
- browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
- * elected(org.eclipse.swt.events.SelectionEvent)\r
- */\r
- public void widgetSelected(SelectionEvent e) {\r
- handleLocationDirectoryButtonPressed();\r
- }\r
- });\r
- \r
- }\r
-\r
- private void createTree(Composite workArea){\r
- \r
- //set label for tree\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select Module to export:");\r
-\r
- Resource input = SimanticsUI.getProject().get();\r
-\r
- modelExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
-\r
- modelExplorer\r
- .setBrowseContexts(SysdynResource.URIs.ExportModuleTree);\r
-\r
- modelExplorer.finish();\r
-\r
- modelExplorer.setInput(null, input);\r
-\r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- modelExplorer);\r
-\r
- ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
-\r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- setMessage(null);\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- setMessage(null);\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- });\r
- }\r
-\r
- //Set filePathField active\r
- public void setVisible(boolean visible) {\r
- super.setVisible(visible);\r
- this.filePathField.setFocus();\r
- }\r
- \r
- //Open dialog for choosing the file\r
- protected void handleLocationDirectoryButtonPressed() {\r
- \r
- final Shell shell = filePathField.getShell();\r
- \r
- FileDialog dialog = new FileDialog(shell, SWT.SAVE);\r
- \r
- String[] ext = {"*.sysdynModule"};\r
- dialog.setFilterExtensions(ext);\r
- \r
- dialog.setText("Export Module");\r
-\r
- String dirName = filePathField.getText().trim();\r
- \r
- File path = new File(dirName);\r
- if (path.exists()) {\r
- dialog.setFilterPath(new Path(dirName).toOSString()); \r
- }\r
- \r
- String selectedFile = dialog.open();\r
- if (selectedFile != null) {\r
- filePathField.setText(selectedFile);\r
- validatePage();\r
- } \r
-\r
- }\r
- \r
- //Get selection from the tree\r
- @SuppressWarnings("unchecked")\r
- public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
- Class<T> clazz) {\r
- \r
- if(explorer == null)\r
- return null;\r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return null;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
- if (inc == null)\r
- return null;\r
- final T resource = (T) inc.getAdapter(clazz);\r
-\r
- return resource;\r
- }\r
- \r
- //Create export file when finish is pressed\r
- public boolean createProjects() {\r
- \r
- final String selected = previouslyBrowsedFile;\r
- if(selected == null) return false;\r
-\r
- selectedModule= getExplorerResource(modelExplorer, Resource.class);\r
- if(selectedModule == null)\r
- return false;\r
- \r
- String name = null;\r
- try {\r
- name = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- \r
- Resource component = selectedModule;\r
- if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
- return null;\r
- \r
- Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
- if (configuration == null)\r
- return null;\r
- \r
- ArrayList<String> dependencies = null;\r
- for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {\r
- if(dependencies == null)\r
- dependencies = new ArrayList<>();\r
- String name = NameUtils.getSafeName(graph, r);\r
- String instanceOf = NameUtils.getSafeName(graph, graph.getSingleObject(r, l0.InstanceOf));\r
- dependencies.add(name + " : " + instanceOf);\r
- }\r
- if(dependencies != null && !dependencies.isEmpty())\r
- throw new ContainsDependenciesException(dependencies);\r
- \r
- String name = graph.getPossibleRelatedValue(component, l0.HasName, Bindings.STRING);\r
- return name;\r
- \r
- }\r
- \r
- });\r
- } \r
- catch (DatabaseException e1) {\r
- e1.printStackTrace();\r
- }\r
- if(name == null) return false;\r
- \r
- SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
- \r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- final Resource component = selectedModule;\r
- //final Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);\r
- if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))\r
- return;\r
-\r
- graph.asyncRequest(new WriteRequest() {\r
-\r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
- ModelingResources mr = ModelingResources.getInstance(graph);\r
- final Resource modulesymbol = graph.getPossibleObject(component, mr.ComponentTypeToSymbol);\r
- Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
- if (!graph.hasStatement(configuration, l0.PartOf, component)&& \r
- !graph.hasStatement(modulesymbol, l0.PartOf, component)) {\r
- // Make sure that configuration and symbol are included.\r
- // In old versions, they were attached to model, not to module.\r
- Resource previousPartof = graph.getSingleObject(configuration, l0.PartOf);\r
-\r
- graph.deny(configuration, l0.PartOf);\r
- graph.deny(modulesymbol, l0.PartOf);\r
- graph.claim(configuration, l0.PartOf, l0.ConsistsOf, component);\r
- graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, component);\r
-\r
- export(graph, selected, component);\r
-\r
- graph.deny(configuration, l0.PartOf);\r
- graph.deny(modulesymbol, l0.PartOf);\r
- graph.claim(configuration, l0.PartOf, l0.ConsistsOf, previousPartof);\r
- graph.claim(modulesymbol, l0.PartOf, l0.ConsistsOf, previousPartof);\r
- } else {\r
- // Normal export\r
- export(graph, selected, component);\r
- }\r
- }\r
- }, e -> {\r
- Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to export module, see exception for details.", e));\r
- });\r
-\r
- }\r
- });\r
-\r
- return true;\r
- }\r
- \r
- private void export(WriteGraph graph, String path, Resource component) throws DatabaseException {\r
- // FIXME: Enumeration replacement handling like this is not suitable.\r
-\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- SysdynResource sr = SysdynResource.getInstance(graph);\r
- StructuralResource2 sr2 = StructuralResource2.getInstance(graph);\r
-\r
- Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);\r
- ArrayList<Pair<Resource, Resource>> replacements = new ArrayList<>();\r
-\r
- for(Resource enumeration : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Enumeration))) {\r
- if(graph.hasStatement(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
- for(Resource replacement : graph.getObjects(enumeration, sr.Redeclaration_replacedEnumeration_Inverse)) {\r
- replacements.add(Pair.make(enumeration, replacement));\r
- }\r
- }\r
- }\r
-\r
- for(Pair<Resource,Resource> replacement : replacements)\r
- graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
-\r
- try {\r
- TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, component);\r
- try (TransferableGraphSource tgs = graph.syncRequest( new ModelTransferableGraphSourceRequest(conf) )) {\r
- TransferableGraphs.writeTransferableGraph(graph, tgs, new File(path), TGStatusMonitor.NULL_MONITOR);\r
- } catch (Exception e) {\r
- Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,\r
- "Failed to export module, see exception for details.", e));\r
- }\r
- } catch (DatabaseException e) {\r
- throw e;\r
- } catch (Exception e) {\r
- throw new DatabaseException(e);\r
- } finally {\r
- for(Pair<Resource,Resource> replacement : replacements)\r
- graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);\r
- }\r
- }\r
-\r
- class ContainsDependenciesException extends DatabaseException {\r
- private static final long serialVersionUID = -1533706136673146020L;\r
- \r
- private Collection<String> dependencies;\r
- \r
- ContainsDependenciesException(Collection<String> dependencies) {\r
- this.dependencies = dependencies;\r
- }\r
- \r
- public Collection<String> getDependencies() {\r
- return this.dependencies;\r
- }\r
- \r
- }\r
- \r
- void validatePage() {\r
- \r
- if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
- setPageComplete(false);\r
- return;\r
- }\r
- \r
- if (modelExplorer != null){\r
- final Resource selectedResource = getExplorerResource(modelExplorer, Resource.class);\r
-\r
- String root = null;\r
- try {\r
- root = SimanticsUI.getSession().syncRequest(new Read<String>() {\r
-\r
- @Override\r
- public String perform(ReadGraph graph) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(graph);\r
- Resource model = graph.getPossibleObject(selectedResource, l0.PartOf);\r
- String rootName = NameUtils.getSafeName(graph, model);\r
-\r
- return rootName;\r
- }\r
-\r
- });\r
- if (root != null && root.equalsIgnoreCase("Development Project")){\r
- setPageComplete(false);\r
- setMessage("Select Module under the Model.");\r
- return;\r
- }\r
- } catch (DatabaseException e) {\r
- Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,\r
- "Failed to validate wizard page contents, see exception for details.", e));\r
- }\r
- }\r
- \r
- setPageComplete(true);\r
- \r
- }\r
- \r
-\r
-\r
+package org.simantics.sysdyn.ui.wizards.modules;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.PixelConverter;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+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.events.SelectionListener;
+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.eclipse.swt.widgets.Tree;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+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.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.TGStatusMonitor;
+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.ui.SimanticsUI;
+import org.simantics.utils.datastructures.ArrayMap;
+import org.simantics.utils.datastructures.Pair;
+
+public class WizardModulesExportPage 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;
+
+ private Resource selectedModule;
+
+ GraphExplorerComposite modelExplorer;
+
+ private boolean selectionMade = false;
+
+ /**
+ * Creates a new project creation wizard page.
+ *
+ */
+ public WizardModulesExportPage() {
+ this("wizardModulesExportPage", null, null); //$NON-NLS-1$
+ }
+
+ /**
+ * Create a new instance of the receiver.
+ *
+ * @param pageName
+ */
+ public WizardModulesExportPage(String pageName) {
+ this(pageName,null, null);
+ }
+
+ /**
+ * More (many more) parameters.
+ *
+ * @param pageName
+ * @param initialPath
+ * @param currentSelection
+ * @since 3.5
+ */
+ public WizardModulesExportPage(String pageName,String initialPath,
+ IStructuredSelection currentSelection) {
+ super(pageName);
+ //this.currentSelection = currentSelection;
+ setPageComplete(false);
+ setTitle("Export Module");
+ setDescription("Choose the Module and the export location, 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);
+ createTree(workArea);
+ }
+
+ private void createProjectsRoot(Composite workArea) {
+
+ // set label for field
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select the export location for Module:");
+
+ 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));
+
+ // module 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();
+ }
+ });
+
+ }
+
+ private void createTree(Composite workArea){
+
+ //set label for tree
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select Module to export:");
+
+ Resource input = SimanticsUI.getProject().get();
+
+ modelExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
+
+ modelExplorer
+ .setBrowseContexts(SysdynResource.URIs.ExportModuleTree);
+
+ modelExplorer.finish();
+
+ modelExplorer.setInput(null, input);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ modelExplorer);
+
+ ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ setMessage(null);
+ selectionMade = true;
+ validatePage();
+ }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ setMessage(null);
+ selectionMade = true;
+ validatePage();
+ }
+ });
+ }
+
+ //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.SAVE);
+
+ String[] ext = {"*.sysdynModule"};
+ dialog.setFilterExtensions(ext);
+
+ dialog.setText("Export Module");
+
+ 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();
+ }
+
+ }
+
+ //Get selection from the tree
+ @SuppressWarnings("unchecked")
+ public static <T> T getExplorerResource(GraphExplorerComposite explorer,
+ Class<T> clazz) {
+
+ if(explorer == null)
+ return null;
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return null;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();
+ if (inc == null)
+ return null;
+ final T resource = (T) inc.getAdapter(clazz);
+
+ return resource;
+ }
+
+ //Create export file when finish is pressed
+ public boolean createProjects() {
+
+ final String selected = previouslyBrowsedFile;
+ if(selected == null) return false;
+
+ selectedModule= getExplorerResource(modelExplorer, Resource.class);
+ if(selectedModule == null)
+ return false;
+
+ String name = null;
+ try {
+ name = SimanticsUI.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ Layer0 l0 = Layer0.getInstance(graph);
+
+ Resource component = selectedModule;
+ if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))
+ return null;
+
+ Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);
+ if (configuration == null)
+ return null;
+
+ ArrayList<String> dependencies = null;
+ for(Resource r : graph.syncRequest(new ObjectsWithType(configuration, l0.ConsistsOf, sr.Module))) {
+ if(dependencies == null)
+ dependencies = new ArrayList<>();
+ String 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);
+
+ String name = graph.getPossibleRelatedValue(component, l0.HasName, Bindings.STRING);
+ return name;
+
+ }
+
+ });
+ }
+ catch (DatabaseException e1) {
+ e1.printStackTrace();
+ }
+ if(name == null) return false;
+
+ SimanticsUI.getSession().asyncRequest(new ReadRequest() {
+
+ @Override
+ public void run(ReadGraph graph) throws DatabaseException {
+ final Resource component = selectedModule;
+ //final Resource component = graph.getPossibleObject(modulesymbol, mr.SymbolToComponentType);
+ if (component == null || !graph.hasStatement(component, Layer0.getInstance(graph).PartOf))
+ return;
+
+ graph.asyncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+ ModelingResources mr = ModelingResources.getInstance(graph);
+ final Resource modulesymbol = graph.getPossibleObject(component, mr.ComponentTypeToSymbol);
+ 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, 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, component);
+ }
+ }
+ }, e -> {
+ Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to export module, see exception for details.", e));
+ });
+
+ }
+ });
+
+ return true;
+ }
+
+ private void export(WriteGraph graph, String path, Resource component) throws DatabaseException {
+ // FIXME: Enumeration replacement handling like this is not suitable.
+
+ Layer0 l0 = Layer0.getInstance(graph);
+ SysdynResource sr = SysdynResource.getInstance(graph);
+ StructuralResource2 sr2 = StructuralResource2.getInstance(graph);
+
+ Resource configuration = graph.getPossibleObject(component, sr2.IsDefinedBy);
+ ArrayList<Pair<Resource, Resource>> replacements = new ArrayList<>();
+
+ 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(Pair.make(enumeration, replacement));
+ }
+ }
+ }
+
+ for(Pair<Resource,Resource> replacement : replacements)
+ graph.deny(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);
+
+ try {
+ TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, component);
+ try (TransferableGraphSource tgs = graph.syncRequest( new ModelTransferableGraphSourceRequest(conf) )) {
+ TransferableGraphs.writeTransferableGraph(graph, tgs, new File(path), TGStatusMonitor.NULL_MONITOR);
+ } catch (Exception e) {
+ Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ "Failed to export module, see exception for details.", e));
+ }
+ } catch (DatabaseException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new DatabaseException(e);
+ } finally {
+ for(Pair<Resource,Resource> replacement : replacements)
+ graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second);
+ }
+ }
+
+ class ContainsDependenciesException extends DatabaseException {
+ private static final long serialVersionUID = -1533706136673146020L;
+
+ private Collection<String> dependencies;
+
+ ContainsDependenciesException(Collection<String> dependencies) {
+ this.dependencies = dependencies;
+ }
+
+ public Collection<String> getDependencies() {
+ return this.dependencies;
+ }
+
+ }
+
+ void validatePage() {
+
+ if (previouslyBrowsedFile.isEmpty() || selectionMade == false){
+ setPageComplete(false);
+ return;
+ }
+
+ if (modelExplorer != null){
+ final Resource selectedResource = getExplorerResource(modelExplorer, Resource.class);
+
+ String root = null;
+ try {
+ root = SimanticsUI.getSession().syncRequest(new Read<String>() {
+
+ @Override
+ public String perform(ReadGraph graph) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(graph);
+ Resource model = graph.getPossibleObject(selectedResource, l0.PartOf);
+ String rootName = NameUtils.getSafeName(graph, model);
+
+ return rootName;
+ }
+
+ });
+ if (root != null && root.equalsIgnoreCase("Development Project")){
+ setPageComplete(false);
+ setMessage("Select Module under the Model.");
+ return;
+ }
+ } catch (DatabaseException e) {
+ Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
+ "Failed to validate wizard page contents, see exception for details.", e));
+ }
+ }
+
+ setPageComplete(true);
+
+ }
+
+
+
}
\ No newline at end of file
-package org.simantics.sysdyn.ui.wizards.modules;\r
-\r
-import java.io.File;\r
-\r
-import org.eclipse.core.runtime.IStatus;\r
-import org.eclipse.core.runtime.Path;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.jface.layout.GridDataFactory;\r
-import org.eclipse.jface.layout.PixelConverter;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.ISelectionProvider;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.swt.SWT;\r
-import org.eclipse.swt.events.ModifyEvent;\r
-import org.eclipse.swt.events.ModifyListener;\r
-import org.eclipse.swt.events.SelectionAdapter;\r
-import org.eclipse.swt.events.SelectionEvent;\r
-import org.eclipse.swt.events.SelectionListener;\r
-import org.eclipse.swt.layout.GridData;\r
-import org.eclipse.swt.layout.GridLayout;\r
-import org.eclipse.swt.widgets.Button;\r
-import org.eclipse.swt.widgets.Composite;\r
-import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.Label;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Text;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
-import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.sysdyn.SysdynResource;\r
-import org.simantics.sysdyn.ui.utils.imports.ImportUtilsUI;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.ArrayMap;\r
-\r
-\r
-public class WizardModulesImportPage extends WizardPage{\r
- \r
- public static String IMPORTMODULETPATH = "IMPORT_MODULE_PATH";\r
- \r
- // dialog store id constants\r
- \r
- private Text filePathField;\r
- \r
- // Keep track of the archive that we browsed to last time\r
- // the wizard was invoked.\r
- private static String previouslyBrowsedFile = "";\r
-\r
- private Button browseDirectoriesButton;\r
-\r
- private Shell shell;\r
- \r
- //private IStructuredSelection currentSelection;\r
- \r
- private Resource selectedModel;\r
- \r
- GraphExplorerComposite modelExplorer;\r
- \r
- private boolean selectionMade = false;\r
- \r
- /**\r
- * Creates a new project creation wizard page.\r
- * \r
- */\r
- public WizardModulesImportPage() {\r
- this("wizardModulesImportPage", null, null); //$NON-NLS-1$\r
- }\r
-\r
- /**\r
- * Create a new instance of the receiver.\r
- * \r
- * @param pageName\r
- */\r
- public WizardModulesImportPage(String pageName) {\r
- this(pageName,null, null);\r
- }\r
- \r
- /**\r
- * More (many more) parameters.\r
- * \r
- * @param pageName\r
- * @param initialPath\r
- * @param currentSelection\r
- * @since 3.5\r
- */\r
- public WizardModulesImportPage(String pageName,String initialPath,\r
- IStructuredSelection currentSelection) {\r
- super(pageName);\r
- setPageComplete(false);\r
- //this.currentSelection = currentSelection;\r
- setTitle("Import Module");\r
- setDescription("Choose the Module file and the import location, then press Finish.");\r
- }\r
- \r
- public void createControl(Composite parent) {\r
- \r
- initializeDialogUnits(parent);\r
-\r
- Composite workArea = new Composite(parent, SWT.NONE);\r
- setControl(workArea);\r
-\r
- workArea.setLayout(new GridLayout());\r
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH\r
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));\r
-\r
- createProjectsRoot(workArea);\r
- \r
- createTree(workArea);\r
- }\r
- \r
- private void createProjectsRoot(Composite workArea) {\r
- \r
- // set label for field\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select Module source:");\r
- \r
- Composite projectGroup = new Composite(workArea, SWT.NONE);\r
- GridLayout layout = new GridLayout();\r
- layout.numColumns = 2;\r
- layout.makeColumnsEqualWidth = false;\r
- layout.marginWidth = 0;\r
- \r
- projectGroup.setLayout(layout);\r
- projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));\r
- \r
- // module location entry field\r
- this.filePathField = new Text(projectGroup, SWT.BORDER);\r
-\r
- GridData directoryPathData = new GridData(SWT.FILL, SWT.NONE, true, false);\r
- directoryPathData.widthHint = new PixelConverter(filePathField).convertWidthInCharsToPixels(25);\r
- filePathField.setLayoutData(directoryPathData);\r
- \r
- filePathField.addModifyListener(new ModifyListener(){\r
- @Override\r
- public void modifyText(ModifyEvent e) {\r
- previouslyBrowsedFile = filePathField.getText(); \r
- }\r
- });\r
- if (previouslyBrowsedFile != null){\r
- filePathField.setText(previouslyBrowsedFile);\r
- validatePage();\r
- }\r
- \r
- // browse button\r
- browseDirectoriesButton = new Button(projectGroup, SWT.PUSH);\r
- browseDirectoriesButton.setText("Browse");\r
- setButtonLayoutData(browseDirectoriesButton);\r
- \r
- browseDirectoriesButton.addSelectionListener(new SelectionAdapter() {\r
- /*\r
- * (non-Javadoc)\r
- * \r
- * @see org.eclipse.swt.events.SelectionAdapter#widgetS\r
- * elected(org.eclipse.swt.events.SelectionEvent)\r
- */\r
- public void widgetSelected(SelectionEvent e) {\r
- handleLocationDirectoryButtonPressed();\r
- }\r
- });\r
- \r
- }\r
-\r
- private void createTree(Composite workArea){\r
- \r
- //set label for tree\r
- Label title = new Label(workArea, SWT.NONE);\r
- title.setText("Select import location:");\r
-\r
- try {\r
- Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {\r
-\r
- @Override\r
- public Resource perform(ReadGraph graph)\r
- throws DatabaseException {\r
- Resource model = SimanticsUI.getProject().get();\r
- return model;\r
- }\r
-\r
- });\r
-\r
- modelExplorer = new GraphExplorerComposite(ArrayMap.keys(\r
- "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);\r
-\r
- modelExplorer\r
- .setBrowseContexts(SysdynResource.URIs.ImportModuleTree);\r
-\r
- modelExplorer.finish();\r
-\r
- modelExplorer.setInput(null, input);\r
- \r
- GridDataFactory.fillDefaults().grab(true, true).applyTo(\r
- modelExplorer);\r
- \r
- ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {\r
- \r
- @Override\r
- public void widgetSelected(SelectionEvent e) {\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- @Override\r
- public void widgetDefaultSelected(SelectionEvent e) {\r
- selectionMade = true;\r
- validatePage();\r
- }\r
- });\r
- \r
-\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
-\r
- }\r
- \r
- //Set filePathField active\r
- public void setVisible(boolean visible) {\r
- super.setVisible(visible);\r
- this.filePathField.setFocus();\r
- }\r
- \r
- //Open dialog for choosing the file\r
- protected void handleLocationDirectoryButtonPressed() {\r
- \r
- shell = filePathField.getShell();\r
- \r
- FileDialog dialog = new FileDialog(shell, SWT.OPEN);\r
- \r
- String[] ext = {"*.sysdynModule; *.tg", "*.*"};\r
- dialog.setFilterExtensions(ext);\r
- \r
- dialog.setText("Import Module");\r
-\r
- String dirName = filePathField.getText().trim();\r
- \r
- File path = new File(dirName);\r
- if (path.exists()) {\r
- dialog.setFilterPath(new Path(dirName).toOSString()); \r
- }\r
- \r
- String selectedFile = dialog.open();\r
- if (selectedFile != null) {\r
- filePathField.setText(selectedFile);\r
- validatePage();\r
- } \r
- }\r
- \r
- //Get selection from the tree\r
- @SuppressWarnings("unchecked")\r
- public static <T> T getExplorerResource(GraphExplorerComposite explorer,\r
- Class<T> clazz) {\r
- \r
- if(explorer == null)\r
- return null;\r
- ISelection selection = ((ISelectionProvider) explorer\r
- .getAdapter(ISelectionProvider.class)).getSelection();\r
- if (selection == null)\r
- return null;\r
- IStructuredSelection iss = (IStructuredSelection) selection;\r
- AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();\r
- if (inc == null)\r
- return null;\r
- final T resource = (T) inc.getAdapter(clazz);\r
-\r
- return resource;\r
- }\r
- \r
- //Create project after finish is pressed.\r
- public boolean createProjects() {\r
- \r
- String selected = previouslyBrowsedFile;\r
- if(selected == null){ \r
- setErrorMessage("Error when retrieving resource");\r
- return false;\r
- }\r
- \r
- selectedModel= getExplorerResource(modelExplorer, Resource.class);\r
- if(selectedModel == null){\r
- setErrorMessage("No file selected");\r
- return false;\r
- }\r
- \r
- IStatus status = ImportUtilsUI.importModuleFile(selectedModel, selected, null);\r
- \r
- /*\r
- TransferableGraph1 tg = null;\r
- try {\r
- tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
- } catch (RuntimeBindingConstructionException e) {\r
- e.printStackTrace();\r
- } catch (IOException e) {\r
- setErrorMessage("The imported file is not of type: Module Type");\r
- return false;\r
- }\r
- if(tg == null){\r
- setErrorMessage("The imported file is not of type: Module Type");\r
- return false;\r
- }\r
-\r
- \r
- DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(selectedModel);\r
- try {\r
- DefaultPasteHandler.defaultExecute(tg, selectedModel, ia);\r
- } catch (MissingDependencyException e) {\r
- e.printStackTrace();\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
- }\r
- \r
- final Resource root = ia.getRoot();\r
- \r
- try {\r
- SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
- \r
- @Override\r
- public void perform(WriteGraph graph) throws DatabaseException {\r
- if(!graph.isInheritedFrom(root, SysdynResource.getInstance(graph).Module)) {\r
- Resource instanceOf = graph.getPossibleObject(root, Layer0.getInstance(graph).InstanceOf);\r
- String type = "...";\r
- if(instanceOf != null)\r
- type = NameUtils.getSafeName(graph, instanceOf);\r
- else {\r
- Resource inheritedFrom = graph.getPossibleObject(root, Layer0.getInstance(graph).Inherits);\r
- if(inheritedFrom != null)\r
- type = NameUtils.getSafeName(graph, inheritedFrom);\r
- }\r
- graph.deny(root, Layer0.getInstance(graph).PartOf);\r
- error = type;\r
- }\r
- }\r
- });\r
- } catch (DatabaseException e) {\r
- e.printStackTrace();\r
- }\r
- \r
- if (!error.isEmpty()){\r
- setErrorMessage("The imported file is not of type: Module Type (" + error +")");\r
- error = "";\r
- return false;\r
- }\r
- */\r
- if(status == null || !status.equals(Status.OK_STATUS)) {\r
- setErrorMessage(status.getMessage());\r
- return false;\r
- }\r
-\r
- return true;\r
- }\r
- \r
- void validatePage() {\r
- \r
- if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
- setPageComplete(false);\r
- return;\r
- }\r
- \r
- setErrorMessage(null);\r
- setPageComplete(true);\r
- \r
- }\r
- \r
+package org.simantics.sysdyn.ui.wizards.modules;
+
+import java.io.File;
+
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Status;
+import org.eclipse.jface.layout.GridDataFactory;
+import org.eclipse.jface.layout.PixelConverter;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.ISelectionProvider;
+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.events.SelectionListener;
+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.eclipse.swt.widgets.Tree;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
+import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;
+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.sysdyn.ui.utils.imports.ImportUtilsUI;
+import org.simantics.ui.SimanticsUI;
+import org.simantics.utils.datastructures.ArrayMap;
+
+
+public class WizardModulesImportPage extends WizardPage{
+
+ public static String IMPORTMODULETPATH = "IMPORT_MODULE_PATH";
+
+ // 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;
+
+ private Shell shell;
+
+ //private IStructuredSelection currentSelection;
+
+ private Resource selectedModel;
+
+ GraphExplorerComposite modelExplorer;
+
+ private boolean selectionMade = false;
+
+ /**
+ * Creates a new project creation wizard page.
+ *
+ */
+ public WizardModulesImportPage() {
+ this("wizardModulesImportPage", null, null); //$NON-NLS-1$
+ }
+
+ /**
+ * Create a new instance of the receiver.
+ *
+ * @param pageName
+ */
+ public WizardModulesImportPage(String pageName) {
+ this(pageName,null, null);
+ }
+
+ /**
+ * More (many more) parameters.
+ *
+ * @param pageName
+ * @param initialPath
+ * @param currentSelection
+ * @since 3.5
+ */
+ public WizardModulesImportPage(String pageName,String initialPath,
+ IStructuredSelection currentSelection) {
+ super(pageName);
+ setPageComplete(false);
+ //this.currentSelection = currentSelection;
+ setTitle("Import Module");
+ setDescription("Choose the Module file and the import location, 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);
+
+ createTree(workArea);
+ }
+
+ private void createProjectsRoot(Composite workArea) {
+
+ // set label for field
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select Module 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));
+
+ // module 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();
+ }
+ });
+
+ }
+
+ private void createTree(Composite workArea){
+
+ //set label for tree
+ Label title = new Label(workArea, SWT.NONE);
+ title.setText("Select import location:");
+
+ try {
+ Resource input = SimanticsUI.getSession().syncRequest(new Read<Resource>() {
+
+ @Override
+ public Resource perform(ReadGraph graph)
+ throws DatabaseException {
+ Resource model = SimanticsUI.getProject().get();
+ return model;
+ }
+
+ });
+
+ modelExplorer = new GraphExplorerComposite(ArrayMap.keys(
+ "displaySelectors", "displayFilter").values(false, false), null, workArea, SWT.BORDER | SWT.SINGLE);
+
+ modelExplorer
+ .setBrowseContexts(SysdynResource.URIs.ImportModuleTree);
+
+ modelExplorer.finish();
+
+ modelExplorer.setInput(null, input);
+
+ GridDataFactory.fillDefaults().grab(true, true).applyTo(
+ modelExplorer);
+
+ ((Tree)modelExplorer.getExplorer().getControl()).addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ selectionMade = true;
+ validatePage();
+ }
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ selectionMade = true;
+ validatePage();
+ }
+ });
+
+
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ //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 = {"*.sysdynModule; *.tg", "*.*"};
+ dialog.setFilterExtensions(ext);
+
+ dialog.setText("Import Module");
+
+ 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();
+ }
+ }
+
+ //Get selection from the tree
+ @SuppressWarnings("unchecked")
+ public static <T> T getExplorerResource(GraphExplorerComposite explorer,
+ Class<T> clazz) {
+
+ if(explorer == null)
+ return null;
+ ISelection selection = ((ISelectionProvider) explorer
+ .getAdapter(ISelectionProvider.class)).getSelection();
+ if (selection == null)
+ return null;
+ IStructuredSelection iss = (IStructuredSelection) selection;
+ AdaptableHintContext inc = (AdaptableHintContext) iss.getFirstElement();
+ if (inc == null)
+ return null;
+ final T resource = (T) inc.getAdapter(clazz);
+
+ return resource;
+ }
+
+ //Create project after finish is pressed.
+ public boolean createProjects() {
+
+ String selected = previouslyBrowsedFile;
+ if(selected == null){
+ setErrorMessage("Error when retrieving resource");
+ return false;
+ }
+
+ selectedModel= getExplorerResource(modelExplorer, Resource.class);
+ if(selectedModel == null){
+ setErrorMessage("No file selected");
+ return false;
+ }
+
+ IStatus status = ImportUtilsUI.importModuleFile(selectedModel, selected, null);
+
+ /*
+ TransferableGraph1 tg = null;
+ try {
+ tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));
+ } catch (RuntimeBindingConstructionException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ setErrorMessage("The imported file is not of type: Module Type");
+ return false;
+ }
+ if(tg == null){
+ setErrorMessage("The imported file is not of type: Module Type");
+ return false;
+ }
+
+
+ DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(selectedModel);
+ try {
+ DefaultPasteHandler.defaultExecute(tg, selectedModel, ia);
+ } catch (MissingDependencyException e) {
+ e.printStackTrace();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ final Resource root = ia.getRoot();
+
+ try {
+ SimanticsUI.getSession().syncRequest(new WriteRequest() {
+
+ @Override
+ public void perform(WriteGraph graph) throws DatabaseException {
+ if(!graph.isInheritedFrom(root, SysdynResource.getInstance(graph).Module)) {
+ 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;
+ }
+ }
+ });
+ } catch (DatabaseException e) {
+ e.printStackTrace();
+ }
+
+ if (!error.isEmpty()){
+ setErrorMessage("The imported file is not of type: Module Type (" + error +")");
+ error = "";
+ return false;
+ }
+ */
+ if(status == null || !status.equals(Status.OK_STATUS)) {
+ setErrorMessage(status.getMessage());
+ return false;
+ }
+
+ return true;
+ }
+
+ void validatePage() {
+
+ if (previouslyBrowsedFile.isEmpty() || selectionMade == false){
+ setPageComplete(false);
+ return;
+ }
+
+ setErrorMessage(null);
+ setPageComplete(true);
+
+ }
+
}
\ No newline at end of file