]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.debug.ui/src/org/simantics/debug/ui/SearchResourceDialog.java
Index tokenized lowercase versions of name and types for UI searches
[simantics/platform.git] / bundles / org.simantics.debug.ui / src / org / simantics / debug / ui / SearchResourceDialog.java
index c96b8469ee2bb573fb7524877709383560028eff..06710f6e29bd03a3dec4ecbdc50d5f4afdbd4b64 100644 (file)
@@ -13,6 +13,7 @@
 package org.simantics.debug.ui;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
@@ -23,6 +24,7 @@ import java.util.Set;
 import java.util.TreeSet;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 
 import org.eclipse.core.runtime.CoreException;
 import org.eclipse.core.runtime.IProgressMonitor;
@@ -56,6 +58,8 @@ import org.simantics.db.common.request.UniqueRead;
 import org.simantics.db.common.uri.UnescapedChildMapOfResource;
 import org.simantics.db.common.utils.NameUtils;
 import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.genericrelation.Dependencies;
+import org.simantics.db.layer0.genericrelation.IndexQueries;
 import org.simantics.db.layer0.migration.OntologiesFromLibrary;
 import org.simantics.db.layer0.variable.Variables.Role;
 import org.simantics.db.request.Read;
@@ -85,13 +89,13 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
      */
     private static final int DEFAULT_MAX_INDEX_HITS = 1000;
 
-    private static final Pattern ID_PATTERN = Pattern.compile("\\$([0-9]+)");
+    private static final Pattern ID_PATTERN = Pattern.compile("\\$([0-9]+)"); //$NON-NLS-1$
 
     private static final String SEARCH_RESOURCE_DIALOG = "SearchResourceDialog"; //$NON-NLS-1$
 
     private static final int SHOW_IN_BROWSER_ID = IDialogConstants.CLIENT_ID + 1;
 
-    private static final String SHOW_IN_BROWSER_LABEL = "Show In Browser";
+    private static final String SHOW_IN_BROWSER_LABEL = Messages.SearchResourceDialog_ShowInBrowser;
 
     private Session session;
     @SuppressWarnings("unused")
@@ -103,7 +107,7 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
         @Override
         public String getText(Object element) {
             if (element == null)
-                return "null";
+                return "null"; //$NON-NLS-1$
             // This may happen if multiple choice is enabled
             if (element instanceof String)
                 return (String) element;
@@ -117,15 +121,15 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
                         String name = NameUtils.getSafeName(g, r);
                         String uri = DebugUtils.getPossibleRootRelativePath(g, r);
                         return
-                                "[" + r.getResourceId() + "] - "
+                                "[" + r.getResourceId() + "] - " //$NON-NLS-1$ //$NON-NLS-2$
                                 + name
-                                + (uri != null ? " - " : "")
-                                + (uri != null ? uri : "");
+                                + (uri != null ? " - " : "") //$NON-NLS-1$ //$NON-NLS-2$
+                                + (uri != null ? uri : ""); //$NON-NLS-1$
                     }
                 });
             } catch (DatabaseException e) {
-                Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Resource label provider failed unexpectedly.", e));
-                return "";
+                Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.SearchResourceDialog_ActivatorResourceLabelProviderFailed, e));
+                return ""; //$NON-NLS-1$
             }
         }
     };
@@ -137,7 +141,7 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
         @Override
         public String getText(Object element) {
             if (element==null)
-                return "null";
+                return "null"; //$NON-NLS-1$
             return element.toString();
         }
         @Override
@@ -162,19 +166,19 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
         this.session = s;
         this.selection = selection;
         this.labelProvider = new ElementLabelProvider(shell.getDisplay());
-        setMessage("Enter name, resource URI or ID");
+        setMessage(Messages.SearchResourceDialog_EnterNameResURIOrId);
         setListLabelProvider(labelProvider);
         setDetailsLabelProvider(detailsLabelProvider);
         setTitle(title);
         //setInitialPattern("*", FilteredItemsSelectionDialog.FULL_SELECTION);
         setSelectionHistory(new ResourceSelectionHistory());
-        setSeparatorLabel("Previously selected above, others below");
+        setSeparatorLabel(Messages.SearchResourceDialog_SeperatorLblPreviouslySelected);
     }
 
     @Override
     protected void configureShell(Shell shell) {
         this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), shell);
-        setImage((Image) resourceManager.get(BundleUtils.getImageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/cog_blue.png")));
+        setImage((Image) resourceManager.get(BundleUtils.getImageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/cog_blue.png"))); //$NON-NLS-1$
         super.configureShell(shell);
     }
 
@@ -193,7 +197,9 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
         if (buttonId == SHOW_IN_BROWSER_ID) {
             okPressed();
             LabeledResource lr = (LabeledResource) getFirstResult();
-            ShowInBrowser.defaultExecute(new StructuredSelection(new ResourceWorkbenchSelectionElement(lr.resource)));
+            if (lr != null) {
+               ShowInBrowser.defaultExecute(new StructuredSelection(new ResourceWorkbenchSelectionElement(lr.resource)));
+            }
             return;
         }
         super.buttonPressed(buttonId);
@@ -219,16 +225,16 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
                             try {
                                 return DebugUtils.getSafeLabel(g, r);
                             } catch (Exception ex) {
-                                System.out.println("Exception thrown from restoreItemFromMemento");
+                                System.out.println("Exception thrown from restoreItemFromMemento"); //$NON-NLS-1$
                             }
                         } catch (Throwable t) {}
-                        return "" + r.getResourceId();
+                        return "" + r.getResourceId(); //$NON-NLS-1$
                     }
                 });
                 if (name==null) return null;
                 return new LabeledResource(name, r);
             } catch (NumberFormatException | DatabaseException e) {
-                LOGGER.info("Search memento restoration failed.", e);
+                LOGGER.info("Search memento restoration failed.", e); //$NON-NLS-1$
                 return null;
             }
         }
@@ -255,110 +261,128 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
     @Override
     protected ItemsFilter createFilter() {
         // NOTE: filter must be created here.
-        return new ItemsFilter() {
-            @Override
-            public boolean matchItem(Object item) {
-                //return matches(item.toString());
-                return true;
-            }
+        return new ItemsFilterWithSearchResults();
+    }
 
-            // If this method returns true, it means fillContentProvider will
-            // not be called again, but the existing results are just re-filtered.
-            @Override
-            public boolean isSubFilter(ItemsFilter filter) {
-                //System.out.println(getPattern() + " vs. " + filter.getPattern());
-                return false;
-            }
+    private class ItemsFilterWithSearchResults extends ItemsFilter {
+        private Set<Object> searchResults = new HashSet<Object>();
 
-            @Override
-            public boolean isConsistentItem(Object item) {
-                return true;
-            }
+        public ItemsFilterWithSearchResults() {
+            
+            final String pattern = getPattern();
+            final boolean findUris = pattern.trim().startsWith("http:/"); //$NON-NLS-1$
+            final long referencedResourceId = referencedResourceId(pattern);
+            final boolean findIds = referencedResourceId != 0;
 
-            @Override
-            public boolean equalsFilter(ItemsFilter filter) {
-                return false;
-            }
-        };
-    }
+            searchResults.clear();
+            if (pattern.isEmpty()) return;
+            //progressMonitor.beginTask("Searching", IProgressMonitor.UNKNOWN);
 
-    @Override
-    protected void fillContentProvider(final AbstractContentProvider contentProvider,
-            final ItemsFilter itemsFilter, final IProgressMonitor progressMonitor)
-                    throws CoreException {
-        final String pattern = itemsFilter.getPattern();
-        final boolean findUris = pattern.trim().startsWith("http:/");
-        final long referencedResourceId = referencedResourceId(pattern);
-        final boolean findIds = referencedResourceId != 0;
-
-        //progressMonitor.beginTask("Searching", IProgressMonitor.UNKNOWN);
-
-        try {
-            session.syncRequest(new ReadRequest() {
-                @Override
-                public void run(ReadGraph graph) throws DatabaseException {
-                    // Find by ID first.
-                    if (findIds) {
-                        try {
-                            Resource r = graph.getService(SerialisationSupport.class).getResource(referencedResourceId);
-                            contentProvider.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r), itemsFilter);
-                            //contentProvider.add(new LabeledResource(pattern, r), itemsFilter);
-                        } catch (DatabaseException e) {
-                            // No resource for specified id.
-                        }
-                    }
-                    if (findUris) {
-                        String uri = pattern;
-                        if (uri.endsWith(Role.CHILD.getIdentifier())) {
-                            uri = uri.substring(0, uri.length() - 1);
+            try {
+                session.syncRequest(new ReadRequest() {
+                    @Override
+                    public void run(ReadGraph graph) throws DatabaseException {
+                        // Find by ID first.
+                        if (findIds) {
+                            try {
+                                Resource r = graph.getService(SerialisationSupport.class).getResource(referencedResourceId);
+                                searchResults.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r));
+                            } catch (DatabaseException e) {
+                                // No resource for specified id.
+                            }
                         }
-                        Resource r = graph.getPossibleResource(uri);
-                        if (r != null) {
-                            contentProvider.add(new LabeledResource(DebugUtils.getSafeURI(graph, r), r), itemsFilter );
+                        if (findUris) {
+                            String uri = pattern;
+                            if (uri.endsWith(Role.CHILD.getIdentifier())) {
+                                uri = uri.substring(0, uri.length() - 1);
+                            }
+                            Resource r = graph.getPossibleResource(uri);
+                            if (r != null) {
+                               searchResults.add(new LabeledResource(DebugUtils.getSafeURI(graph, r), r));
 
-                            Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(r));
-                            for (Resource child : children.values()) {
-                                contentProvider.add(new LabeledResource(DebugUtils.getSafeURI(graph, child), child), itemsFilter );
+                                Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(r));
+                                for (Resource child : children.values()) {
+                                       searchResults.add(new LabeledResource(DebugUtils.getSafeURI(graph, child), child));
+                                }
                             }
-                        }
-                    } else {
-                        Resource project = Simantics.peekProjectResource();
-                        if (project != null) {
-                            IResourceFilter rf = resourceFilter;
-                            String filter = getFilterForResourceFilter(rf);
-                            if (!filter.isEmpty())
-                                filter += " AND ";
-                            filter += "Name:" + pattern + "*";
-
-                            Layer0 L0 = Layer0.getInstance(graph);
-
-                            Set<Resource> indexRoots = new HashSet<>();
-                            indexRoots.addAll(graph.syncRequest(new ObjectsWithType(project, L0.ConsistsOf, L0.IndexRoot)));
-                            indexRoots.addAll(graph.syncRequest(new OntologiesFromLibrary(graph.getRootLibrary())));
-                            for (Resource indexRoot : indexRoots) {
-                                Collection<Resource> hits = find(graph, indexRoot, filter);
-                                for (Resource r : hits) {
-                                    if (rf != null && !rf.acceptResource(graph, r))
-                                        continue;
-                                    contentProvider.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r), itemsFilter);
+                        } else {
+                            String[] terms = pattern.trim().split("\\s+"); //$NON-NLS-1$
+                            if (terms.length == 0) return;
+
+                            Resource project = Simantics.peekProjectResource();
+                            if (project != null) {
+                                IResourceFilter rf = resourceFilter;
+                                String filter = getFilterForResourceFilter(rf);
+                                if (!filter.isEmpty())
+                                    filter += " AND "; //$NON-NLS-1$
+                                
+                                filter += Dependencies.FIELD_NAME_SEARCH + ":("; //$NON-NLS-1$
+                                filter += Arrays.stream(terms).map(term -> "+" + IndexQueries.escape(term.toLowerCase(), false) + "*").collect(Collectors.joining(" ")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                                filter +=")"; //$NON-NLS-1$
+
+                                Layer0 L0 = Layer0.getInstance(graph);
+
+                                Set<Resource> indexRoots = new HashSet<>();
+                                indexRoots.addAll(graph.syncRequest(new ObjectsWithType(project, L0.ConsistsOf, L0.IndexRoot)));
+                                indexRoots.addAll(graph.syncRequest(new OntologiesFromLibrary(graph.getRootLibrary())));
+                                for (Resource indexRoot : indexRoots) {
+                                    Collection<Resource> hits = find(graph, indexRoot, filter);
+                                    for (Resource r : hits) {
+                                        if (rf != null && !rf.acceptResource(graph, r))
+                                            continue;
+                                        searchResults.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r));
+                                    }
                                 }
                             }
                         }
                     }
-                }
 
-                public Collection<Resource> find(ReadGraph graph, Resource index, String filter) throws DatabaseException {
-                    //TimeLogger.resetTimeAndLog("find(" + graph.getURI(index) + ", " + filter + ")");
-                    Collection<Resource> indexResult = graph.syncRequest(new QueryIndex(index, filter), TransientCacheListener.<Collection<Resource>>instance());
-                    //TimeLogger.log("found " + indexResult.size());
-                    return indexResult;
-                }
+                    public Collection<Resource> find(ReadGraph graph, Resource index, String filter) throws DatabaseException {
+                        //TimeLogger.resetTimeAndLog("find(" + graph.getURI(index) + ", " + filter + ")");
+                        Collection<Resource> indexResult = graph.syncRequest(new QueryIndex(index, filter), TransientCacheListener.<Collection<Resource>>instance());
+                        //TimeLogger.log("found " + indexResult.size());
+                        return indexResult;
+                    }
+
+                });
+            } catch (DatabaseException ex) {
+                Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex));
+            }
 
-            });
-        } catch (DatabaseException ex) {
-            Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex));
         }
 
+        @Override
+        public boolean matchItem(Object item) {
+            return searchResults.contains(item);
+        }
+
+        @Override
+        public boolean isSubFilter(ItemsFilter filter) {
+            return false;
+        }
+        
+        @Override
+        public boolean isConsistentItem(Object item) {
+            return true;
+        }
+        
+        @Override
+        public boolean equalsFilter(ItemsFilter filter) {
+            return false;
+        }
+        
+        public void fillContentProvider(final AbstractContentProvider contentProvider) {
+               for (Object item : searchResults) {
+                       contentProvider.add(item, this);
+               }
+        }
+    }
+    
+    @Override
+    protected void fillContentProvider(final AbstractContentProvider contentProvider,
+            final ItemsFilter itemsFilter, final IProgressMonitor progressMonitor)
+                    throws CoreException {
+        ((ItemsFilterWithSearchResults) itemsFilter).fillContentProvider(contentProvider);
         progressMonitor.done();
     }
 
@@ -424,7 +448,7 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
     @SuppressWarnings("unchecked")
     @Override
     public String getElementName(Object item) {
-        return ((Container<Resource>)item).get().getResourceId()+"";
+        return ((Container<Resource>)item).get().getResourceId()+""; //$NON-NLS-1$
         //return item.toString();
     }
 
@@ -450,12 +474,12 @@ public class SearchResourceDialog extends FilteredItemsSelectionDialog {
 
     private String getFilterForResourceFilter(IResourceFilter filter) {
         if (filter == null || filter == ResourceSearch.FILTER_ALL)
-            return "";
+            return ""; //$NON-NLS-1$
         if (filter == ResourceSearch.FILTER_RELATIONS)
-            return "Types:Relation"; 
+            return "Types:Relation";  //$NON-NLS-1$
         if (filter == ResourceSearch.FILTER_TYPES)
-            return "Types:Type"; 
-        return "";
+            return "Types:Type";  //$NON-NLS-1$
+        return ""; //$NON-NLS-1$
     }
 
 }