Java Code Examples for com.intellij.util.ArrayUtil

The following are top voted examples for showing how to use com.intellij.util.ArrayUtil. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yii2support   File: CompletionContributor.java   View source code 7 votes vote down vote up
@Override
public boolean invokeAutoPopup(@NotNull PsiElement position, char typeChar) {
    MethodReference reference = PsiTreeUtil.getParentOfType(position, MethodReference.class);
    if (reference != null && ArrayUtil.contains(reference.getName(), ViewsUtil.renderMethods)) {
        if (typeChar == '\'' || typeChar == '"') {
            if (position instanceof LeafPsiElement && position.getText().equals("$view")) {
                return true;
            }
            if (position.getNextSibling() instanceof ParameterList) {
                return true;
            }
        }
    }

    return false;
}
 
Example 2
Project: hybris-integration-intellij-idea-plugin   File: DefaultSearchScopeConfigurator.java   View source code 6 votes vote down vote up
private static void addOrReplaceScopes(@NotNull Project project, @NotNull List<NamedScope> newScopes) {
    final Set<String> newScopeNames = newScopes
        .stream()
        .map(NamedScope::getName)
        .collect(Collectors.toSet());

    final NamedScopeManager namedScopeManager = NamedScopeManager.getInstance(project);
    final NamedScope[] existingScopes = namedScopeManager.getEditableScopes();

    final NamedScope[] filteredScopes = Arrays
        .stream(existingScopes)
        .filter(it -> !newScopeNames.contains(it.getName()))
        .toArray(NamedScope[]::new);

    namedScopeManager.setScopes(ArrayUtil.mergeArrays(
        filteredScopes,
        newScopes.toArray(new NamedScope[newScopes.size()])
    ));
}
 
Example 3
Project: hybris-integration-intellij-idea-plugin   File: AbstractSelectModulesToImportStep.java   View source code 6 votes vote down vote up
protected boolean validateCommon() throws ConfigurationException {
    final Set<HybrisModuleDescriptor> moduleDuplicates = this.calculateSelectedModuleDuplicates();
    final Collection<String> moduleDuplicateNames = newHashSet(moduleDuplicates.size());

    for (HybrisModuleDescriptor moduleDuplicate : moduleDuplicates) {
        moduleDuplicateNames.add(this.getModuleNameAndPath(moduleDuplicate));
    }

    if (!moduleDuplicates.isEmpty()) {
        throw new ConfigurationException(
            HybrisI18NBundleUtils.message(
                "hybris.project.import.duplicate.projects.found",
                StringUtil.join(ArrayUtil.toStringArray(moduleDuplicateNames), "\n")
            ),
            HybrisI18NBundleUtils.message("hybris.project.error")
        );
    }

    return true;
}
 
Example 4
Project: hybris-integration-intellij-idea-plugin   File: HybrisModelItemReference.java   View source code 6 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(final boolean incompleteCode) {
    final Project project = myElement.getProject();
    final String modelName = PATTERN.matcher(myElement.getText()).replaceAll("");

    final String javaModelName = modelName + JAVA_MODEL_SUFFIX;
    final String jaloModelName = modelName;

    final PsiClass[] javaModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName(
        javaModelName, GlobalSearchScope.allScope(project)
    );

    final PsiClass[] jaloModelClasses = PsiShortNamesCache.getInstance(project).getClassesByName(
        jaloModelName, GlobalSearchScope.projectScope(project)
    );

    final PsiClass[] psiClasses = ArrayUtil.mergeArrays(javaModelClasses, jaloModelClasses);
    return PsiElementResolveResult.createResults(psiClasses);
}
 
Example 5
Project: intellij-ce-playground   File: SearchableOptionsRegistrarImpl.java   View source code 6 votes vote down vote up
private synchronized void putOptionWithHelpId(@NotNull String option,
                                              @NotNull final String id,
                                              @Nullable final String groupName,
                                              @Nullable String hit,
                                              @Nullable final String path) {
  if (isStopWord(option)) return;
  String stopWord = PorterStemmerUtil.stem(option);
  if (stopWord == null) return;
  if (isStopWord(stopWord)) return;

  long[] configs = myStorage.get(option);
  long packed = pack(id, hit, path, groupName);
  if (configs == null) {
    configs = new long[] {packed};
  }
  else {
    configs = ArrayUtil.indexOf(configs, packed) == -1 ? ArrayUtil.append(configs, packed) : configs;
  }
  myStorage.put(ByteArrayCharSequence.convertToBytesIfAsciiString(option), configs);
}
 
Example 6
Project: intellij-ce-playground   File: AndroidApt.java   View source code 6 votes vote down vote up
@NotNull
private static String[] getNonEmptyExistingDirs(@NotNull String[] dirs) {
  final List<String> result = new ArrayList<String>();
  for (String dirPath : dirs) {
    final File dir = new File(dirPath);

    if (dir.isDirectory()) {
      final File[] children = dir.listFiles();

      if (children != null && children.length > 0) {
        result.add(dirPath);
      }
    }
  }
  return ArrayUtil.toStringArray(result);
}
 
Example 7
Project: intellij-ce-playground   File: ModuleGroupUtil.java   View source code 6 votes vote down vote up
public static <T> T updateModuleGroupPath(final ModuleGroup group,
                                          T parentNode,
                                          final Function<ModuleGroup, T> needToCreateNode,
                                          final Consumer<ParentChildRelation<T>> insertNode,
                                          final Function<ModuleGroup, T> createNewNode) {
  final ArrayList<String> path = new ArrayList<String>();
  final String[] groupPath = group.getGroupPath();
  for (String pathElement : groupPath) {
    path.add(pathElement);
    final ModuleGroup moduleGroup = new ModuleGroup(ArrayUtil.toStringArray(path));
    T moduleGroupNode = needToCreateNode.fun(moduleGroup);
    if (moduleGroupNode == null) {
      moduleGroupNode = createNewNode.fun(moduleGroup);
      insertNode.consume(new ParentChildRelation<T>(parentNode, moduleGroupNode));
    }
    parentNode = moduleGroupNode;
  }
  return parentNode;
}
 
Example 8
Project: intellij-ce-playground   File: PyFunctionBuilder.java   View source code 6 votes vote down vote up
/**
 * Creates builder copying signature and doc from another one.
 *
 * @param source                  what to copy
 * @param decoratorsToCopyIfExist list of decorator names to be copied to new function.
 * @return builder configured by this function
 */
@NotNull
public static PyFunctionBuilder copySignature(@NotNull final PyFunction source, @NotNull final String... decoratorsToCopyIfExist) {
  final String name = source.getName();
  final PyFunctionBuilder functionBuilder = new PyFunctionBuilder((name != null) ? name : "", source);
  for (final PyParameter parameter : source.getParameterList().getParameters()) {
    final String parameterName = parameter.getName();
    if (parameterName != null) {
      functionBuilder.parameter(parameterName);
    }
  }
  final PyDecoratorList decoratorList = source.getDecoratorList();
  if (decoratorList != null) {
    for (final PyDecorator decorator : decoratorList.getDecorators()) {
      final String decoratorName = decorator.getName();
      if (decoratorName != null) {
        if (ArrayUtil.contains(decoratorName, decoratorsToCopyIfExist)) {
          functionBuilder.decorate(decoratorName);
        }
      }
    }
  }
  functionBuilder.myDocStringGenerator = PyDocstringGenerator.forDocStringOwner(source);
  return functionBuilder;
}
 
Example 9
Project: intellij-ce-playground   File: ExternalSystemTestCase.java   View source code 6 votes vote down vote up
public void registerAllowedRoots(List<String> roots, @NotNull Disposable disposable) {
  final List<String> newRoots = new ArrayList<String>(roots);
  newRoots.removeAll(myAllowedRoots);

  final String[] newRootsArray = ArrayUtil.toStringArray(newRoots);
  VfsRootAccess.allowRootAccess(newRootsArray);
  myAllowedRoots.addAll(newRoots);

  Disposer.register(disposable, new Disposable() {
    @Override
    public void dispose() {
      VfsRootAccess.disallowRootAccess(newRootsArray);
      myAllowedRoots.removeAll(newRoots);
    }
  });
}
 
Example 10
Project: intellij-ce-playground   File: PyImportedModuleType.java   View source code 6 votes vote down vote up
public Object[] getCompletionVariants(String completionPrefix, PsiElement location, ProcessingContext context) {
  final List<LookupElement> result = new ArrayList<LookupElement>();
  final PsiElement resolved = myImportedModule.resolve();
  if (resolved instanceof PyFile) {
    final PyModuleType moduleType = new PyModuleType((PyFile)resolved, myImportedModule);
    result.addAll(moduleType.getCompletionVariantsAsLookupElements(location, context, false, false));
  }
  else if (resolved instanceof PsiDirectory) {
    final PsiDirectory dir = (PsiDirectory)resolved;
    if (PyUtil.isPackage(dir, location)) {
      if (ResolveImportUtil.getPointInImport(location) != PointInImport.NONE) {
        result.addAll(PyModuleType.getSubModuleVariants(dir, location, null));
      }
      else {
        result.addAll(PyModuleType.collectImportedSubmodulesAsLookupElements(dir, location, context.get(CTX_NAMES)));
      }
    }
  }
  return ArrayUtil.toObjectArray(result);
}
 
Example 11
Project: intellij-ce-playground   File: JavaGotoSuperHandler.java   View source code 6 votes vote down vote up
@NotNull
private PsiElement[] findSuperElements(@NotNull PsiFile file, int offset) {
  PsiElement element = getElement(file, offset);
  if (element == null) return PsiElement.EMPTY_ARRAY;

  final PsiElement psiElement = PsiTreeUtil.getParentOfType(element, PsiFunctionalExpression.class, PsiMember.class);
  if (psiElement instanceof PsiFunctionalExpression) {
    final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(psiElement);
    if (interfaceMethod != null) {
      return ArrayUtil.prepend(interfaceMethod, interfaceMethod.findSuperMethods(false));
    }
  }

  final PsiNameIdentifierOwner parent = PsiTreeUtil.getNonStrictParentOfType(element, PsiMethod.class, PsiClass.class);
  if (parent == null) {
    return PsiElement.EMPTY_ARRAY;
  }

  return FindSuperElementsHelper.findSuperElements(parent);
}
 
Example 12
Project: intellij-ce-playground   File: DeviceChooser.java   View source code 6 votes vote down vote up
private void refreshTable() {
  IDevice[] devices = myDetectedDevicesRef.get();
  myDisplayedDevices = devices;

  final IDevice[] selectedDevices = getSelectedDevices();
  final TIntArrayList selectedRows = new TIntArrayList();
  for (int i = 0; i < devices.length; i++) {
    if (ArrayUtil.indexOf(selectedDevices, devices[i]) >= 0) {
      selectedRows.add(i);
    }
  }

  myProcessSelectionFlag = false;
  myDeviceTable.setModel(new MyDeviceTableModel(devices));
  if (selectedRows.size() == 0 && devices.length > 0) {
    myDeviceTable.getSelectionModel().setSelectionInterval(0, 0);
  }
  for (int selectedRow : selectedRows.toNativeArray()) {
    if (selectedRow < devices.length) {
      myDeviceTable.getSelectionModel().addSelectionInterval(selectedRow, selectedRow);
    }
  }
  fireSelectedDevicesChanged();
  myProcessSelectionFlag = true;
}
 
Example 13
Project: intellij-ce-playground   File: MostlySingularMultiMap.java   View source code 6 votes vote down vote up
public boolean remove(@NotNull K key, @NotNull V value) {
  Object current = myMap.get(key);
  if (current == null) {
    return false;
  }
  if (current instanceof Object[]) {
    Object[] curArr = (Object[])current;
    Object[] newArr = ArrayUtil.remove(curArr, value, ArrayUtil.OBJECT_ARRAY_FACTORY);
    myMap.put(key, newArr);
    return newArr.length == curArr.length-1;
  }

  if (value.equals(current)) {
    myMap.remove(key);
    return true;
  }

  return false;
}
 
Example 14
Project: intellij-ce-playground   File: GridCaptionPanel.java   View source code 6 votes vote down vote up
public int[] getSelectedCells(@Nullable final Point dragOrigin) {
  ArrayList<Integer> selection = new ArrayList<Integer>();
  RadContainer container = getSelectedGridContainer();
  if (container == null) {
    return ArrayUtil.EMPTY_INT_ARRAY;
  }
  int size = getCellCount();
  for(int i=0; i<size; i++) {
    if (mySelectionModel.isSelectedIndex(i)) {
      selection.add(i);
    }
  }
  if (selection.size() == 0 && dragOrigin != null) {
    int cell = getCellAt(dragOrigin);
    if (cell >= 0) {
      return new int[] { cell };
    }
  }
  int[] result = new int[selection.size()];
  for(int i=0; i<selection.size(); i++) {
    result [i] = selection.get(i).intValue();
  }
  return result;
}
 
Example 15
Project: intellij-ce-playground   File: ApkStep.java   View source code 6 votes vote down vote up
@NotNull
private static String[] parseAndCheckProguardCfgPaths(@NotNull String pathsStr) {
  if (pathsStr.length() == 0) {
    return ArrayUtil.EMPTY_STRING_ARRAY;
  }
  final String[] paths = pathsStr.split(File.pathSeparator);

  if (paths.length == 0) {
    return ArrayUtil.EMPTY_STRING_ARRAY;
  }
  for (String path : paths) {
    if (LocalFileSystem.getInstance().refreshAndFindFileByPath(path) == null) {
      return ArrayUtil.EMPTY_STRING_ARRAY;
    }
  }
  return paths;
}
 
Example 16
Project: intellij-ce-playground   File: AndroidDataSourcePropertiesDialog.java   View source code 6 votes vote down vote up
private void updateDataBases() {
  if (!myPanel.isShowing()) return;
  final Object selectedItem = myDeviceComboBox.getSelectedItem();
  IDevice selectedDevice = selectedItem instanceof IDevice ? (IDevice)selectedItem : null;

  if (selectedDevice == null) {
    myDatabaseMap.clear();
    myPackageNameComboBox.setModel(new DefaultComboBoxModel());
    myDataBaseComboBox.setModel(new DefaultComboBoxModel());
  }
  else if (!selectedDevice.equals(mySelectedDevice)) {
    loadDatabases(selectedDevice);
    myPackageNameComboBox.setModel(new DefaultComboBoxModel(ArrayUtil.toStringArray(myDatabaseMap.keySet())));
    updateDbCombo();
  }
  mySelectedDevice = selectedDevice;
}
 
Example 17
Project: epigraph   File: SchemaQnReferenceResolver.java   View source code 6 votes vote down vote up
@NotNull
public ResolveResult[] multiResolve(@NotNull Project project) {
  List<ResolveResult> typeDefs =
      SchemaIndexUtil.findTypeDefs(project, prefixes, suffix, searchScope).stream()
      .filter(Objects::nonNull)
      .map(PsiElementResolveResult::new)
      .collect(Collectors.toList());

  // see comment in `resolve` above re. namespace declaration reference

  Qn prefix = input;
  int prefixLength = prefix.size();
  List<SchemaNamespaceDecl> namespaceDecls = resolveNamespaces(project, prefix);

  ResolveResult[] namespaces = namespaceDecls.stream()
      .map(ns -> new PsiElementResolveResult(getTargetSegment(ns, prefixLength)))
      .toArray(ResolveResult[]::new);

  return ArrayUtil.mergeArrays(typeDefs.toArray(new ResolveResult[typeDefs.size()]), namespaces);
}
 
Example 18
Project: intellij-ce-playground   File: JavaFxPropertyAttributeDescriptor.java   View source code 6 votes vote down vote up
@Nullable
@Override
public String[] getEnumeratedValues() {
  final PsiClass enumClass = getEnum();
  if (enumClass != null) {
    final PsiField[] fields = enumClass.getFields();
    final List<String> enumConstants = new ArrayList<String>();
    for (PsiField enumField : fields) {
      if (isConstant(enumField)) {
        enumConstants.add(enumField.getName());
      }
    }
    return ArrayUtil.toStringArray(enumConstants);
  }

  final String propertyQName = getBoxedPropertyType(getDeclaration());
  if (CommonClassNames.JAVA_LANG_FLOAT.equals(propertyQName) || CommonClassNames.JAVA_LANG_DOUBLE.equals(propertyQName)) {
    return new String[] {"Infinity", "-Infinity", "NaN",  "-NaN"};
  } else if (CommonClassNames.JAVA_LANG_BOOLEAN.equals(propertyQName)) {
    return new String[] {"true", "false"};
  }

  return null;
}
 
Example 19
Project: intellij-ce-playground   File: Win32FsCache.java   View source code 6 votes vote down vote up
@NotNull
String[] list(@NotNull String path) {
  FileInfo[] fileInfo = myKernel.listChildren(path);
  if (fileInfo == null || fileInfo.length == 0) {
    return ArrayUtil.EMPTY_STRING_ARRAY;
  }

  if (!StringUtil.endsWithChar(path, '/')) path += "/";
  String[] names = new String[fileInfo.length];
  Map<String, FileAttributes> map = getMap();
  for (int i = 0, length = fileInfo.length; i < length; i++) {
    FileInfo info = fileInfo[i];
    String name = info.getName();
    map.put(path + name, info.toFileAttributes());
    names[i] = name;
  }
  return names;
}
 
Example 20
Project: intellij-ce-playground   File: AbstractTreeClassChooserDialog.java   View source code 6 votes vote down vote up
@NotNull
@Override
public Object[] getElementsByName(String name, FindSymbolParameters parameters, @NotNull ProgressIndicator canceled) {
  String patternName = parameters.getLocalPatternName();
  List<T> classes = myTreeClassChooserDialog.getClassesByName(
    name, parameters.isSearchInLibraries(), patternName, myTreeClassChooserDialog.getScope()
  );
  if (classes.size() == 0) return ArrayUtil.EMPTY_OBJECT_ARRAY;
  if (classes.size() == 1) {
    return isAccepted(classes.get(0)) ? ArrayUtil.toObjectArray(classes) : ArrayUtil.EMPTY_OBJECT_ARRAY;
  }
  Set<String> qNames = ContainerUtil.newHashSet();
  List<T> list = new ArrayList<T>(classes.size());
  for (T aClass : classes) {
    if (qNames.add(getFullName(aClass)) && isAccepted(aClass)) {
      list.add(aClass);
    }
  }
  return ArrayUtil.toObjectArray(list);
}
 
Example 21
Project: intellij-ce-playground   File: KeyFMapTest.java   View source code 6 votes vote down vote up
private static void doTestGetKeys(int size) {
  List<Key> keys = ContainerUtil.newArrayList();
  List<Object> values = ContainerUtil.newArrayList();
  for (int i = 0; i < size; i++) {
    keys.add(Key.create("Key#" + i));
    values.add("Value#" + i);
  }

  KeyFMap map = createKeyFMap(keys, values);

  Key[] actualKeys = map.getKeys();

  assertEquals(size, actualKeys.length);

  for (Key key : keys) {
    assertTrue("Key not found: " + key, ArrayUtil.contains(key, actualKeys));
  }
}
 
Example 22
Project: intellij-ce-playground   File: FindManagerTest.java   View source code 6 votes vote down vote up
public void testFindInFileUnderLibraryUnderProject() {
  initProject("libUnderProject", "src");
  String libDir = JavaTestUtil.getJavaTestDataPath() + "/find/libUnderProject/lib";
  PsiTestUtil.addLibrary(myModule, "lib", libDir, new String[]{""}, ArrayUtil.EMPTY_STRING_ARRAY);

  FindModel findModel = new FindModel();
  findModel.setStringToFind("TargetWord");
  findModel.setFromCursor(false);
  findModel.setGlobal(true);
  findModel.setMultipleFiles(true);

  findModel.setWholeWordsOnly(false);
  assertSize(2, findUsages(findModel));

  findModel.setWholeWordsOnly(true);
  assertSize(2, findUsages(findModel));
}
 
Example 23
Project: intellij-ce-playground   File: PyClassRefactoringUtil.java   View source code 6 votes vote down vote up
/**
 * Searches for references inside some element (like {@link com.jetbrains.python.psi.PyAssignmentStatement}, {@link com.jetbrains.python.psi.PyFunction} etc
 * and stored them.
 * After that you can add element to some new parent. Newly created element then should be processed via {@link #restoreNamedReferences(com.intellij.psi.PsiElement)}
 * and all references would be restored.
 *
 * @param element     element to store references for
 * @param namesToSkip if reference inside of element has one of this names, it will not be saved.
 */
public static void rememberNamedReferences(@NotNull final PsiElement element, @NotNull final String... namesToSkip) {
  element.acceptChildren(new PyRecursiveElementVisitor() {
    @Override
    public void visitPyReferenceExpression(PyReferenceExpression node) {
      super.visitPyReferenceExpression(node);
      if (PsiTreeUtil.getParentOfType(node, PyImportStatementBase.class) != null) {
        return;
      }
      final NameDefiner importElement = getImportElement(node);
      if (importElement != null && PsiTreeUtil.isAncestor(element, importElement, false)) {
        return;
      }
      if (!ArrayUtil.contains(node.getText(), namesToSkip)) { //Do not remember name if it should be skipped
        rememberReference(node, element);
      }
    }
  });
}
 
Example 24
Project: intellij-ce-playground   File: XmlLocationCompletionContributor.java   View source code 6 votes vote down vote up
private static Object[] completeSchemaLocation(PsiElement element) {
  XmlTag tag = (XmlTag)element.getParent().getParent();
  XmlAttribute[] attributes = tag.getAttributes();
  final PsiReference[] refs = element.getReferences();
  return ContainerUtil.mapNotNull(attributes, new Function<XmlAttribute, Object>() {
    @Override
    public Object fun(final XmlAttribute attribute) {
      final String attributeValue = attribute.getValue();
      return attributeValue != null &&
             attribute.isNamespaceDeclaration() &&
             ContainerUtil.find(refs, new Condition<PsiReference>() {
               @Override
               public boolean value(PsiReference ref) {
                 return ref.getCanonicalText().equals(attributeValue);
               }
             }) == null ? attributeValue + " " : null;
    }
  }, ArrayUtil.EMPTY_OBJECT_ARRAY);
}
 
Example 25
Project: yii2support   File: Patterns.java   View source code 5 votes vote down vote up
public static Capture<MethodReference> methodWithName(String... methodNames) {
    return new Capture<>(new InitialPatternCondition<MethodReference>(MethodReference.class) {
        @Override
        public boolean accepts(@Nullable Object o, ProcessingContext context) {
            if (o instanceof MethodReference) {
                String methodReferenceName = ((MethodReference) o).getName();
                return methodReferenceName != null && ArrayUtil.contains(methodReferenceName, methodNames);
            }
            return super.accepts(o, context);
        }
    });
}
 
Example 26
Project: yii2support   File: ClassUtils.java   View source code 5 votes vote down vote up
/**
 * Get index for PsiElement which is child in ArrayCreationExpression or Method
 * @param psiElement
 * @return
 */
public static int indexForElementInParameterList(PsiElement psiElement) {
    PsiElement parent = psiElement.getParent();
    if (parent == null) {
        return -1;
    }

    if (parent instanceof ParameterList) {
        return ArrayUtil.indexOf(((ParameterList) parent).getParameters(), psiElement);
    }

    return indexForElementInParameterList(parent);
}
 
Example 27
Project: nullability-annotations-inspection   File: AddPackageInfoWithNullabilityDefaultsFix.java   View source code 5 votes vote down vote up
private void removeRedundantAnnotations(PsiModifierListOwner element,
                                        List<String> redundantAnnotations,
                                        Set<PsiAnnotation.TargetType> targetsForDefaultAnnotation) {
    PsiAnnotation.TargetType[] targetTypes = getTargetsForLocation(element.getModifierList());
    boolean isTargeted = targetsForDefaultAnnotation.isEmpty()
            || ContainerUtil.intersects(targetsForDefaultAnnotation, Arrays.asList(targetTypes));
    if (isTargeted) {
        removePhysicalAnnotations(element, ArrayUtil.toStringArray(redundantAnnotations));
    }
}
 
Example 28
Project: educational-plugin   File: StudySubtaskUtils.java   View source code 5 votes vote down vote up
private static void updateOpenedTestFiles(@NotNull Project project,
                                          @NotNull VirtualFile taskDir,
                                          int fromTaskNumber,
                                          int toSubtaskNumber) {
  String fromSubtaskTestName = getTestFileName(project, fromTaskNumber);
  String toSubtaskTestName = getTestFileName(project, toSubtaskNumber);
  if (fromSubtaskTestName == null || toSubtaskTestName == null) {
    return;
  }
  VirtualFile fromTest = taskDir.findChild(fromSubtaskTestName);
  VirtualFile toTest = taskDir.findChild(toSubtaskTestName);
  if (fromTest == null || toTest == null) {
    return;
  }
  FileEditorManager editorManager = FileEditorManager.getInstance(project);
  if (editorManager.isFileOpen(fromTest)) {
    VirtualFile[] selectedFiles = editorManager.getSelectedFiles();
    boolean isSelected = ArrayUtil.contains(fromTest, selectedFiles);
    editorManager.closeFile(fromTest);
    editorManager.openFile(toTest, isSelected);
    if (!isSelected) {
      for (VirtualFile file : selectedFiles) {
        editorManager.openFile(file, true);
      }
    }
  }
}
 
Example 29
Project: intellij-ce-playground   File: JavaMemberNameCompletionContributor.java   View source code 5 votes vote down vote up
public static String[] completeVariableNameForRefactoring(JavaCodeStyleManager codeStyleManager,
                                                          final PrefixMatcher matcher,
                                                          @Nullable final PsiType varType,
                                                          final VariableKind varKind,
                                                          SuggestedNameInfo suggestedNameInfo,
                                                          final boolean includeOverlapped, final boolean methodPrefix) {
  Set<String> result = new LinkedHashSet<String>();
  final String[] suggestedNames = suggestedNameInfo.names;
  for (final String suggestedName : suggestedNames) {
    if (matcher.prefixMatches(suggestedName)) {
      result.add(suggestedName);
    }
  }

  if (!hasStartMatches(matcher, result) && PsiType.VOID != varType && includeOverlapped) {
    // use suggested names as suffixes
    final String requiredSuffix = codeStyleManager.getSuffixByVariableKind(varKind);
    final String prefix = matcher.getPrefix();
    if (varKind != VariableKind.STATIC_FINAL_FIELD || methodPrefix) {
      for (int i = 0; i < suggestedNames.length; i++) {
        suggestedNames[i] = codeStyleManager.variableNameToPropertyName(suggestedNames[i], varKind);
      }
    }

    ContainerUtil.addAll(result, getOverlappedNameVersions(prefix, suggestedNames, requiredSuffix));


  }
  return ArrayUtil.toStringArray(result);
}
 
Example 30
Project: intellij-ce-playground   File: RootModelBase.java   View source code 5 votes vote down vote up
@Override
@NotNull
public String[] getDependencyModuleNames() {
  List<String> result = orderEntries().withoutSdk().withoutLibraries().withoutModuleSourceEntries()
    .process(new CollectDependentModules(), new ArrayList<String>());
  return ArrayUtil.toStringArray(result);
}
 
Example 31
Project: intellij-ce-playground   File: AnchorReferenceImpl.java   View source code 5 votes vote down vote up
@Override
@NotNull
public Object[] getVariants() {
  final Map<String, XmlTag> idMap = getIdMap();
  if (idMap == null) return ArrayUtil.EMPTY_OBJECT_ARRAY;

  String[] variants = idMap.keySet().toArray(new String[idMap.size()]);
  LookupElement[] elements = new LookupElement[variants.length];
  for (int i = 0, variantsLength = variants.length; i < variantsLength; i++) {
    elements[i] = LookupElementBuilder.create(variants[i]).withCaseSensitivity(true);
  }
  return elements;
}
 
Example 32
Project: intellij-ce-playground   File: RngElementDescriptor.java   View source code 5 votes vote down vote up
@Override
public Object[] getDependences() {
  if (myDeclaration != null) {
    return ArrayUtil.append(myNsDescriptor.getDependences(), myDeclaration.getElement());
  } else {
    return myNsDescriptor.getDependences();
  }
}
 
Example 33
Project: intellij-ce-playground   File: GroovyCompletionData.java   View source code 5 votes vote down vote up
@NotNull
private static String[] addExtendsImplements(PsiElement context) {
  if (context.getParent() == null) {
    return ArrayUtil.EMPTY_STRING_ARRAY;
  }

  PsiElement elem = context.getParent();
  boolean ext = !(elem instanceof GrExtendsClause);
  boolean impl = !(elem instanceof GrImplementsClause);

  if (elem instanceof GrTypeDefinitionBody) { //inner class
    elem = PsiUtil.skipWhitespacesAndComments(context.getPrevSibling(), false);
  }
  else {
    if (elem instanceof GrReferenceExpression && PsiUtil.skipWhitespacesAndComments(elem.getPrevSibling(), false) instanceof GrTypeDefinition) {
      elem = PsiUtil.skipWhitespacesAndComments(elem.getPrevSibling(), false);
    }
    else if (elem.getParent() != null) {
      elem = PsiUtil.skipWhitespacesAndComments(elem.getParent().getPrevSibling(), false);
    }
  }

  ext &= elem instanceof GrInterfaceDefinition || elem instanceof GrClassDefinition || elem instanceof GrTraitTypeDefinition;
  impl &= elem instanceof GrEnumTypeDefinition || elem instanceof GrClassDefinition || elem instanceof GrTraitTypeDefinition;
  if (!ext && !impl) return ArrayUtil.EMPTY_STRING_ARRAY;

  PsiElement[] children = elem.getChildren();
  for (PsiElement child : children) {
    ext &= !(child instanceof GrExtendsClause && ((GrExtendsClause)child).getKeyword() != null);
    if (child instanceof GrImplementsClause && ((GrImplementsClause)child).getKeyword() != null || child instanceof GrTypeDefinitionBody) {
      return ArrayUtil.EMPTY_STRING_ARRAY;
    }
  }
  if (ext && impl) {
    return new String[]{PsiKeyword.EXTENDS, PsiKeyword.IMPLEMENTS};
  }

  return new String[]{ext ? PsiKeyword.EXTENDS : PsiKeyword.IMPLEMENTS};
}
 
Example 34
Project: intellij-ce-playground   File: CopyFilesOrDirectoriesHandler.java   View source code 5 votes vote down vote up
@Nullable
private static PsiDirectory tryNotNullizeDirectory(@NotNull Project project, @Nullable PsiDirectory defaultTargetDirectory) {
  if (defaultTargetDirectory == null) {
    VirtualFile root = ArrayUtil.getFirstElement(ProjectRootManager.getInstance(project).getContentRoots());
    if (root == null) root = project.getBaseDir();
    if (root == null) root = VfsUtil.getUserHomeDir();
    defaultTargetDirectory = root != null ? PsiManager.getInstance(project).findDirectory(root) : null;

    if (defaultTargetDirectory == null) {
      LOG.warn("No directory found for project: " + project.getName() +", root: " + root);
    }
  }
  return defaultTargetDirectory;
}
 
Example 35
Project: intellij-ce-playground   File: AndroidSourceGeneratingBuilder.java   View source code 5 votes vote down vote up
private static void collectResources(@NotNull File resFile,
                                     @NotNull String resType,
                                     @NotNull Map<String, ResourceFileData> resDataMap,
                                     @NotNull TObjectLongHashMap<String> valueResFilesTimestamps,
                                     @Nullable AndroidAptValidityState oldState)
  throws IOException {
  final String resFilePath = FileUtil.toSystemIndependentName(resFile.getPath());
  final long resFileTimestamp = resFile.lastModified();

  if (ResourceFolderType.VALUES.getName().equals(resType) && FileUtilRt.extensionEquals(resFile.getName(), "xml")) {
    ResourceFileData dataToReuse = null;

    if (oldState != null) {
      final long oldTimestamp = oldState.getValueResourceFilesTimestamps().get(resFilePath);

      if (resFileTimestamp == oldTimestamp) {
        dataToReuse = oldState.getResources().get(resFilePath);
      }
    }

    if (dataToReuse != null) {
      resDataMap.put(resFilePath, dataToReuse);
    }
    else {
      final List<ResourceEntry> entries = AndroidBuildDataCache.getInstance().getParsedValueResourceFile(resFile);
      resDataMap.put(resFilePath, new ResourceFileData(entries, 0));
    }
    valueResFilesTimestamps.put(resFilePath, resFileTimestamp);
  }
  else {
    final ResourceType resTypeObj = ResourceType.getEnum(resType);
    final boolean idProvidingType =
      resTypeObj != null && ArrayUtil.find(AndroidCommonUtils.ID_PROVIDING_RESOURCE_TYPES, resTypeObj) >= 0;
    final ResourceFileData data =
      new ResourceFileData(Collections.<ResourceEntry>emptyList(), idProvidingType ? resFileTimestamp : 0);
    resDataMap.put(resFilePath, data);
  }
}
 
Example 36
Project: intellij-ce-playground   File: TableLayoutSpanOperation.java   View source code 5 votes vote down vote up
@Override
protected Point getCellInfo() {
  RadTableLayoutComponent tableComponent = (RadTableLayoutComponent)myComponent.getParent().getParent();
  GridInfo gridInfo = tableComponent.getVirtualGridInfo();
  int row = tableComponent.getChildren().indexOf(myComponent.getParent());
  int column = ArrayUtil.indexOf(gridInfo.components[row], myComponent);

  return new Point(column, row);
}
 
Example 37
Project: intellij-ce-playground   File: TimestampStorage.java   View source code 5 votes vote down vote up
@NotNull
private static TimestampPerTarget[] updateTimestamp(TimestampPerTarget[] oldState, final int targetId, long timestamp) {
  final TimestampPerTarget newItem = new TimestampPerTarget(targetId, timestamp);
  if (oldState == null) {
    return new TimestampPerTarget[]{newItem};
  }
  for (int i = 0, length = oldState.length; i < length; i++) {
    if (oldState[i].targetId == targetId) {
      oldState[i] = newItem;
      return oldState;
    }
  }
  return ArrayUtil.append(oldState, newItem);
}
 
Example 38
Project: intellij-ce-playground   File: XmlUnusedNamespaceInspection.java   View source code 5 votes vote down vote up
private static void checkUnusedLocations(XmlAttribute attribute, ProblemsHolder holder, @NotNull XmlRefCountHolder refCountHolder) {
  if (XmlUtil.XML_SCHEMA_INSTANCE_URI.equals(attribute.getNamespace())) {
    if (XmlUtil.NO_NAMESPACE_SCHEMA_LOCATION_ATT.equals(attribute.getLocalName())) {
      if (refCountHolder.isInUse("")) return;
      holder.registerProblem(attribute, XmlBundle.message("xml.inspections.unused.schema.location"), ProblemHighlightType.LIKE_UNUSED_SYMBOL,
                             new RemoveNamespaceLocationFix(""));
    }
    else if (XmlUtil.SCHEMA_LOCATION_ATT.equals(attribute.getLocalName())) {
      XmlAttributeValue value = attribute.getValueElement();
      if (value == null) return;
      PsiReference[] references = value.getReferences();
      for (int i = 0, referencesLength = references.length; i < referencesLength; i++) {
        PsiReference reference = references[i];
        if (reference instanceof URLReference) {
          String ns = getNamespaceFromReference(reference);
          if (ArrayUtil.indexOf(attribute.getParent().knownNamespaces(), ns) == -1 && !refCountHolder.isUsedNamespace(ns)) {
            if (!XmlHighlightVisitor.hasBadResolve(reference, false)) {
              holder.registerProblemForReference(reference, ProblemHighlightType.LIKE_UNUSED_SYMBOL, XmlBundle.message("xml.inspections.unused.schema.location"),
                                                 new RemoveNamespaceLocationFix(ns));
            }
            for (int j = i + 1; j < referencesLength; j++) {
              PsiReference nextRef = references[j];
              if (nextRef instanceof URLReference) break;
              if (!XmlHighlightVisitor.hasBadResolve(nextRef, false)) {
                holder.registerProblemForReference(nextRef, ProblemHighlightType.LIKE_UNUSED_SYMBOL, XmlBundle.message("xml.inspections.unused.schema.location"),
                                                   new RemoveNamespaceLocationFix(ns));
              }
            }
          }
        }
      }
    }
  }
}
 
Example 39
Project: intellij-ce-playground   File: JavadocEditor.java   View source code 5 votes vote down vote up
@Override
public void saveData() {
  TableUtil.stopEditing(myTable);
  final int count = myTable.getRowCount();
  String[] urls = ArrayUtil.newStringArray(count);
  for (int row = 0; row < count; row++) {
    final TableItem item = ((MyTableModel)myTable.getModel()).getTableItemAt(row);
    urls[row] = item.getUrl();
  }
  getModel().getModuleExtension(JavaModuleExternalPaths.class).setJavadocUrls(urls);
}
 
Example 40
Project: intellij-ce-playground   File: CompositeShortNamesCache.java   View source code 5 votes vote down vote up
@Override
@NotNull
public String[] getAllClassNames() {
  Merger<String> merger = new Merger<String>();
  for (PsiShortNamesCache cache : myCaches) {
    String[] names = cache.getAllClassNames();
    merger.add(names);
  }
  String[] result = merger.getResult();
  return result != null ? result : ArrayUtil.EMPTY_STRING_ARRAY;
}