com.intellij.util.ArrayUtil Java Examples
The following examples show how to use
com.intellij.util.ArrayUtil.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VirtualDirectoryImpl.java From consulo with Apache License 2.0 | 6 votes |
public void removeChild(@Nonnull VirtualFile file) { boolean caseSensitive = getFileSystem().isCaseSensitive(); String name = file.getName(); synchronized (myData) { int indexInReal = findIndex(myData.myChildrenIds, name, caseSensitive); if (indexInReal >= 0) { // there suddenly can be that we ask to add name to adopted whereas it already contained in the real part // in this case we should remove it from there myData.myChildrenIds = ArrayUtil.remove(myData.myChildrenIds, indexInReal); } if (!allChildrenLoaded()) { myData.addAdoptedName(name, caseSensitive); } assertConsistency(caseSensitive, file); } }
Example #2
Source File: GeneratedClassFindUsagesHandler.java From litho with Apache License 2.0 | 6 votes |
@Override public PsiElement[] getPrimaryElements() { final Map<String, String> data = new HashMap<>(); // Overriden below data.put(EventLogger.KEY_RESULT, "fail"); final PsiElement[] results = Optional.of(getPsiElement()) .filter(PsiClass.class::isInstance) .map(PsiClass.class::cast) .map(findGeneratedClass) .map( psiClass -> { data.put(EventLogger.KEY_RESULT, "success"); return ArrayUtil.insert(super.getPrimaryElements(), 0, psiClass); }) .orElseGet(super::getPrimaryElements); data.put(EventLogger.KEY_TARGET, "class"); data.put(EventLogger.KEY_TYPE, EventLogger.VALUE_NAVIGATION_TYPE_FIND_USAGES); LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_NAVIGATION, data); return results; }
Example #3
Source File: LoadTextUtil.java From consulo with Apache License 2.0 | 6 votes |
/** * Loads content of given virtual file. If limit is {@value UNLIMITED} then full CharSequence will be returned. Else CharSequence * will be truncated by limit if it has bigger length. * * @param file Virtual file for content loading * @param limit Maximum characters count or {@value UNLIMITED} * @return Full or truncated CharSequence with file content * @throws IllegalArgumentException for binary files */ @Nonnull public static CharSequence loadText(@Nonnull final VirtualFile file, int limit) { FileType type = file.getFileType(); if (type.isBinary()) throw new IllegalArgumentException("Attempt to load truncated text for binary file: " + file.getPresentableUrl() + ". File type: " + type.getName()); if (file instanceof LightVirtualFile) { return limitCharSequence(((LightVirtualFile)file).getContent(), limit); } if (file.isDirectory()) { throw new AssertionError("'" + file.getPresentableUrl() + "' is a directory"); } try { byte[] bytes = limit == UNLIMITED ? file.contentsToByteArray() : FileUtil.loadFirstAndClose(file.getInputStream(), limit); return getTextByBinaryPresentation(bytes, file); } catch (IOException e) { return ArrayUtil.EMPTY_CHAR_SEQUENCE; } }
Example #4
Source File: CachedValuesManager.java From consulo with Apache License 2.0 | 6 votes |
/** * Create a cached value with the given provider and non-tracked return value, store it in PSI element's user data. If it's already stored, reuse it. * * @return The cached value */ public static <T> T getCachedValue(@Nonnull final PsiElement psi, @Nonnull Key<CachedValue<T>> key, @Nonnull final CachedValueProvider<T> provider) { CachedValue<T> value = psi.getUserData(key); if (value != null) { return value.getValue(); } return getManager(psi.getProject()).getCachedValue(psi, key, () -> { CachedValueProvider.Result<T> result = provider.compute(); if (result != null && !psi.isPhysical()) { PsiFile file = psi.getContainingFile(); if (file != null) { return CachedValueProvider.Result.create(result.getValue(), ArrayUtil.append(result.getDependencyItems(), file, ArrayUtil.OBJECT_ARRAY_FACTORY)); } } return result; }, false); }
Example #5
Source File: RunAnythingChooseContextAction.java From consulo with Apache License 2.0 | 6 votes |
@RequiredUIAccess @Override public void actionPerformed(@Nonnull AnActionEvent e) { Application.get().invokeLater(() -> { Project project = e.getProject(); FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor(); descriptor.setUseApplicationDialog(); PathChooserDialog chooser = FileChooserFactory.getInstance().createPathChooser(descriptor, project, e.getDataContext().getData(PlatformDataKeys.CONTEXT_COMPONENT)); chooser.chooseAsync(project.getBaseDir()).doWhenDone(virtualFiles -> { List<String> recentDirectories = RunAnythingContextRecentDirectoryCache.getInstance(project).getState().paths; String path = ArrayUtil.getFirstElement(virtualFiles).getPath(); if (recentDirectories.size() >= Registry.intValue("run.anything.context.recent.directory.number")) { recentDirectories.remove(0); } recentDirectories.add(path); setSelectedContext(new RunAnythingContext.RecentDirectoryContext(path)); }); }); }
Example #6
Source File: SpecMethodFindUsagesHandler.java From litho with Apache License 2.0 | 6 votes |
@Override public PsiElement[] getPrimaryElements() { return Optional.of(getPsiElement()) .filter(PsiMethod.class::isInstance) .map(PsiMethod.class::cast) .map(this::findComponentMethods) .map( methods -> { final Map<String, String> data = new HashMap<>(); data.put(EventLogger.KEY_TARGET, "method"); data.put(EventLogger.KEY_TYPE, EventLogger.VALUE_NAVIGATION_TYPE_FIND_USAGES); LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_NAVIGATION, data); return ArrayUtil.mergeArrays(methods, super.getPrimaryElements()); }) .orElseGet(super::getPrimaryElements); }
Example #7
Source File: HaxeAnnotationTest.java From intellij-haxe with Apache License 2.0 | 6 votes |
private void doTest(String... additionalPaths) throws Exception { final String[] paths = ArrayUtil.append(additionalPaths, getTestName(false) + ".hx"); myFixture.configureByFiles(ArrayUtil.reverseArray(paths)); final HaxeTypeAnnotator annotator = new HaxeTypeAnnotator(); try { LanguageAnnotators.INSTANCE.addExplicitExtension(HaxeLanguage.INSTANCE, annotator); myFixture.enableInspections(getAnnotatorBasedInspection()); try { myFixture.testHighlighting(true, true, true, myFixture.getFile().getVirtualFile()); } finally { LanguageAnnotators.INSTANCE.removeExplicitExtension(HaxeLanguage.INSTANCE, annotator); } } finally { LanguageAnnotators.INSTANCE.removeExplicitExtension(HaxeLanguage.INSTANCE, annotator); } }
Example #8
Source File: GutterIntentionMenuContributor.java From consulo with Apache License 2.0 | 6 votes |
private static void addActions(@Nonnull Project project, @Nonnull RangeHighlighterEx info, @Nonnull List<? super HighlightInfo.IntentionActionDescriptor> descriptors, @Nonnull DataContext dataContext) { final GutterIconRenderer r = info.getGutterIconRenderer(); if (r == null || DumbService.isDumb(project) && !DumbService.isDumbAware(r)) { return; } List<HighlightInfo.IntentionActionDescriptor> list = new ArrayList<>(); AtomicInteger order = new AtomicInteger(); AnAction[] actions = new AnAction[]{r.getClickAction(), r.getMiddleButtonClickAction(), r.getRightButtonClickAction()}; if (r.getPopupMenuActions() != null) { actions = ArrayUtil.mergeArrays(actions, r.getPopupMenuActions().getChildren(null)); } for (AnAction action : actions) { if (action != null) { addActions(action, list, r, order, dataContext); } } descriptors.addAll(list); }
Example #9
Source File: StubBasedPsiElementBase.java From consulo with Apache License 2.0 | 6 votes |
/** * @return children of specified type, taken from stubs (if this element is currently stub-based) or AST (otherwise). */ @Nonnull public <Psi extends PsiElement> Psi[] getStubOrPsiChildren(@Nonnull TokenSet filter, @Nonnull Psi[] array) { T stub = getGreenStub(); if (stub != null) { //noinspection unchecked return (Psi[])stub.getChildrenByType(filter, array); } else { final ASTNode[] nodes = getNode().getChildren(filter); Psi[] psiElements = ArrayUtil.newArray(ArrayUtil.getComponentType(array), nodes.length); for (int i = 0; i < nodes.length; i++) { //noinspection unchecked psiElements[i] = (Psi)nodes[i].getPsi(); } return psiElements; } }
Example #10
Source File: PantsVirtualFileReference.java From intellij-pants-plugin with Apache License 2.0 | 6 votes |
@NotNull @Override public Object[] getVariants() { final PsiManager psiManager = PsiManager.getInstance(getElement().getProject()); final Optional<VirtualFile> parent = findFile(PathUtil.getParentPath(getRelativePath())); List<LookupElementBuilder> variants = parent.map( file -> Arrays.stream(file.getChildren()) .filter(VirtualFile::isDirectory) .map(f -> { final PsiFile psiFile = psiManager.findFile(f); return psiFile == null ? LookupElementBuilder.create(f.getPresentableName()) : LookupElementBuilder.create(psiFile); }) .collect(Collectors.toList())) .orElse(Collections.emptyList()); return ArrayUtil.toObjectArray(variants); }
Example #11
Source File: IntentionSettingsTree.java From consulo with Apache License 2.0 | 6 votes |
private static List<IntentionActionMetaData> sort(final List<IntentionActionMetaData> intentionsToShow) { List<IntentionActionMetaData> copy = new ArrayList<IntentionActionMetaData>(intentionsToShow); Collections.sort(copy, new Comparator<IntentionActionMetaData>() { @Override public int compare(final IntentionActionMetaData data1, final IntentionActionMetaData data2) { String[] category1 = data1.myCategory; String[] category2 = data2.myCategory; int result = ArrayUtil.lexicographicCompare(category1, category2); if (result != 0) { return result; } return data1.getFamily().compareTo(data2.getFamily()); } }); return copy; }
Example #12
Source File: KeymapImpl.java From consulo with Apache License 2.0 | 6 votes |
private String[] getActionIds(KeyboardModifierGestureShortcut shortcut) { // first, get keystrokes from own map final Map<KeyboardModifierGestureShortcut, List<String>> map = getGesture2ListOfIds(); List<String> list = new ArrayList<String>(); for (Map.Entry<KeyboardModifierGestureShortcut, List<String>> entry : map.entrySet()) { if (shortcut.startsWith(entry.getKey())) { list.addAll(entry.getValue()); } } if (myParent != null) { String[] ids = getParentActionIds(shortcut); if (ids.length > 0) { for (String id : ids) { // add actions from parent keymap only if they are absent in this keymap if (!myActionId2ListOfShortcuts.containsKey(id)) { list.add(id); } } } } return sortInOrderOfRegistration(ArrayUtil.toStringArray(list)); }
Example #13
Source File: HaxeRenameTest.java From intellij-haxe with Apache License 2.0 | 6 votes |
public void doTestOnNthSelection(int n, String newName, String... additionalFiles) { // One-based, for humans. :) assertTrue(n > 0); myFixture.configureByFiles(ArrayUtil.reverseArray(ArrayUtil.append(additionalFiles, getTruncatedSourceFileName()))); // Extract the caret info, and then reset it to just the selection/position requested. List<CaretState> carets = myFixture.getEditor().getCaretModel().getCaretsAndSelections(); assertNotEmpty(carets); // No carets/selections in the source file. assertTrue(carets.size() >= n); List<CaretState> useCaret = new ArrayList<CaretState>(1); useCaret.add(carets.get(n-1)); myFixture.getEditor().getCaretModel().setCaretsAndSelections(useCaret); myFixture.testRename(getTruncatedResultFileName(), newName); }
Example #14
Source File: CS1722.java From consulo-csharp with Apache License 2.0 | 6 votes |
@Override public void invoke(@Nonnull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { DotNetType element = myTypePointer.getElement(); if(element == null) { return; } DotNetTypeList parent = (DotNetTypeList) element.getParent(); DotNetType[] types = parent.getTypes(); int i = ArrayUtil.indexOf(types, element); if(i <= 0) { return; } DotNetType elementAtZeroPosition = types[0]; PsiElement baseElementCopy = element.copy(); PsiElement elementAtZeroCopy = elementAtZeroPosition.copy(); elementAtZeroPosition.replace(baseElementCopy); element.replace(elementAtZeroCopy); }
Example #15
Source File: ExtractInterfaceHandler.java From intellij-haxe with Apache License 2.0 | 5 votes |
public void invoke(@NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) { if (elements.length != 1) return; myProject = project; myClass = (PsiClass)elements[0]; if (!CommonRefactoringUtil.checkReadOnlyStatus(project, myClass)) return; final ExtractInterfaceDialog dialog = new ExtractInterfaceDialog(myProject, myClass); if (!dialog.showAndGet() || !dialog.isExtractSuperclass()) { return; } final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); ExtractSuperClassUtil.checkSuperAccessible(dialog.getTargetDirectory(), conflicts, myClass); if (!ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject)) return; CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myInterfaceName = dialog.getExtractedSuperName(); mySelectedMembers = ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class); myTargetDir = dialog.getTargetDirectory(); myJavaDocPolicy = new DocCommentPolicy(dialog.getDocCommentPolicy()); try { doRefactoring(); } catch (IncorrectOperationException e) { LOG.error(e); } } }); } }, REFACTORING_NAME, null); }
Example #16
Source File: AnalysisScope.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull private static Set<Module> getDirectBackwardDependencies(@Nonnull Module module, @Nonnull Module[] allModules) { Set<Module> result = new HashSet<Module>(); for (Module dependency : allModules) { if (ArrayUtil.find(ModuleRootManager.getInstance(dependency).getDependencies(), module) > -1) { result.add(dependency); } } return result; }
Example #17
Source File: JDOMUtil.java From consulo with Apache License 2.0 | 5 votes |
@SuppressWarnings("unused") @Nonnull @Deprecated /** * to remove in IDEA 15 */ public static Object[] getChildNodesWithAttrs(@Nonnull Element e) { ArrayList<Object> result = new ArrayList<Object>(); result.addAll(e.getContent()); result.addAll(e.getAttributes()); return ArrayUtil.toObjectArray(result); }
Example #18
Source File: LayoutTreeComponent.java From consulo with Apache License 2.0 | 5 votes |
public void updateAndSelect(PackagingElementNode<?> node, final List<? extends PackagingElement<?>> toSelect) { myArtifactsEditor.queueValidation(); final DefaultMutableTreeNode treeNode = TreeUtil.findNodeWithObject(myTree.getRootNode(), node); myTreeStructure.clearCaches(); myBuilder.addSubtreeToUpdate(treeNode, new Runnable() { @Override public void run() { List<PackagingElementNode<?>> nodes = myTree.findNodes(toSelect); myBuilder.select(ArrayUtil.toObjectArray(nodes), null); } }); }
Example #19
Source File: HaxeSubtypesHierarchyTreeStructure.java From intellij-haxe with Apache License 2.0 | 5 votes |
@NotNull protected final Object[] buildChildren(@NotNull final HierarchyNodeDescriptor descriptor) { final HaxeClass theHaxeClass = ((HaxeTypeHierarchyNodeDescriptor) descriptor).getHaxeClass(); if (null == theHaxeClass) return ArrayUtil.EMPTY_OBJECT_ARRAY; if (theHaxeClass instanceof HaxeAnonymousType) return ArrayUtil.EMPTY_OBJECT_ARRAY; if (theHaxeClass.hasModifierProperty(HaxePsiModifier.FINAL_META)) return ArrayUtil.EMPTY_OBJECT_ARRAY; final PsiFile inClassPsiFile = theHaxeClass.getContainingFile(); List<PsiClass> subTypeList = new ArrayList<PsiClass>(); // add the sub-types to this list, as they are found // ---- // search current file for sub-types that extend/implement from this class/type // final HaxeClass[] allHaxeClassesInFile = PsiTreeUtil.getChildrenOfType(inClassPsiFile, HaxeClass.class); if (allHaxeClassesInFile != null) { for (HaxeClass aClassInFile : allHaxeClassesInFile) { if (isThisTypeASubTypeOfTheSuperType(aClassInFile, theHaxeClass)) { subTypeList.add(aClassInFile); } } } // if private class, scope ends there if (theHaxeClass.hasModifierProperty(HaxePsiModifier.PRIVATE)) { // XXX: how about @:allow occurrences? return typeListToObjArray(((HaxeTypeHierarchyNodeDescriptor) descriptor), subTypeList); } // Get the list of subtypes from the file-based indices. Stub-based would // be faster, but we'll have to re-parent all of the PsiClass sub-classes. subTypeList.addAll(getSubTypes(theHaxeClass)); return typeListToObjArray(((HaxeTypeHierarchyNodeDescriptor) descriptor), subTypeList); }
Example #20
Source File: MoveChangesToAnotherListAction.java From consulo with Apache License 2.0 | 5 votes |
protected boolean isEnabled(@Nonnull AnActionEvent e) { Project project = e.getData(CommonDataKeys.PROJECT); if (project == null || !ProjectLevelVcsManager.getInstance(project).hasActiveVcss()) { return false; } return !VcsUtil.isEmpty(e.getData(ChangesListView.UNVERSIONED_FILES_DATA_KEY)) || !ArrayUtil.isEmpty(e.getData(VcsDataKeys.CHANGES)) || !ArrayUtil.isEmpty(e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)); }
Example #21
Source File: GlobalSearchScope.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public GlobalSearchScope uniteWith(@Nonnull GlobalSearchScope scope) { if (scope instanceof UnionScope) { GlobalSearchScope[] newScopes = ArrayUtil.mergeArrays(myScopes, ((UnionScope)scope).myScopes); return new UnionScope(newScopes); } return super.uniteWith(scope); }
Example #22
Source File: StartUseVcsDialog.java From consulo with Apache License 2.0 | 5 votes |
private Object[] prepareComboData() { final Collection<String> displayNames = myData.getVcses().keySet(); final List<String> keys = new ArrayList<String>(displayNames.size() + 1); keys.add(""); keys.addAll(displayNames); Collections.sort(keys); return ArrayUtil.toObjectArray(keys); }
Example #23
Source File: IntToIntSetMap.java From consulo with Apache License 2.0 | 5 votes |
public int[] get(int key) { if (mySingle.containsKey(key)) { return new int[]{mySingle.get(key)}; } TIntHashSet items = myMulti.get(key); if (items == null) return ArrayUtil.EMPTY_INT_ARRAY; return items.toArray(); }
Example #24
Source File: PtyCommandLine.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull public Process startProcessWithPty(@Nonnull List<String> commands, boolean console) throws IOException { Map<String, String> env = new HashMap<>(); setupEnvironment(env); if (isRedirectErrorStream()) { LOG.error("Launching process with PTY and redirected error stream is unsupported yet"); } String[] command = ArrayUtil.toStringArray(commands); File workDirectory = getWorkDirectory(); String directory = workDirectory != null ? workDirectory.getPath() : null; boolean cygwin = myUseCygwinLaunch && SystemInfo.isWindows; return PtyProcess.exec(command, env, directory, console, cygwin, getPtyLogFile()); }
Example #25
Source File: ShortBasedStorage.java From consulo with Apache License 2.0 | 5 votes |
@Override public void setData(int segmentIndex, int data) { if (segmentIndex >= myData.length) { myData = ArrayUtil.realloc(myData, calcCapacity(myData.length, segmentIndex)); } myData[segmentIndex] = (short)data; }
Example #26
Source File: LockFreeCOWSortedArray.java From consulo with Apache License 2.0 | 5 votes |
boolean remove(@Nonnull T listener) { while (true) { T[] oldListeners = listeners; T[] newListeners = ArrayUtil.remove(oldListeners, listener, arrayFactory); //noinspection ArrayEquality if (oldListeners == newListeners) return false; if (UPDATER.compareAndSet(this, oldListeners, newListeners)) break; } return true; }
Example #27
Source File: CSharpNameSuggestionProvider.java From consulo-csharp with Apache License 2.0 | 5 votes |
@Nullable @Override public SuggestedNameInfo getSuggestedNames(PsiElement element, @Nullable PsiElement nameSuggestionContext, Set<String> result) { if(element.getLanguage() != CSharpLanguage.INSTANCE) { return null; } Iterator<String> iterator = result.iterator(); while(iterator.hasNext()) { String next = iterator.next(); if(CSharpNameSuggesterUtil.isKeyword(next)) { iterator.remove(); } } if(element instanceof DotNetVariable) { Collection<String> names = CSharpNameSuggesterUtil.getSuggestedVariableNames((DotNetVariable) element); result.addAll(names); return new SuggestedNameInfo(ArrayUtil.toStringArray(names)) { }; } return null; }
Example #28
Source File: TempFileSystem.java From consulo with Apache License 2.0 | 5 votes |
@Override public String[] list() { String[] names = ArrayUtil.newStringArray(myChildren.size()); for (int i = 0; i < names.length; i++) { names[i] = myChildren.get(i).myName; } return names; }
Example #29
Source File: RangeBlinker.java From consulo with Apache License 2.0 | 5 votes |
private void removeHighlights() { MarkupModel markupModel = myEditor.getMarkupModel(); RangeHighlighter[] allHighlighters = markupModel.getAllHighlighters(); for (RangeHighlighter highlighter : myAddedHighlighters) { if (ArrayUtil.indexOf(allHighlighters, highlighter) != -1) { highlighter.dispose(); } } myAddedHighlighters.clear(); }
Example #30
Source File: LibraryRootsComponent.java From consulo with Apache License 2.0 | 5 votes |
private Object[] getSelectedElements() { if (myTreeBuilder == null || myTreeBuilder.isDisposed()) return ArrayUtil.EMPTY_OBJECT_ARRAY; final TreePath[] selectionPaths = myTreeBuilder.getTree().getSelectionPaths(); if (selectionPaths == null) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } List<Object> elements = new ArrayList<Object>(); for (TreePath selectionPath : selectionPaths) { final Object pathElement = getPathElement(selectionPath); if (pathElement != null) { elements.add(pathElement); } } return ArrayUtil.toObjectArray(elements); }