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();
197 ShowInBrowser.defaultExecute(new StructuredSelection(new ResourceWorkbenchSelectionElement(lr.resource)));
201 super.buttonPressed(buttonId);
204 class ResourceSelectionHistory extends FilteredItemsSelectionDialog.SelectionHistory {
207 protected Object restoreItemFromMemento(IMemento memento) {
208 String data = memento.getTextData();
210 SerialisationSupport support = Simantics.getSession().getService(SerialisationSupport.class);
211 Resource r = support.getResource(Long.parseLong(data));
215 String name = session.syncRequest(new UniqueRead<String>() {
217 public String perform(ReadGraph g) throws DatabaseException {
218 if (!resourceFilter.acceptResource(g, r))
222 return DebugUtils.getSafeLabel(g, r);
223 } catch (Exception ex) {
224 System.out.println("Exception thrown from restoreItemFromMemento");
226 } catch (Throwable t) {}
227 return "" + r.getResourceId();
230 if (name==null) return null;
231 return new LabeledResource(name, r);
232 } catch (NumberFormatException | DatabaseException e) {
233 LOGGER.info("Search memento restoration failed.", e);
238 @SuppressWarnings("unchecked")
240 protected void storeItemToMemento(Object item, IMemento memento) {
241 if(item instanceof Container) {
243 SerialisationSupport support = Simantics.getSession().getService(SerialisationSupport.class);
244 memento.putTextData(String.valueOf(support.getRandomAccessId(((Container<Resource>)item).get())));
245 } catch (DatabaseException e) {
253 protected Control createExtendedContentArea(Composite parent) {
258 protected ItemsFilter createFilter() {
259 // NOTE: filter must be created here.
260 return new ItemsFilterWithSearchResults();
263 private class ItemsFilterWithSearchResults extends ItemsFilter {
264 private Set<Object> searchResults = new HashSet<Object>();
266 public ItemsFilterWithSearchResults() {
268 final String pattern = getPattern();
269 final boolean findUris = pattern.trim().startsWith("http:/");
270 final long referencedResourceId = referencedResourceId(pattern);
271 final boolean findIds = referencedResourceId != 0;
273 searchResults.clear();
274 if (pattern.isEmpty()) return;
275 //progressMonitor.beginTask("Searching", IProgressMonitor.UNKNOWN);
278 session.syncRequest(new ReadRequest() {
280 public void run(ReadGraph graph) throws DatabaseException {
284 Resource r = graph.getService(SerialisationSupport.class).getResource(referencedResourceId);
285 searchResults.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r));
286 } catch (DatabaseException e) {
287 // No resource for specified id.
291 String uri = pattern;
292 if (uri.endsWith(Role.CHILD.getIdentifier())) {
293 uri = uri.substring(0, uri.length() - 1);
295 Resource r = graph.getPossibleResource(uri);
297 searchResults.add(new LabeledResource(DebugUtils.getSafeURI(graph, r), r));
299 Map<String, Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(r));
300 for (Resource child : children.values()) {
301 searchResults.add(new LabeledResource(DebugUtils.getSafeURI(graph, child), child));
305 Resource project = Simantics.peekProjectResource();
306 if (project != null) {
307 IResourceFilter rf = resourceFilter;
308 String filter = getFilterForResourceFilter(rf);
309 if (!filter.isEmpty())
311 filter += "Name:" + pattern + "*";
313 Layer0 L0 = Layer0.getInstance(graph);
315 Set<Resource> indexRoots = new HashSet<>();
316 indexRoots.addAll(graph.syncRequest(new ObjectsWithType(project, L0.ConsistsOf, L0.IndexRoot)));
317 indexRoots.addAll(graph.syncRequest(new OntologiesFromLibrary(graph.getRootLibrary())));
318 for (Resource indexRoot : indexRoots) {
319 Collection<Resource> hits = find(graph, indexRoot, filter);
320 for (Resource r : hits) {
321 if (rf != null && !rf.acceptResource(graph, r))
323 searchResults.add(new LabeledResource(DebugUtils.getSafeLabel(graph, r), r));
330 public Collection<Resource> find(ReadGraph graph, Resource index, String filter) throws DatabaseException {
331 //TimeLogger.resetTimeAndLog("find(" + graph.getURI(index) + ", " + filter + ")");
332 Collection<Resource> indexResult = graph.syncRequest(new QueryIndex(index, filter), TransientCacheListener.<Collection<Resource>>instance());
333 //TimeLogger.log("found " + indexResult.size());
338 } catch (DatabaseException ex) {
339 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex));
345 public boolean matchItem(Object item) {
346 return searchResults.contains(item);
350 public boolean isSubFilter(ItemsFilter filter) {
355 public boolean isConsistentItem(Object item) {
360 public boolean equalsFilter(ItemsFilter filter) {
364 public void fillContentProvider(final AbstractContentProvider contentProvider) {
365 for (Object item : searchResults) {
366 contentProvider.add(item, this);
372 protected void fillContentProvider(final AbstractContentProvider contentProvider,
373 final ItemsFilter itemsFilter, final IProgressMonitor progressMonitor)
374 throws CoreException {
375 ((ItemsFilterWithSearchResults) itemsFilter).fillContentProvider(contentProvider);
376 progressMonitor.done();
380 * A (cacheable) query to optimize single index queries for immutable
381 * indexes such as ontologies.
383 static class QueryIndex extends BinaryRead<Resource, String, Collection<Resource>> {
385 public QueryIndex(Resource index, String filter) {
386 super(index, filter);
390 public Collection<Resource> perform(ReadGraph graph)
391 throws DatabaseException {
392 Layer0X L0X = Layer0X.getInstance(graph);
394 @SuppressWarnings({ "unchecked", "rawtypes" })
395 Function dependencies = graph.syncRequest(new PossibleAdapter(L0X.DependencyResources, Function.class), TransientCacheListener.<Function>instance());
396 if (dependencies == null)
397 return Collections.emptyList();
399 @SuppressWarnings("unchecked")
400 List<Resource> results = (List<Resource>) dependencies.apply(graph, parameter, parameter2, DEFAULT_MAX_INDEX_HITS);
401 if (results == null || results.isEmpty())
402 return Collections.emptyList();
404 // TreeSet to keep the results in deterministic order and to prevent duplicates.
405 Set<Resource> resultSet = new TreeSet<>();
406 for (Resource res : results) {
407 if (res != null && !resultSet.contains(res))
410 return new ArrayList<Resource>(resultSet);
415 private long referencedResourceId(String pattern) {
416 Matcher m = ID_PATTERN.matcher(pattern);
418 String id = m.group(1);
420 return Long.parseLong(id);
421 } catch (NumberFormatException nfe) {
428 protected IDialogSettings getDialogSettings() {
429 IDialogSettings settings = Activator.getDefault().getDialogSettings()
430 .getSection(SEARCH_RESOURCE_DIALOG);
431 if (settings == null) {
432 settings = Activator.getDefault().getDialogSettings()
433 .addNewSection(SEARCH_RESOURCE_DIALOG);
438 @SuppressWarnings("unchecked")
440 public String getElementName(Object item) {
441 return ((Container<Resource>)item).get().getResourceId()+"";
442 //return item.toString();
446 protected Comparator<?> getItemsComparator() {
447 return (arg0, arg1) -> {
448 return arg0.toString().compareTo(arg1.toString());
453 protected IStatus validateItem(Object item) {
454 return Status.OK_STATUS;
457 public IResourceFilter getResourceFilter() {
458 return resourceFilter;
461 public void setResourceFilter(IResourceFilter resourceFilter) {
462 this.resourceFilter = resourceFilter;
465 private String getFilterForResourceFilter(IResourceFilter filter) {
466 if (filter == null || filter == ResourceSearch.FILTER_ALL)
468 if (filter == ResourceSearch.FILTER_RELATIONS)
469 return "Types:Relation";
470 if (filter == ResourceSearch.FILTER_TYPES)