]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.browsing.ui.swt/src/org/simantics/browsing/ui/swt/widgets/GraphExplorerComposite.java
Improvements to modelled SWT documents
[simantics/platform.git] / bundles / org.simantics.browsing.ui.swt / src / org / simantics / browsing / ui / swt / widgets / GraphExplorerComposite.java
index 3ee82ae3b319b944c25b29337d68a27da05d7489..d27eeaa79244a5785070cbb0da57b6bebe52ecda 100644 (file)
@@ -1,5 +1,5 @@
 /*******************************************************************************
- * Copyright (c) 2007, 2012 Association for Decentralized Information Management
+ * Copyright (c) 2007, 2018 Association for Decentralized Information Management
  * in Industry THTH ry.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
@@ -16,10 +16,9 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
-import java.util.function.Consumer;
+import java.util.function.BiFunction;
 
 import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.Platform;
 import org.eclipse.jface.action.IMenuManager;
 import org.eclipse.jface.layout.GridDataFactory;
 import org.eclipse.jface.layout.GridLayoutFactory;
@@ -44,11 +43,11 @@ import org.eclipse.swt.widgets.Control;
 import org.eclipse.swt.widgets.Event;
 import org.eclipse.swt.widgets.Listener;
 import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
 import org.eclipse.swt.widgets.TreeItem;
 import org.eclipse.ui.ISelectionListener;
 import org.eclipse.ui.IWorkbenchSite;
 import org.eclipse.ui.contexts.IContextService;
+import org.simantics.Simantics;
 import org.simantics.browsing.ui.BuiltinKeys;
 import org.simantics.browsing.ui.Column;
 import org.simantics.browsing.ui.ExplorerState;
@@ -56,6 +55,7 @@ import org.simantics.browsing.ui.GraphExplorer;
 import org.simantics.browsing.ui.GraphExplorer.TransientExplorerState;
 import org.simantics.browsing.ui.NodeContext;
 import org.simantics.browsing.ui.StatePersistor;
+import org.simantics.browsing.ui.common.AdaptableHintContext;
 import org.simantics.browsing.ui.common.ColumnKeys;
 import org.simantics.browsing.ui.common.EvaluatorData;
 import org.simantics.browsing.ui.common.EvaluatorDataImpl;
@@ -69,6 +69,7 @@ import org.simantics.browsing.ui.common.processors.LabelerFactoryResolver;
 import org.simantics.browsing.ui.common.processors.UserSelectedComparableFactoryQueryProcessor;
 import org.simantics.browsing.ui.common.processors.UserSelectedViewpointFactoryQueryProcessor;
 import org.simantics.browsing.ui.common.processors.ViewpointFactoryResolver;
+import org.simantics.browsing.ui.common.state.ExplorerStates;
 import org.simantics.browsing.ui.common.views.FilterAreaSource;
 import org.simantics.browsing.ui.common.views.IFilterArea;
 import org.simantics.browsing.ui.common.views.IFilterAreaProvider;
@@ -80,8 +81,6 @@ import org.simantics.browsing.ui.graph.impl.RelatedObjectsQueryProcessor;
 import org.simantics.browsing.ui.graph.impl.SessionContextInputSource;
 import org.simantics.browsing.ui.model.browsecontexts.BrowseContext;
 import org.simantics.browsing.ui.model.nodetypes.NodeType;
-import org.simantics.browsing.ui.swt.Activator;
-import org.simantics.browsing.ui.swt.AdaptableHintContext;
 import org.simantics.browsing.ui.swt.ComparatorSelector;
 import org.simantics.browsing.ui.swt.ContextMenuInitializer;
 import org.simantics.browsing.ui.swt.DefaultExplorerSelectionListener;
@@ -102,12 +101,11 @@ import org.simantics.db.AsyncReadGraph;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
 import org.simantics.db.Session;
-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.request.PossibleVariable;
+import org.simantics.db.layer0.request.PossibleVariableRepresents;
 import org.simantics.db.layer0.variable.Variable;
-import org.simantics.db.layer0.variable.Variables;
 import org.simantics.db.management.ISessionContext;
 import org.simantics.db.management.ISessionContextChangedListener;
 import org.simantics.db.management.ISessionContextProvider;
@@ -126,7 +124,6 @@ import org.simantics.ui.selection.WorkbenchSelectionContentType;
 import org.simantics.ui.selection.WorkbenchSelectionElement;
 import org.simantics.ui.selection.WorkbenchSelectionUtils;
 import org.simantics.utils.ObjectUtils;
-import org.simantics.utils.datastructures.BinaryFunction;
 import org.simantics.utils.datastructures.Function;
 import org.simantics.utils.datastructures.disposable.DisposeState;
 import org.simantics.utils.datastructures.hints.HintListenerAdapter;
@@ -135,10 +132,15 @@ import org.simantics.utils.datastructures.hints.IHintContext.Key;
 import org.simantics.utils.datastructures.hints.IHintListener;
 import org.simantics.utils.datastructures.hints.IHintObservable;
 import org.simantics.utils.datastructures.hints.IHintTracker;
+import org.simantics.utils.ui.SWTUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 public class GraphExplorerComposite extends Composite implements Widget, IAdaptable {
 
+    private static final Logger LOGGER = LoggerFactory.getLogger(GraphExplorerComposite.class);
+
     protected UserSelectedComparableFactoryQueryProcessor userSelectedComparableFactoryQueryProcessor;
     protected UserSelectedViewpointFactoryQueryProcessor  userSelectedViewpointFactoryQueryProcessor;
     protected FilterSelectionRequestQueryProcessor        filterSelectionRequestQueryProcessor;
@@ -248,39 +250,41 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
         @SuppressWarnings("unchecked")
         @Override
         public <T> T getContent(WorkbenchSelectionContentType<T> contentType) {
-
-            if(wse != null) {
+            if (wse != null) {
                 T result = wse.getContent(contentType);
-                if(result != null) return result;
+                if (result != null)
+                    return result;
             }
-            
-            if(contentType instanceof AnyResource) return (T)resource;
-            else if(contentType instanceof AnyVariable) {
-                AnyVariable type = (AnyVariable)contentType;
+
+            if (contentType instanceof AnyResource) {
+                if (resource != null)
+                    return (T) resource;
+                if (variable == null)
+                    return null;
+                try {
+                    return (T) ((AnyResource) contentType).processor.syncRequest(new PossibleVariableRepresents(variable));
+                } catch (DatabaseException e) {
+                    LOGGER.error("Unexpected error occurred while resolving Resource from Variable " + variable, e);
+                }
+            }
+            else if (contentType instanceof AnyVariable) {
+                if (variable != null)
+                    return (T) variable;
+                if (resource == null)
+                    return null;
                 try {
-                       
-                       if(variable != null) return (T)variable;
-                       
-                       if(resource == null) return null;
-                       
-                    return (T) type.processor.sync(new ResourceRead<Variable>(resource) {
-                        @Override
-                        public Variable perform(ReadGraph graph) throws DatabaseException {
-                            return Variables.getPossibleVariable(graph, resource);
-                        }
-                        
-                    });
+                    return (T) ((AnyVariable) contentType).processor.syncRequest(new PossibleVariable(resource));
                 } catch (DatabaseException e) {
-                    Logger.defaultLogError(e);
+                    LOGGER.error("Unexpected error occurred while resolving Variable from Resource " + resource, e);
                 }
             } else if (contentType instanceof ExplorerInputContentType) {
-               return (T)input;
+                return (T) input;
             } else if (contentType instanceof ExplorerColumnContentType) {
-               return (T)explorerState.getActiveColumn();
+                return (T) explorerState.getActiveColumn();
             }
             return null;
         }
-        
+
         @SuppressWarnings("rawtypes")
         @Override
         public Object getAdapter(Class adapter) {
@@ -297,12 +301,12 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
         }
 
     }
-    private BinaryFunction<Object[], GraphExplorer, Object[]> selectionTransformation = new BinaryFunction<Object[], GraphExplorer, Object[]>() {
+    private BiFunction<GraphExplorer, Object[], Object[]> selectionTransformation = new BiFunction<GraphExplorer, Object[], Object[]>() {
 
        private Key[] KEYS = new Key[] { SelectionHints.KEY_MAIN };
        
         @Override
-        public Object[] call(GraphExplorer explorer, Object[] objects) {
+        public Object[] apply(GraphExplorer explorer, Object[] objects) {
             Object[] result = new Object[objects.length];
             for (int i = 0; i < objects.length; i++) {
                SelectionElement context = new SelectionElement(explorer, KEYS, objects[i]);
@@ -404,7 +408,7 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
         if(site != null)
             return SimanticsUI.getSessionContextProvider(site.getWorkbenchWindow());
         else
-            return SimanticsUI.getSessionContextProvider();
+            return Simantics.getSessionContextProvider();
     }
 
     public GraphExplorer getExplorer() {
@@ -423,6 +427,10 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
         ((Control)explorer.getControl()).addListener(eventType, listener);
     }
 
+    public void removeListenerFromControl(int eventType, Listener listener) {
+        ((Control)explorer.getControl()).removeListener(eventType, listener);
+    }
+
     public void finish() {
         created = true;
         createControls(site);
@@ -529,7 +537,7 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
         //tree.getTree().setLayout(new FillLayout()
         //this.setLayout(LayoutUtils.createNoBorderGridLayout(2, false));
 
-        DropTarget target = new DropTarget(control, DND.DROP_COPY | DND.DROP_LINK);
+        DropTarget target = new DropTarget(control, DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK | DND.DROP_DEFAULT);
         target.setTransfer(getAcceptedDataTypes());
         if (control instanceof Tree)  {
         target.addDropListener(new DropTargetListener() {
@@ -694,7 +702,7 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
     }
 
     protected Transfer[] getAcceptedDataTypes() {
-        return new Transfer[] {  LocalObjectTransfer.getTransfer(), FileTransfer.getInstance() };
+        return new Transfer[] { LocalObjectTransfer.getTransfer(), FileTransfer.getInstance(), TextTransfer.getInstance() };
     }
 
     protected void handleDrop(Object data, NodeContext target) {
@@ -723,7 +731,7 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
                                                        event.data = WorkbenchSelectionUtils.getPossibleJSON(selectionProvider.getSelection());
                                                } catch (DatabaseException e) {
                                                        event.data = "{ type:\"Exception\" }";
-                                                       Logger.defaultLogError(e);
+                                                       LOGGER.error("Failed to get current selection as JSON.", e);
                                                }
                                        } else if (LocalObjectTransfer.getTransfer().isSupportedType(event.dataType)) {
                                                ls.dragSetData(event);
@@ -863,7 +871,7 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
        this.filterAreaSource = provider;
     }
 
-    public void setSelectionTransformation(BinaryFunction<Object[], GraphExplorer, Object[]> transformation) {
+    public void setSelectionTransformation(BiFunction<GraphExplorer, Object[], Object[]> transformation) {
         this.selectionTransformation = transformation;
         if(explorer != null) explorer.setSelectionTransformation(transformation);
     }
@@ -1188,52 +1196,48 @@ public class GraphExplorerComposite extends Composite implements Widget, IAdapta
     }
 
     private int getColumnWidth(Column column, ExplorerState state) {
-       // Get saved width from the persistor if there is one.
+        // Get saved width from the persistor if there is one.
         if (state != null && state.columnWidths != null) {
-               Integer width = state.columnWidths.get(column.getLabel());
-               if (width != null)
-                       return width;
+            Integer width = state.columnWidths.get(column.getLabel());
+            if (width != null)
+                return width;
         }
         return column.getWidth();
     }
-    
-    public void setColumns(Column[] columns) {
 
-        explorer.setColumns(columns, new Consumer<Map<Column, Object>>() {
-
-            @Override
-            public void accept(Map<Column, Object> objects) {
-               ExplorerState state = null;
-               if (persistor != null) {
-                       state = persistor.deserialize(
-                               Platform.getStateLocation(Activator.getDefault().getBundle()).toFile(),
-                               explorer.getRoot());
-               }
-
-                for(Map.Entry<Column, Object> entry : objects.entrySet()) {
-                    Column column = entry.getKey();
-                    TreeColumn treeColumn = (TreeColumn)entry.getValue();
-
-                    if (column.getWidth() < 0) {
-                        throw new IllegalArgumentException("Column minimum width cannot be < 0, got " + column.getWidth());
-                    }
-
-                    int width = getColumnWidth(column, state);
-                    if(column.hasGrab()) {
-                       
-                        ad.setColumnData(treeColumn, new ColumnWeightData(column.getWeight(), width));
-
-                    } else {
-
-                        ad.setColumnData(treeColumn, new ColumnWeightData(0, width));
-
-                    }
-
-                }
-            }
+    protected void restoreColumnSizes(Map<Column, Object> columns) {
+        if (persistor != null) {
+            setColumnData(columns, null);
+            ExplorerStates.scheduleRead(explorer.getRoot(), persistor).thenAccept(state -> {
+                SWTUtils.asyncExec(GraphExplorerComposite.this, () -> {
+                    if (explorerComposite.isDisposed())
+                        setColumnData(columns, state);
+                });
+            });
+        } else {
+            setColumnData(columns, null);
+        }
+    }
 
+    protected void setColumnData(Map<Column, Object> columns, ExplorerState state) {
+        columns.forEach((column, widget) -> {
+            org.eclipse.swt.widgets.Widget columnWidget = (org.eclipse.swt.widgets.Widget) widget;
+            ad.setColumnData(columnWidget,
+                    new ColumnWeightData(
+                            column.hasGrab() ? column.getWeight() : 0,
+                            getColumnWidth(column, state)));
         });
+    }
 
+    public void setColumns(Column[] columns) {
+        // ColumnWeightData does not support column weight/width < 0
+        for (Column column : columns) {
+            if (column.getWeight() < 0)
+                throw new IllegalArgumentException("Column weight must be >= 0, got " + column.getWeight() + " for " + column);
+            if (column.getWidth() < 0)
+                throw new IllegalArgumentException("Column minimum width must be >= 0, got " + column.getWidth() + " for " + column);
+        }
+        explorer.setColumns(columns, this::restoreColumnSizes);
     }
 
     @Override