package jetbrains.mps.ide.findusages.findalgorithm.finders; /*Generated by MPS */ import jetbrains.mps.ide.findusages.model.SearchResults; import jetbrains.mps.ide.findusages.model.SearchResult; import jetbrains.mps.internal.collections.runtime.ListSequence; import java.util.List; import org.jetbrains.mps.openapi.model.SNode; import java.util.Comparator; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.smodel.behaviour.BHReflection; import jetbrains.mps.core.aspects.behaviour.SMethodTrimmedId; import jetbrains.mps.util.IterableUtil; public class FinderUtils { private FinderUtils() { } public static boolean isAllResultsIsNodes(SearchResults results) { for (SearchResult result : ListSequence.fromList(((List<SearchResult>) results.getSearchResults()))) { if (!(result.getObject() instanceof SNode)) { return false; } } return true; } public static void sortNodeResultsByEditorPosition(SearchResults<SNode> results) { List<SearchResult<SNode>> resultList = results.getSearchResults(); List<SearchResult<SNode>> sorted = ListSequence.fromList(resultList).sort(new Comparator<SearchResult<SNode>>() { public int compare(SearchResult<SNode> a, SearchResult<SNode> b) { return FinderUtils.compareNodes(a.getObject(), b.getObject()); } }, true).toListSequence(); results.getSearchResults().clear(); results.getSearchResults().addAll(sorted); } public static int compareNodes(SNode n1, SNode n2) { List<SNode> path1 = ListSequence.fromList(SNodeOperations.getNodeAncestors(n1, null, true)).reversedList(); List<SNode> path2 = ListSequence.fromList(SNodeOperations.getNodeAncestors(n2, null, true)).reversedList(); for (int i = 0; i < ListSequence.fromList(path1).count() && i < ListSequence.fromList(path2).count(); ++i) { if (ListSequence.fromList(path1).getElement(i) != ListSequence.fromList(path2).getElement(i)) { return compareBrothers(ListSequence.fromList(path1).getElement(i), ListSequence.fromList(path2).getElement(i)); } } return ListSequence.fromList(path1).count() - ListSequence.fromList(path2).count(); } public static int compareBrothers(SNode n1, SNode n2) { if (SNodeOperations.getContainingLink(n1) == null || SNodeOperations.getContainingLink(n2) == null) { // if one of them is null, both must be null assert SNodeOperations.getContainingLink(n1) == null && SNodeOperations.getContainingLink(n2) == null : "Root node is supposed to be a 'brother' of another root node only. n1=" + ((String) BHReflection.invoke(n1, SMethodTrimmedId.create("getPresentation", null, "hEwIMiw"))) + ", n2=" + ((String) BHReflection.invoke(n2, SMethodTrimmedId.create("getPresentation", null, "hEwIMiw"))); return n1.getPresentation().compareTo(n2.getPresentation()); } List<SNode> children = IterableUtil.asList(SNodeOperations.getParent(n1).getChildren()); return ListSequence.fromList(children).indexOf(n1) - ListSequence.fromList(children).indexOf(n2); } }