]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/modelBrowser/handlers/StandardCopyHandler.java
Fixed StandardCopyHandler SWT threading regression
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / modelBrowser / handlers / StandardCopyHandler.java
index 3fffbbce52d116d424ccf8d79c76f7a724514e99..002a31381439d3df4320a22dd79b28d19c012674 100644 (file)
-/*******************************************************************************\r
- * Copyright (c) 2007 VTT Technical Research Centre of Finland and others.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- *     VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.modeling.ui.modelBrowser.handlers;\r
-\r
-import gnu.trove.set.hash.THashSet;\r
-\r
-import java.util.Collections;\r
-import java.util.List;\r
-import java.util.Set;\r
-\r
-import org.eclipse.core.commands.AbstractHandler;\r
-import org.eclipse.core.commands.ExecutionEvent;\r
-import org.eclipse.core.commands.ExecutionException;\r
-import org.eclipse.jface.action.IStatusLineManager;\r
-import org.eclipse.jface.viewers.ISelection;\r
-import org.eclipse.jface.viewers.StructuredSelection;\r
-import org.eclipse.swt.dnd.Clipboard;\r
-import org.eclipse.swt.dnd.TextTransfer;\r
-import org.eclipse.swt.dnd.Transfer;\r
-import org.eclipse.swt.widgets.Control;\r
-import org.eclipse.swt.widgets.Display;\r
-import org.eclipse.swt.widgets.Shell;\r
-import org.eclipse.swt.widgets.Tree;\r
-import org.eclipse.swt.widgets.TreeItem;\r
-import org.eclipse.ui.PlatformUI;\r
-import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.Simantics;\r
-import org.simantics.browsing.ui.BuiltinKeys;\r
-import org.simantics.browsing.ui.GraphExplorer;\r
-import org.simantics.browsing.ui.NodeContext;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.common.utils.Logger;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.SelectionHints;\r
-import org.simantics.db.layer0.adapter.CopyHandler;\r
-import org.simantics.db.layer0.util.ClipboardUtils;\r
-import org.simantics.db.layer0.util.SimanticsClipboardImpl;\r
-import org.simantics.db.layer0.variable.Variable;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.datastructures.hints.IHintContext;\r
-import org.simantics.utils.ui.ISelectionUtils;\r
-import org.simantics.utils.ui.SWTUtils;\r
-import org.simantics.utils.ui.SWTUtils.ControlFilter;\r
-import org.simantics.utils.ui.workbench.WorkbenchUtils;\r
-\r
-public class StandardCopyHandler extends AbstractHandler {\r
-\r
-    private static IStatusLineManager status;\r
-\r
-    private static List<Variable> getVariables(ISelection selection) {\r
-        NodeContext context = ISelectionUtils.getSinglePossibleKey(selection, SelectionHints.KEY_MAIN, NodeContext.class);\r
-        if(context == null) return Collections.emptyList();\r
-        Object input = context.getConstant(BuiltinKeys.INPUT);\r
-        IHintContext hints = input instanceof IHintContext ? (IHintContext) input : null;\r
-        if(hints == null) return Collections.emptyList();\r
-        Variable var = hints.getHint(SelectionHints.KEY_SELECTION_PROPERTY);\r
-        if(var == null) return Collections.emptyList();\r
-        else return Collections.singletonList(var);\r
-    }\r
-\r
-    private boolean copyText(ISelection selection) {\r
-       if(selection instanceof StructuredSelection) {\r
-               StructuredSelection sel = (StructuredSelection)selection;\r
-               if(sel.size() == 1) {\r
-                       Object element = sel.getFirstElement();\r
-                       if(element instanceof String) {\r
-                               setSystemClipboardText((String) element);\r
-                       }\r
-               }\r
-       }\r
-       return false;\r
-    }\r
-    \r
-    @Override\r
-    public Object execute(ExecutionEvent event) throws ExecutionException {\r
-       \r
-        status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );\r
-        ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();\r
-        \r
-        // If the selection is plain text copy it into system clipboard and be happy\r
-        if(copyText(selection)) return null;\r
-\r
-        formatSelectionToClipboardText(event);\r
-\r
-        final Resource[] rs = ResourceAdaptionUtils.toResources(selection);\r
-        copyResourcesToClipboard(rs, selection);\r
-        return null;\r
-    }\r
-    \r
-    public static String copyResourcesToClipboard(final Resource[] rs, ISelection selection) {\r
-       \r
-        if(rs == null || rs.length == 0) {\r
-            // This support was added for copying of properties (variables)\r
-            final List<Variable> variables = getVariables(selection);\r
-            if(!variables.isEmpty()) {\r
-                final SimanticsClipboardImpl builder = new SimanticsClipboardImpl();\r
-                for(Variable var : variables) {\r
-                    builder.addContent(Collections.singleton(ClipboardUtils.createVariable(Simantics.getSession(), var)));\r
-                }\r
-                Simantics.setClipboard(builder);\r
-                setCopyMessage(builder.getContents().size(), "variable");\r
-                return null;\r
-            }\r
-            setCopyMessage(0, "");\r
-            return null;\r
-        }\r
-\r
-        try {\r
-            final SimanticsClipboardImpl builder = new SimanticsClipboardImpl();\r
-            Simantics.getSession().syncRequest(new ReadRequest() {\r
-                @Override\r
-                public void run(ReadGraph graph) throws DatabaseException {\r
-                    for (Resource r : rs) {\r
-                        CopyHandler handler = graph.adapt(r, CopyHandler.class);\r
-                        handler.copyToClipboard(graph, builder);\r
-                    }\r
-                }\r
-            });\r
-            Simantics.setClipboard(builder);\r
-            setCopyMessage(builder.getContents().size(), "resource");\r
-        } catch (DatabaseException e) {\r
-            Logger.defaultLogError(e);\r
-        }\r
-\r
-        return null;\r
-    }\r
-\r
-    private static void setCopyMessage(int count, String elementName) {\r
-        if (count > 1)\r
-            setStatus("Copied " + count + " " + elementName + "s to clipboard");\r
-        else if (count == 1)\r
-            setStatus("Copied " + elementName + " to clipboard");\r
-        else\r
-            setStatus("Nothing to copy.");\r
-    }\r
-\r
-    private static void setStatus(String message) {\r
-        if (status != null)\r
-            status.setMessage(message);\r
-    }\r
-\r
-    private boolean formatSelectionToClipboardText(ExecutionEvent event) {\r
-        Shell shell = HandlerUtil.getActiveShell(event);\r
-        Tree tree = shell == null ? null : tryGetExplorer(shell.getDisplay().getFocusControl());\r
-        if (tree == null)\r
-            return false;\r
-\r
-        TreeItem[] selection = tree.getSelection();\r
-        if (selection.length == 0)\r
-            return false;\r
-\r
-        StringBuilder sb = format(selection, new StringBuilder());\r
-        if (sb.length() > 0) {\r
-            setSystemClipboardText(sb.toString());\r
-            return true;\r
-        }\r
-        return false;\r
-    }\r
-\r
-    private static StringBuilder format(TreeItem[] selection, StringBuilder sb) {\r
-        Set<TreeItem> items = new THashSet<TreeItem>(selection.length);\r
-        for (TreeItem item : selection)\r
-            items.add(item);\r
-        for (TreeItem item : selection) {\r
-            int cc = item.getParent().getColumnCount();\r
-            int indent = indentLevel(item, items);\r
-            for (int i = 0; i < indent; ++i)\r
-                sb.append('\t');\r
-            boolean first = true;\r
-            for (int c = 0; c < cc; ++c) {\r
-                String ct = item.getText(c);\r
-                if (!first) {\r
-                    sb.append('\t');\r
-                }\r
-                first = false;\r
-                sb.append(ct);\r
-            }\r
-            sb.append('\n');\r
-        }\r
-        return sb;\r
-    }\r
-\r
-    private static int indentLevel(TreeItem item, Set<TreeItem> items) {\r
-        TreeItem p = item.getParentItem();\r
-        for (int i = 1; ; p = p.getParentItem()) {\r
-            if (p == null)\r
-                return 0;\r
-            if (items.contains(p))\r
-                return i;\r
-        }\r
-    }\r
-\r
-    private static Tree tryGetExplorer(Control control) {\r
-        return SWTUtils.tryGetObject(control, new ControlFilter<Tree>() {\r
-            @Override\r
-            public Tree accept(Control control) {\r
-                if (!control.isDisposed()\r
-                        && control instanceof Tree\r
-                        && control.getData(GraphExplorer.KEY_GRAPH_EXPLORER) != null)\r
-                    return (Tree) control;\r
-                return null;\r
-            }\r
-        });\r
-    }\r
-\r
-    private static void setSystemClipboardText(String text) {\r
-        Clipboard clipboard = new Clipboard(Display.getCurrent());\r
-        clipboard.setContents(new Object[]{ text }, new Transfer[] { TextTransfer.getInstance() });\r
-        clipboard.dispose();\r
-    }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007 VTT Technical Research Centre of Finland and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.modeling.ui.modelBrowser.handlers;
+
+import gnu.trove.set.hash.THashSet;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import org.eclipse.core.commands.AbstractHandler;
+import org.eclipse.core.commands.ExecutionEvent;
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.SubMonitor;
+import org.eclipse.core.runtime.jobs.Job;
+import org.eclipse.jface.action.IStatusLineManager;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.swt.dnd.Clipboard;
+import org.eclipse.swt.dnd.TextTransfer;
+import org.eclipse.swt.dnd.Transfer;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.swt.widgets.Tree;
+import org.eclipse.swt.widgets.TreeItem;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.handlers.HandlerUtil;
+import org.simantics.Simantics;
+import org.simantics.browsing.ui.BuiltinKeys;
+import org.simantics.browsing.ui.GraphExplorer;
+import org.simantics.browsing.ui.NodeContext;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.common.request.ReadRequest;
+import org.simantics.db.common.utils.Logger;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.SelectionHints;
+import org.simantics.db.layer0.adapter.CopyHandler;
+import org.simantics.db.layer0.util.ClipboardUtils;
+import org.simantics.db.layer0.util.SimanticsClipboardImpl;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.datastructures.hints.IHintContext;
+import org.simantics.utils.ui.ISelectionUtils;
+import org.simantics.utils.ui.SWTUtils;
+import org.simantics.utils.ui.SWTUtils.ControlFilter;
+import org.simantics.utils.ui.workbench.WorkbenchUtils;
+
+public class StandardCopyHandler extends AbstractHandler {
+
+    private static IStatusLineManager status;
+
+    private static List<Variable> getVariables(ISelection selection) {
+        NodeContext context = ISelectionUtils.getSinglePossibleKey(selection, SelectionHints.KEY_MAIN, NodeContext.class);
+        if(context == null) return Collections.emptyList();
+        Object input = context.getConstant(BuiltinKeys.INPUT);
+        IHintContext hints = input instanceof IHintContext ? (IHintContext) input : null;
+        if(hints == null) return Collections.emptyList();
+        Variable var = hints.getHint(SelectionHints.KEY_SELECTION_PROPERTY);
+        if(var == null) return Collections.emptyList();
+        else return Collections.singletonList(var);
+    }
+
+    private boolean copyText(ISelection selection) {
+       if(selection instanceof StructuredSelection) {
+               StructuredSelection sel = (StructuredSelection)selection;
+               if(sel.size() == 1) {
+                       Object element = sel.getFirstElement();
+                       if(element instanceof String) {
+                               setSystemClipboardText((String) element);
+                       }
+               }
+       }
+       return false;
+    }
+    
+    @Override
+    public Object execute(ExecutionEvent event) throws ExecutionException {
+       
+        status = WorkbenchUtils.getStatusLine( HandlerUtil.getActiveSite(event) );
+        ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
+        
+        // If the selection is plain text copy it into system clipboard and be happy
+        if(copyText(selection)) return null;
+
+        formatSelectionToClipboardText(event);
+        final Resource[] rs = ResourceAdaptionUtils.toResources(selection);
+        Job job = new Job("Copy resources") {
+            
+            @Override
+            protected IStatus run(IProgressMonitor monitor) {
+                monitor.beginTask("Copy resources to clipboard", 1);
+                copyResourcesToClipboard(rs, selection, SubMonitor.convert(monitor, 1));
+                return null;
+            }
+        };
+        job.setUser(true);
+        job.schedule();
+        
+        return null;
+    }
+    
+    public static String copyResourcesToClipboard(final Resource[] rs, ISelection selection, IProgressMonitor monitor) {
+       
+        if(rs == null || rs.length == 0) {
+            // This support was added for copying of properties (variables)
+            final List<Variable> variables = getVariables(selection);
+            if(!variables.isEmpty()) {
+                final SimanticsClipboardImpl builder = new SimanticsClipboardImpl();
+                for(Variable var : variables) {
+                    builder.addContent(Collections.singleton(ClipboardUtils.createVariable(Simantics.getSession(), var)), monitor);
+                }
+                Simantics.setClipboard(builder);
+                setCopyMessage(builder.getContents().size(), "variable");
+                return null;
+            }
+            setCopyMessage(0, "");
+            return null;
+        }
+
+        try {
+            final SimanticsClipboardImpl builder = new SimanticsClipboardImpl();
+            Simantics.getSession().syncRequest(new ReadRequest() {
+                @Override
+                public void run(ReadGraph graph) throws DatabaseException {
+                    for (Resource r : rs) {
+                        CopyHandler handler = graph.adapt(r, CopyHandler.class);
+                        handler.copyToClipboard(graph, builder, monitor);
+                    }
+                }
+            });
+            Simantics.setClipboard(builder);
+            setCopyMessage(builder.getContents().size(), "resource");
+        } catch (DatabaseException e) {
+            Logger.defaultLogError(e);
+        }
+
+        return null;
+    }
+
+    private static void setCopyMessage(int count, String elementName) {
+        if (count > 1)
+            setStatus("Copied " + count + " " + elementName + "s to clipboard");
+        else if (count == 1)
+            setStatus("Copied " + elementName + " to clipboard");
+        else
+            setStatus("Nothing to copy.");
+    }
+
+    private static void setStatus(String message) {
+        if (status != null) {
+            SWTUtils.asyncExec(
+                    PlatformUI.getWorkbench().getDisplay(),
+                    () -> status.setMessage(message));
+        }
+    }
+
+    private boolean formatSelectionToClipboardText(ExecutionEvent event) {
+        Shell shell = HandlerUtil.getActiveShell(event);
+        Tree tree = shell == null ? null : tryGetExplorer(shell.getDisplay().getFocusControl());
+        if (tree == null)
+            return false;
+
+        TreeItem[] selection = tree.getSelection();
+        if (selection.length == 0)
+            return false;
+
+        StringBuilder sb = format(selection, new StringBuilder());
+        if (sb.length() > 0) {
+            setSystemClipboardText(sb.toString());
+            return true;
+        }
+        return false;
+    }
+
+    private static StringBuilder format(TreeItem[] selection, StringBuilder sb) {
+        Set<TreeItem> items = new THashSet<TreeItem>(selection.length);
+        for (TreeItem item : selection)
+            items.add(item);
+        for (TreeItem item : selection) {
+            int cc = item.getParent().getColumnCount();
+            int indent = indentLevel(item, items);
+            for (int i = 0; i < indent; ++i)
+                sb.append('\t');
+            boolean first = true;
+            for (int c = 0; c < cc; ++c) {
+                String ct = item.getText(c);
+                if (!first) {
+                    sb.append('\t');
+                }
+                first = false;
+                sb.append(ct);
+            }
+            sb.append('\n');
+        }
+        return sb;
+    }
+
+    private static int indentLevel(TreeItem item, Set<TreeItem> items) {
+        TreeItem p = item.getParentItem();
+        for (int i = 1; ; p = p.getParentItem()) {
+            if (p == null)
+                return 0;
+            if (items.contains(p))
+                return i;
+        }
+    }
+
+    private static Tree tryGetExplorer(Control control) {
+        return SWTUtils.tryGetObject(control, new ControlFilter<Tree>() {
+            @Override
+            public Tree accept(Control control) {
+                if (!control.isDisposed()
+                        && control instanceof Tree
+                        && control.getData(GraphExplorer.KEY_GRAPH_EXPLORER) != null)
+                    return (Tree) control;
+                return null;
+            }
+        });
+    }
+
+    private static void setSystemClipboardText(String text) {
+        Clipboard clipboard = new Clipboard(Display.getCurrent());
+        clipboard.setContents(new Object[]{ text }, new Transfer[] { TextTransfer.getInstance() });
+        clipboard.dispose();
+    }
+
+}