From a9c56cdf008b5f9a9f2a4e50568340ca26f2cd1a Mon Sep 17 00:00:00 2001 From: Miro Richard Eklund Date: Tue, 17 Jul 2018 15:16:33 +0300 Subject: [PATCH] swt.AdaptableHintContext -> common.AdaptableHintContext gitlab #10 Change-Id: I34f4001944568ae4d7ff675d1c9f57dbc759687e --- .../sysdyn/ui/browser/SysdynBrowser.java | 356 +++---- .../sysdyn/ui/properties/ArrayIndexesTab.java | 990 +++++++++--------- .../ui/properties/ExternalFilesTab.java | 498 ++++----- .../SharedFunctionLibrariesTab.java | 508 ++++----- .../functions/WizardFunctionsExportPage.java | 686 ++++++------ .../functions/WizardFunctionsImportPage.java | 880 ++++++++-------- .../models/WizardModelsExportPage.java | 588 +++++------ .../modules/WizardModulesExportPage.java | 922 ++++++++-------- .../modules/WizardModulesImportPage.java | 728 ++++++------- 9 files changed, 3078 insertions(+), 3078 deletions(-) diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynBrowser.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynBrowser.java index 8cda4726..ede50aed 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynBrowser.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/browser/SysdynBrowser.java @@ -1,178 +1,178 @@ -/******************************************************************************* - * 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.swt.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 browseContexts = new HashSet(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 selectionTransformation = new BinaryFunction() { - - - /* - 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 getContent(WorkbenchSelectionContentType 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(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 vn = (VariableNode) 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 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; - } - -} +/******************************************************************************* + * 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 browseContexts = new HashSet(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 selectionTransformation = new BinaryFunction() { + + + /* + 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 getContent(WorkbenchSelectionContentType 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(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 vn = (VariableNode) 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 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; + } + +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayIndexesTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayIndexesTab.java index 0a2e68ec..80c57e52 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayIndexesTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ArrayIndexesTab.java @@ -1,495 +1,495 @@ -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.swt.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(context) { - - List 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 filtered = new ArrayList(); - 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() { - - @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(context) { - - List 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 enumerations = ListUtils.toList(graph, arrayIndexes); - List toBeMoved = new ArrayList(); - 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 list = (List) object2; - Set selection = new HashSet(); - 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(context) { - - List 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 enumerations = ListUtils.toList(graph, arrayIndexes); - List toBeMoved = new ArrayList(); - 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 list = (List) object2; - Set selection = new HashSet(); - 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(context) { - - List 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 enumerations = ListUtils.toList(graph, arrayIndexes); - List toBeRemoved = new ArrayList(); - 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 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 getSelectedResources(GraphExplorerComposite explorer) { - List result = new ArrayList(); - - ISelection selection = ((ISelectionProvider) explorer - .getAdapter(ISelectionProvider.class)).getSelection(); - if (selection == null) - return result; - IStructuredSelection iss = (IStructuredSelection) selection; - @SuppressWarnings("unchecked") - List selections = iss.toList(); - for(AdaptableHintContext ahc : selections) { - Resource resource = (Resource) ahc.getAdapter(Resource.class); - result.add(resource); - } - return result; - } - - private List getSelectedIndexes(final GraphExplorerComposite explorer) { - final List result = new ArrayList(); - - 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(); - } - } - } - } -} +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(context) { + + List 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 filtered = new ArrayList(); + 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() { + + @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(context) { + + List 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 enumerations = ListUtils.toList(graph, arrayIndexes); + List toBeMoved = new ArrayList(); + 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 list = (List) object2; + Set selection = new HashSet(); + 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(context) { + + List 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 enumerations = ListUtils.toList(graph, arrayIndexes); + List toBeMoved = new ArrayList(); + 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 list = (List) object2; + Set selection = new HashSet(); + 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(context) { + + List 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 enumerations = ListUtils.toList(graph, arrayIndexes); + List toBeRemoved = new ArrayList(); + 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 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 getSelectedResources(GraphExplorerComposite explorer) { + List result = new ArrayList(); + + ISelection selection = ((ISelectionProvider) explorer + .getAdapter(ISelectionProvider.class)).getSelection(); + if (selection == null) + return result; + IStructuredSelection iss = (IStructuredSelection) selection; + @SuppressWarnings("unchecked") + List selections = iss.toList(); + for(AdaptableHintContext ahc : selections) { + Resource resource = (Resource) ahc.getAdapter(Resource.class); + result.add(resource); + } + return result; + } + + private List getSelectedIndexes(final GraphExplorerComposite explorer) { + final List result = new ArrayList(); + + 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(); + } + } + } + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExternalFilesTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExternalFilesTab.java index fb32aa51..ca286119 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExternalFilesTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ExternalFilesTab.java @@ -1,249 +1,249 @@ -/******************************************************************************* - * 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.swt.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(context) { - - private Pair 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(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 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(context) { - - private int delete; - private List 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 getSelectedResources(GraphExplorerComposite explorer) { - List result = new ArrayList(); - ISelection selection = ((ISelectionProvider) explorer - .getAdapter(ISelectionProvider.class)).getSelection(); - if (selection == null) - return result; - IStructuredSelection iss = (IStructuredSelection) selection; - @SuppressWarnings("unchecked") - List 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 selections = iss.toList(); - - boolean enabled = false; - if (!selections.isEmpty()) - enabled = true; - removeButton.getControl().setEnabled(enabled); - exportButton.getControl().setEnabled(enabled); - } - }; -} +/******************************************************************************* + * 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(context) { + + private Pair 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(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 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(context) { + + private int delete; + private List 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 getSelectedResources(GraphExplorerComposite explorer) { + List result = new ArrayList(); + ISelection selection = ((ISelectionProvider) explorer + .getAdapter(ISelectionProvider.class)).getSelection(); + if (selection == null) + return result; + IStructuredSelection iss = (IStructuredSelection) selection; + @SuppressWarnings("unchecked") + List 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 selections = iss.toList(); + + boolean enabled = false; + if (!selections.isEmpty()) + enabled = true; + removeButton.getControl().setEnabled(enabled); + exportButton.getControl().setEnabled(enabled); + } + }; +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java index a130a91c..7fec15f7 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/SharedFunctionLibrariesTab.java @@ -1,254 +1,254 @@ -/******************************************************************************* - * 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.swt.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(context) { - - List 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(context) { - - List 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 getSelectedResources(GraphExplorerComposite explorer) { - List result = new ArrayList(); - - ISelection selection = ((ISelectionProvider) explorer - .getAdapter(ISelectionProvider.class)).getSelection(); - if (selection == null) - return result; - IStructuredSelection iss = (IStructuredSelection) selection; - @SuppressWarnings("unchecked") - List 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); - } -} - +/******************************************************************************* + * 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(context) { + + List 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(context) { + + List 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 getSelectedResources(GraphExplorerComposite explorer) { + List result = new ArrayList(); + + ISelection selection = ((ISelectionProvider) explorer + .getAdapter(ISelectionProvider.class)).getSelection(); + if (selection == null) + return result; + IStructuredSelection iss = (IStructuredSelection) selection; + @SuppressWarnings("unchecked") + List 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); + } +} + diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java index 372fe621..f007253e 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsExportPage.java @@ -1,344 +1,344 @@ -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.swt.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 getExplorerResource(GraphExplorerComposite explorer, - Class 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() { - - @Override - public String perform(ReadGraph graph) throws DatabaseException { - if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf)) - return null; - Layer0 l0 = Layer0.getInstance(graph); - String name = graph.syncRequest(new PossibleRelatedValue(functionLibrary, l0.HasName, Bindings.STRING )); - return name; - - } - - }); - } catch (DatabaseException 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() { - - @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); - - } - +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 getExplorerResource(GraphExplorerComposite explorer, + Class 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() { + + @Override + public String perform(ReadGraph graph) throws DatabaseException { + if (!graph.hasStatement(functionLibrary, Layer0.getInstance(graph).PartOf)) + return null; + Layer0 l0 = Layer0.getInstance(graph); + String name = graph.syncRequest(new PossibleRelatedValue(functionLibrary, l0.HasName, Bindings.STRING )); + return name; + + } + + }); + } catch (DatabaseException 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() { + + @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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java index 702a96cd..68cd42df 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java @@ -1,441 +1,441 @@ -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.swt.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() { - - @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 getExplorerResource(GraphExplorerComposite explorer, - Class 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() { - - @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); - - } - +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() { + + @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 getExplorerResource(GraphExplorerComposite explorer, + Class 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() { + + @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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java index f53eb7ec..0dab6289 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsExportPage.java @@ -1,294 +1,294 @@ -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.swt.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 getExplorerResource(GraphExplorerComposite explorer, - Class 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.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 getExplorerResource(GraphExplorerComposite explorer, + Class 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); + + } +} diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java index e57a8210..69ec0fb6 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesExportPage.java @@ -1,462 +1,462 @@ -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.swt.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 getExplorerResource(GraphExplorerComposite explorer, - Class 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() { - - @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 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> 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 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 replacement : replacements) - graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second); - } - } - - class ContainsDependenciesException extends DatabaseException { - private static final long serialVersionUID = -1533706136673146020L; - - private Collection dependencies; - - ContainsDependenciesException(Collection dependencies) { - this.dependencies = dependencies; - } - - public Collection 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() { - - @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); - - } - - - +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 getExplorerResource(GraphExplorerComposite explorer, + Class 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() { + + @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 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> 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 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 replacement : replacements) + graph.claim(replacement.first, sr.Redeclaration_replacedEnumeration_Inverse, replacement.second); + } + } + + class ContainsDependenciesException extends DatabaseException { + private static final long serialVersionUID = -1533706136673146020L; + + private Collection dependencies; + + ContainsDependenciesException(Collection dependencies) { + this.dependencies = dependencies; + } + + public Collection 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() { + + @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 diff --git a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java index 415d02c3..fa92bae2 100644 --- a/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java +++ b/bundles/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java @@ -1,365 +1,365 @@ -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.swt.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() { - - @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 getExplorerResource(GraphExplorerComposite explorer, - Class 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); - - } - +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() { + + @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 getExplorerResource(GraphExplorerComposite explorer, + Class 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 -- 2.47.1