]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.debug.ui/src/org/simantics/debug/ui/SearchResourceDialog.java
Re-enabled CTRL+SHIFT+R resource search dialog in org.simantics.debug.ui
[simantics/platform.git] / bundles / org.simantics.debug.ui / src / org / simantics / debug / ui / SearchResourceDialog.java
index 8c88468e4ef424e7b956eb680968543e27c2025e..1ae23d7197c0b61bd5f039611872388f9641a739 100644 (file)
@@ -1,5 +1,5 @@
 /*******************************************************************************\r
- * Copyright (c) 2007, 2013 Association for Decentralized Information Management\r
+ * Copyright (c) 2007, 2016 Association for Decentralized Information Management\r
  * in Industry THTH ry.\r
  * All rights reserved. This program and the accompanying materials\r
  * are made available under the terms of the Eclipse Public License v1.0\r
@@ -17,6 +17,7 @@ import java.util.Collection;
 import java.util.Collections;\r
 import java.util.Comparator;\r
 import java.util.HashSet;\r
+import java.util.List;\r
 import java.util.Map;\r
 import java.util.Set;\r
 import java.util.TreeSet;\r
@@ -27,14 +28,14 @@ import org.eclipse.core.runtime.CoreException;
 import org.eclipse.core.runtime.IProgressMonitor;\r
 import org.eclipse.core.runtime.IStatus;\r
 import org.eclipse.core.runtime.Status;\r
+import org.eclipse.jface.dialogs.IDialogConstants;\r
 import org.eclipse.jface.dialogs.IDialogSettings;\r
 import org.eclipse.jface.resource.JFaceResources;\r
 import org.eclipse.jface.resource.LocalResourceManager;\r
 import org.eclipse.jface.resource.ResourceManager;\r
 import org.eclipse.jface.viewers.IStructuredSelection;\r
 import org.eclipse.jface.viewers.LabelProvider;\r
-import org.eclipse.swt.events.DisposeEvent;\r
-import org.eclipse.swt.events.DisposeListener;\r
+import org.eclipse.jface.viewers.StructuredSelection;\r
 import org.eclipse.swt.graphics.Image;\r
 import org.eclipse.swt.widgets.Composite;\r
 import org.eclipse.swt.widgets.Control;\r
@@ -46,11 +47,12 @@ import org.simantics.Simantics;
 import org.simantics.db.ReadGraph;\r
 import org.simantics.db.Resource;\r
 import org.simantics.db.Session;\r
-import org.simantics.db.common.primitiverequest.Adapter;\r
+import org.simantics.db.common.primitiverequest.PossibleAdapter;\r
 import org.simantics.db.common.procedure.adapter.TransientCacheListener;\r
 import org.simantics.db.common.request.BinaryRead;\r
 import org.simantics.db.common.request.ObjectsWithType;\r
 import org.simantics.db.common.request.ReadRequest;\r
+import org.simantics.db.common.request.UniqueRead;\r
 import org.simantics.db.common.uri.UnescapedChildMapOfResource;\r
 import org.simantics.db.common.utils.NameUtils;\r
 import org.simantics.db.exception.DatabaseException;\r
@@ -64,24 +66,38 @@ import org.simantics.debug.ui.internal.DebugUtils;
 import org.simantics.layer0.Layer0;\r
 import org.simantics.operation.Layer0X;\r
 import org.simantics.scl.runtime.function.Function;\r
-import org.simantics.ui.SimanticsUI;\r
+import org.simantics.ui.selection.ResourceWorkbenchSelectionElement;\r
 import org.simantics.ui.workbench.dialogs.ResourceLabelProvider;\r
 import org.simantics.utils.Container;\r
 import org.simantics.utils.ui.BundleUtils;\r
+import org.slf4j.Logger;\r
+import org.slf4j.LoggerFactory;\r
 \r
 /**\r
  * TODO Add Debugger Composite as preview!\r
  */\r
 public class SearchResourceDialog extends FilteredItemsSelectionDialog {\r
 \r
+    private static final Logger LOGGER = LoggerFactory.getLogger(SearchResourceDialog.class);\r
+\r
+    /**\r
+     * The default maximum amount of Dependencies index hits to produce as results.\r
+     */\r
+    private static final int DEFAULT_MAX_INDEX_HITS = 1000;\r
+\r
+    private static final Pattern ID_PATTERN = Pattern.compile("\\$([0-9]+)");\r
+\r
     private static final String SEARCH_RESOURCE_DIALOG = "SearchResourceDialog"; //$NON-NLS-1$\r
 \r
-    Session session;\r
-    IStructuredSelection selection;\r
-    ResourceManager resourceManager;\r
+    private static final int SHOW_IN_BROWSER_ID = IDialogConstants.CLIENT_ID + 1;\r
+\r
+    private static final String SHOW_IN_BROWSER_LABEL = "Show In Browser";\r
 \r
-    // Needed in a subclass\r
-    protected IResourceFilter resourceFilter = ResourceSearch.FILTER_ALL;\r
+    private Session session;\r
+    @SuppressWarnings("unused")\r
+    private IStructuredSelection selection;\r
+    private ResourceManager resourceManager;\r
+    private IResourceFilter resourceFilter = ResourceSearch.FILTER_ALL;\r
 \r
     LabelProvider detailsLabelProvider = new LabelProvider() {\r
         @Override\r
@@ -143,69 +159,75 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
     public SearchResourceDialog(Session s, boolean multi, Shell shell, String title, IStructuredSelection selection) {\r
         super(shell, multi);\r
         this.session = s;\r
-        resourceManager = new LocalResourceManager(JFaceResources.getResources());\r
+        this.selection = selection;\r
         this.labelProvider = new ElementLabelProvider(shell.getDisplay());\r
-        setMessage("Enter ID, URI or name");\r
+        setMessage("Enter name, resource URI or ID");\r
         setListLabelProvider(labelProvider);\r
         setDetailsLabelProvider(detailsLabelProvider);\r
-        setImage((Image) resourceManager.get(BundleUtils.getImageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/cog_blue.png")));\r
         setTitle(title);\r
         //setInitialPattern("*", FilteredItemsSelectionDialog.FULL_SELECTION);\r
         setSelectionHistory(new ResourceSelectionHistory());\r
-        this.selection = selection;\r
         setSeparatorLabel("Previously selected above, others below");\r
     }\r
 \r
     @Override\r
     protected void configureShell(Shell shell) {\r
+        this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), shell);\r
+        setImage((Image) resourceManager.get(BundleUtils.getImageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/cog_blue.png")));\r
         super.configureShell(shell);\r
-        shell.addDisposeListener(new DisposeListener() {\r
-            @Override\r
-            public void widgetDisposed(DisposeEvent e) {\r
-                resourceManager.dispose();\r
-            }\r
-        });\r
+    }\r
+\r
+    @Override\r
+    protected void createButtonsForButtonBar(Composite parent) {\r
+        createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,\r
+                true);\r
+        createButton(parent, SHOW_IN_BROWSER_ID, SHOW_IN_BROWSER_LABEL,\r
+                true);\r
+        createButton(parent, IDialogConstants.CANCEL_ID,\r
+                IDialogConstants.CANCEL_LABEL, false);\r
+    }\r
+\r
+    @Override\r
+    protected void buttonPressed(int buttonId) {\r
+        if (buttonId == SHOW_IN_BROWSER_ID) {\r
+            okPressed();\r
+            LabeledResource lr = (LabeledResource) getFirstResult();\r
+            ShowInBrowser.defaultExecute(new StructuredSelection(new ResourceWorkbenchSelectionElement(lr.resource)));\r
+            return;\r
+        }\r
+        super.buttonPressed(buttonId);\r
     }\r
 \r
     class ResourceSelectionHistory extends FilteredItemsSelectionDialog.SelectionHistory {\r
 \r
         @Override\r
         protected Object restoreItemFromMemento(IMemento memento) {\r
-            String dada = memento.getTextData();\r
+            String data = memento.getTextData();\r
             try {\r
-                SerialisationSupport support = SimanticsUI.getSession().getService(SerialisationSupport.class);\r
-                final Resource r = support.getResource(Long.parseLong(dada));\r
-                if (r == null) {\r
+                SerialisationSupport support = Simantics.getSession().getService(SerialisationSupport.class);\r
+                Resource r = support.getResource(Long.parseLong(data));\r
+                if (r == null)\r
                     return null;\r
-                }\r
 \r
-                String name = session.syncRequest(new Read<String>() {\r
+                String name = session.syncRequest(new UniqueRead<String>() {\r
                     @Override\r
                     public String perform(ReadGraph g) throws DatabaseException {\r
-                        if (!resourceFilter.acceptResource(g, r)) {\r
+                        if (!resourceFilter.acceptResource(g, r))\r
                             return null;\r
-                        }\r
-                        String name = null;\r
                         try {\r
                             try {\r
-                                name = g.adapt(r, String.class);\r
+                                return g.adapt(r, String.class);\r
                             } catch (Exception ex) {\r
                                 System.out.println("Exception thrown from restoreItemFromMemento");\r
                             }\r
-                            if (name != null) {\r
-                                return name;\r
-                            }\r
                         } catch (Throwable t) {}\r
                         return "" + r.getResourceId();\r
                     }\r
                 });\r
                 if (name==null) return null;\r
                 return new LabeledResource(name, r);\r
-            } catch (NumberFormatException e) {\r
-                e.printStackTrace();\r
-                return null;\r
-            } catch (DatabaseException e) {\r
-                e.printStackTrace();\r
+            } catch (NumberFormatException | DatabaseException e) {\r
+                LOGGER.info("Search memento restoration failed.", e);\r
                 return null;\r
             }\r
         }\r
@@ -215,7 +237,7 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
         protected void storeItemToMemento(Object item, IMemento memento) {\r
             if(item instanceof Container) {\r
                 try {\r
-                    SerialisationSupport support = SimanticsUI.getSession().getService(SerialisationSupport.class);\r
+                    SerialisationSupport support = Simantics.getSession().getService(SerialisationSupport.class);\r
                     memento.putTextData(String.valueOf(support.getRandomAccessId(((Container<Resource>)item).get())));\r
                 } catch (DatabaseException e) {\r
                     e.printStackTrace();\r
@@ -268,7 +290,7 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
         final long referencedResourceId = referencedResourceId(pattern);\r
         final boolean findIds = referencedResourceId != 0;\r
 \r
-        progressMonitor.beginTask("Searching", IProgressMonitor.UNKNOWN);\r
+        //progressMonitor.beginTask("Searching", IProgressMonitor.UNKNOWN);\r
 \r
         try {\r
             session.syncRequest(new ReadRequest() {\r
@@ -308,13 +330,12 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
                             filter += "Name:" + pattern + "*";\r
 \r
                             Layer0 L0 = Layer0.getInstance(graph);\r
-                            \r
-                            HashSet<Resource> indexRoots = new HashSet<Resource>();\r
+\r
+                            Set<Resource> indexRoots = new HashSet<>();\r
                             indexRoots.addAll(graph.syncRequest(new ObjectsWithType(project, L0.ConsistsOf, L0.IndexRoot)));\r
                             indexRoots.addAll(graph.syncRequest(new OntologiesFromLibrary(graph.getRootLibrary())));\r
                             for (Resource indexRoot : indexRoots) {\r
-                                Collection<Resource> hits = new ArrayList<Resource>(find(graph, indexRoot, filter));\r
-                                hits.add(indexRoot);\r
+                                Collection<Resource> hits = find(graph, indexRoot, filter);\r
                                 for (Resource r : hits) {\r
                                     if (rf != null && !rf.acceptResource(graph, r))\r
                                         continue;\r
@@ -326,26 +347,10 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
                 }\r
 \r
                 public Collection<Resource> find(ReadGraph graph, Resource index, String filter) throws DatabaseException {\r
+                    //TimeLogger.resetTimeAndLog("find(" + graph.getURI(index) + ", " + filter + ")");\r
                     Collection<Resource> indexResult = graph.syncRequest(new QueryIndex(index, filter), TransientCacheListener.<Collection<Resource>>instance());\r
-\r
-//                    Layer0 L0 = Layer0.getInstance(graph);\r
-//                    Collection<Resource> linkedRoots = graph.syncRequest(new ObjectsWithType(index, L0.IsLinkedTo, L0.IndexRoot));\r
-//                    if (linkedRoots.isEmpty())\r
-                        return indexResult;\r
-\r
-//                    Collection<Resource> result = indexResult;\r
-//                    for (Resource dep : linkedRoots) {\r
-//                        Collection<Resource> linkedIndexResults = find(graph, dep, filter);\r
-//                        if (linkedIndexResults.isEmpty())\r
-//                            continue;\r
-//                        if (result == indexResult) {\r
-//                            result = new ArrayList<Resource>(indexResult.size() + linkedIndexResults.size());\r
-//                            result.addAll(indexResult);\r
-//                        } else {\r
-//                        }\r
-//                        result.addAll(linkedIndexResults);\r
-//                    }\r
-//                    return result;\r
+                    //TimeLogger.log("found " + indexResult.size());\r
+                    return indexResult;\r
                 }\r
 \r
             });\r
@@ -372,28 +377,26 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
             Layer0X L0X = Layer0X.getInstance(graph);\r
 \r
             @SuppressWarnings({ "unchecked", "rawtypes" })\r
-            Function dependencies = graph.syncRequest(new Adapter(L0X.Dependencies, Function.class), TransientCacheListener.<Function>instance());\r
+            Function dependencies = graph.syncRequest(new PossibleAdapter(L0X.DependencyResources, Function.class), TransientCacheListener.<Function>instance());\r
+            if (dependencies == null)\r
+                return Collections.emptyList();\r
 \r
             @SuppressWarnings("unchecked")\r
-            Collection<Map<String, Object>> results = (Collection<Map<String, Object>>)dependencies.apply(graph, parameter, parameter2);\r
+            List<Resource> results = (List<Resource>) dependencies.apply(graph, parameter, parameter2, DEFAULT_MAX_INDEX_HITS);\r
             if (results == null || results.isEmpty())\r
                 return Collections.emptyList();\r
 \r
-            // TreeSet to keep the results in deterministic order.\r
-            Set<Resource> resultSet = new TreeSet<Resource>();\r
-            for (Map<String, Object> entry : results) {\r
-                Resource res = (Resource)entry.get("Resource");\r
+            // TreeSet to keep the results in deterministic order and to prevent duplicates.\r
+            Set<Resource> resultSet = new TreeSet<>();\r
+            for (Resource res : results) {\r
                 if (res != null && !resultSet.contains(res))\r
                     resultSet.add(res);\r
             }\r
-\r
             return new ArrayList<Resource>(resultSet);\r
         }\r
 \r
     }\r
 \r
-    Pattern ID_PATTERN = Pattern.compile("\\$([0-9]+)");\r
-\r
     private long referencedResourceId(String pattern) {\r
         Matcher m = ID_PATTERN.matcher(pattern);\r
         if (m.matches()) {\r
@@ -424,14 +427,10 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
         //return item.toString();\r
     }\r
 \r
-    @SuppressWarnings("rawtypes")\r
     @Override\r
-    protected Comparator getItemsComparator() {\r
-        return new Comparator() {\r
-            @Override\r
-            public int compare(Object arg0, Object arg1) {\r
-                return arg0.toString().compareTo(arg1.toString());\r
-            }\r
+    protected Comparator<?> getItemsComparator() {\r
+        return (arg0, arg1) -> {\r
+            return arg0.toString().compareTo(arg1.toString());\r
         };\r
     }\r
 \r