1 /*******************************************************************************
2 * Copyright (c) 2007, 2016 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 * Semantum Oy - index based searching and graph manipulation (#4255)
12 *******************************************************************************/
13 package org.simantics.debug.ui;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.HashSet;
20 import java.util.List;
23 import java.util.TreeSet;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
27 import org.eclipse.core.runtime.CoreException;
28 import org.eclipse.core.runtime.IProgressMonitor;
29 import org.eclipse.core.runtime.IStatus;
30 import org.eclipse.core.runtime.Status;
31 import org.eclipse.jface.dialogs.IDialogConstants;
32 import org.eclipse.jface.dialogs.IDialogSettings;
33 import org.eclipse.jface.resource.JFaceResources;
34 import org.eclipse.jface.resource.LocalResourceManager;
35 import org.eclipse.jface.resource.ResourceManager;
36 import org.eclipse.jface.viewers.IStructuredSelection;
37 import org.eclipse.jface.viewers.LabelProvider;
38 import org.eclipse.jface.viewers.StructuredSelection;
39 import org.eclipse.swt.graphics.Image;
40 import org.eclipse.swt.widgets.Composite;
41 import org.eclipse.swt.widgets.Control;
42 import org.eclipse.swt.widgets.Display;
43 import org.eclipse.swt.widgets.Shell;
44 import org.eclipse.ui.IMemento;
45 import org.eclipse.ui.dialogs.FilteredItemsSelectionDialog;
46 import org.simantics.Simantics;
47 import org.simantics.db.ReadGraph;
48 import org.simantics.db.Resource;
49 import org.simantics.db.Session;
50 import org.simantics.db.common.primitiverequest.PossibleAdapter;
51 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
52 import org.simantics.db.common.request.BinaryRead;
53 import org.simantics.db.common.request.ObjectsWithType;
54 import org.simantics.db.common.request.ReadRequest;
55 import org.simantics.db.common.request.UniqueRead;
56 import org.simantics.db.common.uri.UnescapedChildMapOfResource;
57 import org.simantics.db.common.utils.NameUtils;
58 import org.simantics.db.exception.DatabaseException;
59 import org.simantics.db.layer0.migration.OntologiesFromLibrary;
60 import org.simantics.db.layer0.variable.Variables.Role;
61 import org.simantics.db.request.Read;
62 import org.simantics.db.service.SerialisationSupport;
63 import org.simantics.debug.ui.ResourceSearch.IResourceFilter;
64 import org.simantics.debug.ui.internal.Activator;
65 import org.simantics.debug.ui.internal.DebugUtils;
66 import org.simantics.layer0.Layer0;
67 import org.simantics.operation.Layer0X;
68 import org.simantics.scl.runtime.function.Function;
69 import org.simantics.ui.selection.ResourceWorkbenchSelectionElement;
70 import org.simantics.ui.workbench.dialogs.ResourceLabelProvider;
71 import org.simantics.utils.Container;
72 import org.simantics.utils.ui.BundleUtils;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
77 * TODO Add Debugger Composite as preview!
79 public class SearchResourceDialog extends FilteredItemsSelectionDialog {
81 private static final Logger LOGGER = LoggerFactory.getLogger(SearchResourceDialog.class);
84 * The default maximum amount of Dependencies index hits to produce as results.
86 private static final int DEFAULT_MAX_INDEX_HITS = 1000;
88 private static final Pattern ID_PATTERN = Pattern.compile("\\$([0-9]+)");
90 private static final String SEARCH_RESOURCE_DIALOG = "SearchResourceDialog"; //$NON-NLS-1$
92 private static final int SHOW_IN_BROWSER_ID = IDialogConstants.CLIENT_ID + 1;
94 private static final String SHOW_IN_BROWSER_LABEL = "Show In Browser";
96 private Session session;
97 @SuppressWarnings("unused")
98 private IStructuredSelection selection;
99 private ResourceManager resourceManager;
100 private IResourceFilter resourceFilter = ResourceSearch.FILTER_ALL;
102 LabelProvider detailsLabelProvider = new LabelProvider() {
104 public String getText(Object element) {
107 // This may happen if multiple choice is enabled
108 if (element instanceof String)
109 return (String) element;
110 @SuppressWarnings("unchecked")
111 Container<Resource> rc = (Container<Resource>) element;
112 final Resource r = rc.get();
114 return session.syncRequest(new Read<String>() {
116 public String perform(ReadGraph g) throws DatabaseException {
117 String name = NameUtils.getSafeName(g, r);
118 String uri = DebugUtils.getPossibleRootRelativePath(g, r);
120 "[" + r.getResourceId() + "] - "
122 + (uri != null ? " - " : "")
123 + (uri != null ? uri : "");
126 } catch (DatabaseException e) {
127 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Resource label provider failed unexpectedly.", e));
133 static class ElementLabelProvider extends ResourceLabelProvider {
134 public ElementLabelProvider(Display display) {
138 public String getText(Object element) {
141 return element.toString();
144 public Image getImage(Object element) {
147 @SuppressWarnings("unchecked")
148 Container<Resource> rc = (Container<Resource>) element;
149 final Resource r = rc.get();
150 return super.getImage(r);
154 ElementLabelProvider labelProvider;
156 public SearchResourceDialog(Session s, boolean multi, Shell shell, String title) {
157 this(s, multi, shell, title, null);
160 public SearchResourceDialog(Session s, boolean multi, Shell shell, String title, IStructuredSelection selection) {
163 this.selection = selection;
164 this.labelProvider = new ElementLabelProvider(shell.getDisplay());
165 setMessage("Enter name, resource URI or ID");
166 setListLabelProvider(labelProvider);
167 setDetailsLabelProvider(detailsLabelProvider);
169 //setInitialPattern("*", FilteredItemsSelectionDialog.FULL_SELECTION);
170 setSelectionHistory(new ResourceSelectionHistory());
171 setSeparatorLabel("Previously selected above, others below");
175 protected void configureShell(Shell shell) {
176 this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), shell);
177 setImage((Image) resourceManager.get(BundleUtils.getImageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/cog_blue.png")));
178 super.configureShell(shell);
182 protected void createButtonsForButtonBar(Composite parent) {
183 createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
185 createButton(parent, SHOW_IN_BROWSER_ID, SHOW_IN_BROWSER_LABEL,
187 createButton(parent, IDialogConstants.CANCEL_ID,
188 IDialogConstants.CANCEL_LABEL, false);
192 protected void buttonPressed(int buttonId) {
193 if (buttonId == SHOW_IN_BROWSER_ID) {
195 LabeledResource lr = (LabeledResource) getFirstResult();
196 ShowInBrowser.defaultExecute(new StructuredSelection(new ResourceWorkbenchSelectionElement(lr.resource)));
199 super.buttonPressed(buttonId);
202 class ResourceSelectionHistory extends FilteredItemsSelectionDialog.SelectionHistory {
205 protected Object restoreItemFromMemento(IMemento memento) {
206 String data = memento.getTextData();
208 SerialisationSupport support = Simantics.getSession().getService(SerialisationSupport.class);
209 Resource r = support.getResource(Long.parseLong(data));
213 String name = session.syncRequest(new UniqueRead<String>() {
215 public String perform(ReadGraph g) throws DatabaseException {
216 if (!resourceFilter.acceptResource(g, r))
220 return DebugUtils.getSafeLabel(g, r);
221 } catch (Exception ex) {
222 System.out.println("Exception thrown from restoreItemFromMemento");
224 } catch (Throwable t) {}
225 return "" + r.getResourceId();
228 if (name==null) return null;
229 return new LabeledResource(name, r);
230 } catch (NumberFormatException | DatabaseException e) {
231 LOGGER.info("Search memento restoration failed.", e);
236 @SuppressWarnings("unchecked")
238 protected void storeItemToMemento(Object item, IMemento memento) {
239 if(item instanceof Container) {
241 SerialisationSupport support = Simantics.getSession().getService(SerialisationSupport.class);
242 memento.putTextData(String.valueOf(support.getRandomAccessId(((Container<Resource>)item).get())));
243 } catch (DatabaseException e) {
251 protected Control createExtendedContentArea(Composite parent) {
256 protected ItemsFilter createFilter() {
257 // NOTE: filter must be created here.
258 return new ItemsFilter() {
260 public boolean matchItem(Object item) {
261 //return matches(item.toString());
265 // If this method returns true, it means fillContentProvider will
266 // not be called again, but the existing results are just re-filtered.
268 public boolean isSubFilter(ItemsFilter filter) {
269 //System.out.println(getPattern() + " vs. " + filter.getPattern());
274 public boolean isConsistentItem(Object item) {
279 public boolean equalsFilter(ItemsFilter filter) {
286 protected void fillContentProvider(final AbstractContentProvider contentProvider,
287 final ItemsFilter itemsFilter, final IProgressMonitor progressMonitor)
288 throws CoreException {
289 final String pattern = itemsFilter.getPattern();
290 final boolean findUris = pattern.trim().startsWith("http:/");
291 final long referencedResourceId = referencedResourceId(pattern);
292 final boolean findIds = referencedResourceId != 0;
294 //progressMonitor.beginTask("Searching", IProgressMonitor.UNKNOWN);
297 session.syncRequest(new ReadRequest() {
299 public void run(ReadGraph graph) throws DatabaseException {
303 Resource r = graph.getService(SerialisationSupport.class).getResource(referencedResourceId);
304 contentProvider.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r), itemsFilter);
305 //contentProvider.add(new LabeledResource(pattern, r), itemsFilter);
306 } catch (DatabaseException e) {
307 // No resource for specified id.
311 String uri = pattern;
312 if (uri.endsWith(Role.CHILD.getIdentifier())) {
313 uri = uri.substring(0, uri.length() - 1);
315 Resource r = graph.getPossibleResource(uri);
317 contentProvider.add(new LabeledResource(DebugUtils.getSafeURI(graph, r), r), itemsFilter );
319 Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(r));
320 for (Resource child : children.values()) {
321 contentProvider.add(new LabeledResource(DebugUtils.getSafeURI(graph, child), child), itemsFilter );
325 Resource project = Simantics.peekProjectResource();
326 if (project != null) {
327 IResourceFilter rf = resourceFilter;
328 String filter = getFilterForResourceFilter(rf);
329 if (!filter.isEmpty())
331 filter += "Name:" + pattern + "*";
333 Layer0 L0 = Layer0.getInstance(graph);
335 Set<Resource> indexRoots = new HashSet<>();
336 indexRoots.addAll(graph.syncRequest(new ObjectsWithType(project, L0.ConsistsOf, L0.IndexRoot)));
337 indexRoots.addAll(graph.syncRequest(new OntologiesFromLibrary(graph.getRootLibrary())));
338 for (Resource indexRoot : indexRoots) {
339 Collection<Resource> hits = find(graph, indexRoot, filter);
340 for (Resource r : hits) {
341 if (rf != null && !rf.acceptResource(graph, r))
343 contentProvider.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r), itemsFilter);
350 public Collection<Resource> find(ReadGraph graph, Resource index, String filter) throws DatabaseException {
351 //TimeLogger.resetTimeAndLog("find(" + graph.getURI(index) + ", " + filter + ")");
352 Collection<Resource> indexResult = graph.syncRequest(new QueryIndex(index, filter), TransientCacheListener.<Collection<Resource>>instance());
353 //TimeLogger.log("found " + indexResult.size());
358 } catch (DatabaseException ex) {
359 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex));
362 progressMonitor.done();
366 * A (cacheable) query to optimize single index queries for immutable
367 * indexes such as ontologies.
369 static class QueryIndex extends BinaryRead<Resource, String, Collection<Resource>> {
371 public QueryIndex(Resource index, String filter) {
372 super(index, filter);
376 public Collection<Resource> perform(ReadGraph graph)
377 throws DatabaseException {
378 Layer0X L0X = Layer0X.getInstance(graph);
380 @SuppressWarnings({ "unchecked", "rawtypes" })
381 Function dependencies = graph.syncRequest(new PossibleAdapter(L0X.DependencyResources, Function.class), TransientCacheListener.<Function>instance());
382 if (dependencies == null)
383 return Collections.emptyList();
385 @SuppressWarnings("unchecked")
386 List<Resource> results = (List<Resource>) dependencies.apply(graph, parameter, parameter2, DEFAULT_MAX_INDEX_HITS);
387 if (results == null || results.isEmpty())
388 return Collections.emptyList();
390 // TreeSet to keep the results in deterministic order and to prevent duplicates.
391 Set<Resource> resultSet = new TreeSet<>();
392 for (Resource res : results) {
393 if (res != null && !resultSet.contains(res))
396 return new ArrayList<Resource>(resultSet);
401 private long referencedResourceId(String pattern) {
402 Matcher m = ID_PATTERN.matcher(pattern);
404 String id = m.group(1);
406 return Long.parseLong(id);
407 } catch (NumberFormatException nfe) {
414 protected IDialogSettings getDialogSettings() {
415 IDialogSettings settings = Activator.getDefault().getDialogSettings()
416 .getSection(SEARCH_RESOURCE_DIALOG);
417 if (settings == null) {
418 settings = Activator.getDefault().getDialogSettings()
419 .addNewSection(SEARCH_RESOURCE_DIALOG);
424 @SuppressWarnings("unchecked")
426 public String getElementName(Object item) {
427 return ((Container<Resource>)item).get().getResourceId()+"";
428 //return item.toString();
432 protected Comparator<?> getItemsComparator() {
433 return (arg0, arg1) -> {
434 return arg0.toString().compareTo(arg1.toString());
439 protected IStatus validateItem(Object item) {
440 return Status.OK_STATUS;
443 public IResourceFilter getResourceFilter() {
444 return resourceFilter;
447 public void setResourceFilter(IResourceFilter resourceFilter) {
448 this.resourceFilter = resourceFilter;
451 private String getFilterForResourceFilter(IResourceFilter filter) {
452 if (filter == null || filter == ResourceSearch.FILTER_ALL)
454 if (filter == ResourceSearch.FILTER_RELATIONS)
455 return "Types:Relation";
456 if (filter == ResourceSearch.FILTER_TYPES)