Java Code Examples for com.intellij.util.ArrayUtil

The following examples show how to use com.intellij.util.ArrayUtil. These examples are extracted from open source projects. 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 Project: consulo   Source File: LoadTextUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 2
Source Project: litho   Source File: SpecMethodFindUsagesHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: litho   Source File: GeneratedClassFindUsagesHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: consulo   Source File: GutterIntentionMenuContributor.java    License: Apache License 2.0 6 votes vote down vote up
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 5
Source Project: consulo   Source File: StubBasedPsiElementBase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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 6
Source Project: intellij-haxe   Source File: HaxeAnnotationTest.java    License: Apache License 2.0 6 votes vote down vote up
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 7
Source Project: consulo-csharp   Source File: CS1722.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: consulo   Source File: VirtualDirectoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 9
Source Project: consulo   Source File: IntentionSettingsTree.java    License: Apache License 2.0 6 votes vote down vote up
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 10
Source Project: consulo   Source File: RunAnythingChooseContextAction.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
Source Project: consulo   Source File: CachedValuesManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 12
@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 13
Source Project: consulo   Source File: KeymapImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 14
Source Project: intellij-haxe   Source File: HaxeRenameTest.java    License: Apache License 2.0 6 votes vote down vote up
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 15
@Before
@Override
public void setUp() throws Exception {
  super.setUp();
  ensureTempDirCreated();

  myTestDir = new File(ourTempDir, getTestName(false));
  FileUtil.ensureExists(myTestDir);

  setUpFixtures();
  myProject = myTestFixture.getProject();

  EdtTestUtil.runInEdtAndWait(() -> ApplicationManager.getApplication().runWriteAction(() -> {
    try {
      setUpInWriteAction();
    }
    catch (Throwable e) {
      try {
        tearDown();
      }
      catch (Exception e1) {
        e1.printStackTrace();
      }
      throw new RuntimeException(e);
    }
  }));

  List<String> allowedRoots = new ArrayList<>();
  collectAllowedRoots(allowedRoots);
  if (!allowedRoots.isEmpty()) {
    VfsRootAccess.allowRootAccess(myTestFixture.getTestRootDisposable(), ArrayUtil.toStringArray(allowedRoots));
  }
}
 
Example 16
Source Project: leetcode-editor   Source File: HttpRequests.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public CharSequence readChars(@Nullable ProgressIndicator indicator) throws IOException {
    BufferExposingByteArrayOutputStream byteStream = doReadBytes(indicator);
    if (byteStream.size() == 0) {
        return ArrayUtil.EMPTY_CHAR_SEQUENCE;
    }
    else {
        return getCharset().decode(ByteBuffer.wrap(byteStream.getInternalBuffer(), 0, byteStream.size()));
    }
}
 
Example 17
@NotNull
@Override
public String[] getNames(Project project, boolean b) {
    if(!Symfony2ProjectComponent.isEnabled(project)) {
        return new String[0];
    }

    Set<String> routeNames = new HashSet<>();
    for (SymfonyCommand symfonyCommand : SymfonyCommandUtil.getCommands(project)) {
        routeNames.add(symfonyCommand.getName());
    }

    return ArrayUtil.toStringArray(routeNames);
}
 
Example 18
Source Project: consulo   Source File: AbstractTreeClassChooserDialog.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String[] getNames(boolean checkBoxState) {
  if (!myFastMode) {
    return myInheritorsProvider.getNames();
  }
  final List<String> names = new ArrayList<String>();

  myFastMode = myInheritorsProvider.searchForInheritorsOfBaseClass().forEach(new Processor<T>() {
    private int count;

    @Override
    public boolean process(T aClass) {
      if (count++ > 1000) {
        return false;
      }
      if ((getTreeClassChooserDialog().getFilter().isAccepted(aClass)) && aClass.getName() != null) {
        names.add(aClass.getName());
      }
      return true;
    }
  });
  if (!myFastMode) {
    return getNames(checkBoxState);
  }
  if ((getTreeClassChooserDialog().getFilter().isAccepted(myInheritorsProvider.getBaseClass())) && myInheritorsProvider.getBaseClass().getName() != null) {
    names.add(myInheritorsProvider.getBaseClass().getName());
  }
  return ArrayUtil.toStringArray(names);
}
 
Example 19
Source Project: reasonml-idea-plugin   Source File: ParserState.java    License: MIT License 5 votes vote down vote up
@Nullable
public ParserScope popEndUntilOneOfElementType(@NotNull ORTokenElementType... scopeElementTypes) {
    ParserScope scope = null;

    if (!m_scopes.isEmpty()) {
        scope = m_scopes.peek();
        while (scope != null && !ArrayUtil.contains(scope.getScopeTokenElementType(), scopeElementTypes)) {
            popEnd();
            scope = getLatestScope();
        }
    }

    return scope;
}
 
Example 20
Source Project: consulo   Source File: VirtualFileImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public byte[] contentsToByteArray() throws IOException {
  if (myFileInfo == null) {
    throw new UnsupportedOperationException();
  }

  VirtualFile localFile = myFileInfo.getLocalFile();
  if (localFile != null) {
    return localFile.contentsToByteArray();
  }
  return ArrayUtil.EMPTY_BYTE_ARRAY;
}
 
Example 21
@Override
public XmlAttributeDescriptor[] getAttributesDescriptors(@Nullable XmlTag context) {
    Collection<XmlAttributeDescriptor> attributeDescriptors = new ArrayList<>();

    viewHelper.arguments.forEach((s, viewHelperArgument) -> {
        attributeDescriptors.add(new ViewHelperArgumentDescriptor(viewHelper, viewHelperArgument));
    });

    final XmlAttributeDescriptor[] commonAttributes = HtmlNSDescriptorImpl.getCommonAttributeDescriptors(context);

    return ArrayUtil.mergeArrays(attributeDescriptors.toArray(new XmlAttributeDescriptor[0]), commonAttributes);
}
 
Example 22
Source Project: consulo   Source File: LazyParseablePsiElement.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
protected <T> T[] findChildrenByClass(Class<T> aClass) {
  List<T> result = new ArrayList<>();
  for (PsiElement cur = getFirstChild(); cur != null; cur = cur.getNextSibling()) {
    if (aClass.isInstance(cur)) result.add((T)cur);
  }
  return result.toArray(ArrayUtil.newArray(aClass, result.size()));
}
 
Example 23
Source Project: consulo-csharp   Source File: CS1722.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public HighlightInfoFactory checkImpl(@Nonnull CSharpLanguageVersion languageVersion, @Nonnull CSharpHighlightContext highlightContext, @Nonnull DotNetTypeList element)
{
	if(element.getNode().getElementType() != CSharpStubElements.EXTENDS_LIST)
	{
		return null;
	}

	CSharpTypeDeclaration resolvedElement = null;
	DotNetType baseType = null;
	DotNetType[] types = element.getTypes();

	for(DotNetType type : types)
	{
		DotNetTypeRef typeRef = type.toTypeRef();
		PsiElement temp = typeRef.resolve().getElement();
		if(temp instanceof CSharpTypeDeclaration && !((CSharpTypeDeclaration) temp).isInterface())
		{
			resolvedElement = (CSharpTypeDeclaration) temp;
			baseType = type;
			break;
		}
	}

	if(baseType == null)
	{
		return null;
	}
	int i = ArrayUtil.indexOf(types, baseType);
	if(i != 0)
	{
		CSharpTypeDeclaration parent = (CSharpTypeDeclaration) element.getParent();
		return newBuilder(baseType, formatElement(parent), formatElement(resolvedElement)).addQuickFix(new MoveToFirstPositionFix(baseType));
	}
	return null;
}
 
Example 24
Source Project: consulo   Source File: ModuleRootLayerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String[] getContentRootUrls() {
  if (getContent().isEmpty()) return ArrayUtil.EMPTY_STRING_ARRAY;
  final ArrayList<String> result = new ArrayList<>(getContent().size());

  for (ContentEntry contentEntry : getContent()) {
    result.add(contentEntry.getUrl());
  }

  return ArrayUtil.toStringArray(result);
}
 
Example 25
Source Project: consulo   Source File: EditorSearchSession.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private String getEmptyText() {
  if (myFindModel.isGlobal() || !myFindModel.getStringToFind().isEmpty()) return "";
  String text = getEditor().getSelectionModel().getSelectedText();
  if (text != null && text.contains("\n")) {
    boolean replaceState = myFindModel.isReplaceState();
    AnAction action = ActionManager.getInstance().getAction(replaceState ? IdeActions.ACTION_REPLACE : IdeActions.ACTION_TOGGLE_FIND_IN_SELECTION_ONLY);
    Shortcut shortcut = ArrayUtil.getFirstElement(action.getShortcutSet().getShortcuts());
    if (shortcut != null) {
      return ApplicationBundle.message("editorsearch.in.selection.with.hint", KeymapUtil.getShortcutText(shortcut));
    }
  }
  return ApplicationBundle.message("editorsearch.in.selection");
}
 
Example 26
Source Project: consulo   Source File: DefaultInspectionToolPresentation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isProblemResolved(RefEntity refEntity, CommonProblemDescriptor descriptor) {
  if (descriptor == null) return true;
  for (RefEntity entity : getIgnoredElements().keySet()) {
    if (Comparing.equal(entity, refEntity)) {
      final CommonProblemDescriptor[] descriptors = getIgnoredElements().get(refEntity);
      return ArrayUtil.contains(descriptor, descriptors);
    }
  }
  return false;
}
 
Example 27
Source Project: consulo   Source File: RowIcon.java    License: Apache License 2.0 5 votes vote down vote up
protected RowIcon(RowIcon icon) {
  super(icon);
  myAlignment = icon.myAlignment;
  myWidth = icon.myWidth;
  myHeight = icon.myHeight;
  myIcons = ArrayUtil.copyOf(icon.myIcons);
  myScaledIcons = null;
}
 
Example 28
Source Project: consulo-csharp   Source File: CSharpStubVariableImplUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static DotNetVariable getPrevVariable(@Nonnull CSharpStubVariableImpl<?> variable)
{
	if(isMultipleDeclaration(variable))
	{
		CSharpVariableDeclStub<?> stub = variable.getStub();
		if(stub != null)
		{
			StubElement<?> parentStub = stub.getParentStub();
			PsiElement[] stubVariables = parentStub.getChildrenByType(variable.getElementType(), PsiElement.ARRAY_FACTORY);

			int i = ArrayUtil.find(stubVariables, variable);
			if(i <= 0)
			{
				LOGGER.error("Variable dont have type but dont second");
				return null;
			}

			return (DotNetVariable) stubVariables[i - 1];
		}
		else
		{
			CSharpStubVariableImpl<?> prevVariable = PsiTreeUtil.getPrevSiblingOfType(variable, variable.getClass());
			if(prevVariable == null)
			{
				LOGGER.error("Variable dont have type but dont second");
				return null;
			}
			return prevVariable;
		}
	}
	return null;
}
 
Example 29
Source Project: consulo   Source File: JDOMUtil.java    License: Apache License 2.0 5 votes vote down vote up
@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 30
Source Project: consulo   Source File: DirectoryChooser.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@RequiredReadAction
private static PsiDirectory getDefaultSelection(PsiDirectory[] directories, Project project) {
  final String defaultSelectionPath = PropertiesComponent.getInstance(project).getValue(DEFAULT_SELECTION);
  if (defaultSelectionPath != null) {
    final VirtualFile directoryByDefault = LocalFileSystem.getInstance().findFileByPath(defaultSelectionPath);
    if (directoryByDefault != null) {
      final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(directoryByDefault);
      return directory != null && ArrayUtil.find(directories, directory) > -1 ? directory : null;
    }
  }
  return null;
}