private boolean startProcessing() {
    LOG.assertTrue(Thread.holdsLock(myQueue));

    if (isProcessing || !myStarted) {
      return false;
    }
    isProcessing = true;
    final T item = myQueue.removeFirst();
    final Runnable runnable =
        () -> {
          if (myDeathCondition.value(null)) return;
          runSafely(() -> myProcessor.consume(item, myContinuationContext));
        };
    final Application application = ApplicationManager.getApplication();
    if (myThreadToUse == ThreadToUse.AWT) {
      final ModalityState state = myModalityState.remove(new MyOverrideEquals(item));
      if (state != null) {
        application.invokeLater(runnable, state);
      } else {
        application.invokeLater(runnable);
      }
    } else {
      application.executeOnPooledThread(runnable);
    }
    return true;
  }
  public static boolean isValidName(
      final Project project, final PsiElement psiElement, final String newName) {
    if (newName == null || newName.length() == 0) {
      return false;
    }
    final Condition<String> inputValidator =
        RenameInputValidatorRegistry.getInputValidator(psiElement);
    if (inputValidator != null) {
      return inputValidator.value(newName);
    }
    if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) {
      return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0;
    }
    if (psiElement instanceof PomTargetPsiElement) {
      return !StringUtil.isEmptyOrSpaces(newName);
    }

    final PsiFile file = psiElement.getContainingFile();
    final Language elementLanguage = psiElement.getLanguage();

    final Language fileLanguage = file == null ? null : file.getLanguage();
    Language language =
        fileLanguage == null
            ? elementLanguage
            : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage;

    return LanguageNamesValidation.INSTANCE
        .forLanguage(language)
        .isIdentifier(newName.trim(), project);
  }
  private static Condition<PsiElement> findFieldUsages(
      final PsiField psiField,
      final List<UsageInfo> usages,
      final PsiElement[] allElementsToDelete) {
    final Condition<PsiElement> isInsideDeleted = getUsageInsideDeletedFilter(allElementsToDelete);
    ReferencesSearch.search(psiField)
        .forEach(
            reference -> {
              if (!isInsideDeleted.value(reference.getElement())) {
                final PsiElement element = reference.getElement();
                final PsiElement parent = element.getParent();
                if (parent instanceof PsiAssignmentExpression
                    && element == ((PsiAssignmentExpression) parent).getLExpression()) {
                  usages.add(
                      new SafeDeleteFieldWriteReference(
                          (PsiAssignmentExpression) parent, psiField));
                } else {
                  TextRange range = reference.getRangeInElement();
                  usages.add(
                      new SafeDeleteReferenceJavaDeleteUsageInfo(
                          reference.getElement(),
                          psiField,
                          range.getStartOffset(),
                          range.getEndOffset(),
                          false,
                          PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class)
                              != null));
                }
              }

              return true;
            });

    return isInsideDeleted;
  }
  @Override
  public boolean processDeclarations(
      @NotNull PsiScopeProcessor processor,
      @NotNull ResolveState state,
      PsiElement lastParent,
      @NotNull PsiElement place) {
    GlobalSearchScope scope = place.getResolveScope();

    processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this);
    ElementClassHint classHint = processor.getHint(ElementClassHint.KEY);

    final JavaPsiFacade facade = getFacade();
    final Condition<String> prefixMatcher = processor.getHint(JavaCompletionHints.NAME_FILTER);

    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) {
      NameHint nameHint = processor.getHint(NameHint.KEY);
      if (nameHint != null) {
        final String shortName = nameHint.getName(state);
        if (containsClassNamed(shortName)
            && processClassesByName(processor, state, scope, shortName)) return false;
      } else if (prefixMatcher != null) {
        for (String className : getClassNamesCache()) {
          if (prefixMatcher.value(className)) {
            if (processClassesByName(processor, state, scope, className)) return false;
          }
        }
      } else {
        PsiClass[] classes = getClasses(scope);
        if (!processClasses(processor, state, classes)) return false;
      }
    }
    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.PACKAGE)) {
      NameHint nameHint = processor.getHint(NameHint.KEY);
      if (nameHint != null) {
        PsiPackage aPackage = findSubPackageByName(nameHint.getName(state));
        if (aPackage != null) {
          if (!processor.execute(aPackage, state)) return false;
        }
      } else {
        PsiPackage[] packs = getSubPackages(scope);
        for (PsiPackage pack : packs) {
          final String packageName = pack.getName();
          if (packageName == null) continue;
          if (!facade.getNameHelper().isIdentifier(packageName, PsiUtil.getLanguageLevel(this))) {
            continue;
          }
          if (!processor.execute(pack, state)) {
            return false;
          }
        }
      }
    }
    return true;
  }
    private Alignment getAlignment(ASTNode node) {
      IElementType elementType = node.getElementType();

      Condition<ASTNode> noneAlignmentCondition = myNoneAlignmentCondition.get(elementType);
      if (noneAlignmentCondition != null && noneAlignmentCondition.value(node)) {
        return null;
      }

      Alignment alignment = myAlignments.get(elementType);
      if (alignment == null) {
        return myDefaultAlignment;
      }
      return alignment == NO_ALIGNMENT ? null : alignment;
    }
  private static boolean checkDependants(
      final IdeaPluginDescriptor pluginDescriptor,
      final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor,
      final Condition<PluginId> check,
      final Set<PluginId> processed) {
    processed.add(pluginDescriptor.getPluginId());
    final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
    final Set<PluginId> optionalDependencies =
        new HashSet<PluginId>(Arrays.asList(pluginDescriptor.getOptionalDependentPluginIds()));
    for (final PluginId dependentPluginId : dependentPluginIds) {
      if (processed.contains(dependentPluginId)) continue;

      // TODO[yole] should this condition be a parameter?
      if (isModuleDependency(dependentPluginId)
          && (ourAvailableModules.isEmpty()
              || ourAvailableModules.contains(dependentPluginId.getIdString()))) {
        continue;
      }
      if (!optionalDependencies.contains(dependentPluginId)) {
        if (!check.value(dependentPluginId)) {
          return false;
        }
        final IdeaPluginDescriptor dependantPluginDescriptor =
            pluginId2Descriptor.fun(dependentPluginId);
        if (dependantPluginDescriptor != null
            && !checkDependants(dependantPluginDescriptor, pluginId2Descriptor, check, processed)) {
          return false;
        }
      }
    }
    return true;
  }
  public static void showDiffForChange(
      final Iterable<Change> changes,
      final Condition<Change> selectionChecker,
      final Project project,
      @NotNull ShowDiffUIContext context) {
    int newIndex = -1;
    ChangeForDiffConvertor convertor = new ChangeForDiffConvertor(project, true);
    final List<DiffRequestPresentable> changeList = ContainerUtil.newArrayList();
    for (Change change : changes) {
      if (!directoryOrBinary(change)) { // todo
        DiffRequestPresentable presentable = convertor.convert(change);
        if (presentable != null) {
          if ((newIndex == -1) && selectionChecker.value(change)) {
            newIndex = changeList.size();
          }
          changeList.add(presentable);
        }
      }
    }
    if (changeList.isEmpty()) {
      return;
    }
    if (newIndex < 0) {
      newIndex = 0;
    }

    showDiffImpl(project, changeList, newIndex, context);
  }
 public Fragment getSubfragmentAt(int offset, FragmentSide side, Condition<Fragment> condition) {
   LOG.assertTrue(
       getRange(side).getStartOffset() <= offset
           && offset < getRange(side).getEndOffset()
           && condition.value(this));
   return this;
 }
  public static void showDiffForChange(
      final Iterable<Change> changes,
      final Condition<Change> selectionChecker,
      final Project project,
      @NotNull ShowDiffUIContext context) {
    int cnt = 0;
    int newIndex = -1;
    final List<Change> changeList = new ArrayList<Change>();
    for (Change change : changes) {
      if (!directoryOrBinary(change)) { // todo
        changeList.add(change);
        if ((newIndex == -1) && selectionChecker.value(change)) {
          newIndex = cnt;
        }
        ++cnt;
      }
    }
    if (changeList.isEmpty()) {
      return;
    }
    if (newIndex < 0) {
      newIndex = 0;
    }

    showDiffImpl(
        project,
        ObjectsConvertor.convert(
            changeList, new ChangeForDiffConvertor(project, true), ObjectsConvertor.NOT_NULL),
        newIndex,
        context);
  }
  // TODO: Make it work for properties
  public Collection<DeclarationDescriptor> getJetCallableExtensions(
      @NotNull Condition<String> acceptedNameCondition,
      @NotNull JetSimpleNameExpression expression,
      @NotNull ResolveSession resolveSession,
      @NotNull GlobalSearchScope searchScope) {
    Collection<DeclarationDescriptor> resultDescriptors = new ArrayList<DeclarationDescriptor>();

    BindingContext context = ResolveSessionUtils.resolveToExpression(resolveSession, expression);
    JetExpression receiverExpression = expression.getReceiverExpression();

    if (receiverExpression != null) {
      JetType expressionType = context.get(BindingContext.EXPRESSION_TYPE, receiverExpression);
      JetScope scope = context.get(BindingContext.RESOLUTION_SCOPE, receiverExpression);

      if (expressionType != null && scope != null) {
        Collection<String> extensionFunctionsNames = getAllJetExtensionFunctionsNames(searchScope);

        Set<FqName> functionFQNs = new java.util.HashSet<FqName>();

        // Collect all possible extension function qualified names
        for (String name : extensionFunctionsNames) {
          if (acceptedNameCondition.value(name)) {
            Collection<PsiElement> extensionFunctions =
                getJetExtensionFunctionsByName(name, searchScope);

            for (PsiElement extensionFunction : extensionFunctions) {
              if (extensionFunction instanceof JetNamedFunction) {
                functionFQNs.add(JetPsiUtil.getFQName((JetNamedFunction) extensionFunction));
              } else if (extensionFunction instanceof PsiMethod) {
                FqName functionFQN =
                    JetFromJavaDescriptorHelper.getJetTopLevelDeclarationFQN(
                        (PsiMethod) extensionFunction);
                if (functionFQN != null) {
                  functionFQNs.add(functionFQN);
                }
              }
            }
          }
        }

        // Iterate through the function with attempt to resolve found functions
        for (FqName functionFQN : functionFQNs) {
          for (CallableDescriptor functionDescriptor :
              ExpressionTypingUtils.canFindSuitableCall(
                  functionFQN,
                  project,
                  receiverExpression,
                  expressionType,
                  scope,
                  resolveSession.getModuleConfiguration())) {

            resultDescriptors.add(functionDescriptor);
          }
        }
      }
    }

    return resultDescriptors;
  }
 public static void copyChildren(Element from, Element to, Condition<Element> filter) {
   final List<Element> list = from.getChildren();
   for (Element element : list) {
     if (filter.value(element)) {
       to.addContent((Element) element.clone());
     }
   }
 }
 public void unregisterQuickFix(@NotNull Condition<IntentionAction> condition) {
   for (Iterator<Pair<IntentionActionDescriptor, TextRange>> it = quickFixActionRanges.iterator();
       it.hasNext(); ) {
     Pair<IntentionActionDescriptor, TextRange> pair = it.next();
     if (condition.value(pair.first.getAction())) {
       it.remove();
     }
   }
 }
 @Nullable
 public static Element findChild(Element parent, final Condition<Element> filter) {
   final List<Element> list = parent.getChildren();
   for (Element e : list) {
     if (filter.value(e)) {
       return e;
     }
   }
   return null;
 }
 @Override
 @NonNls
 public String toString() {
   return "[runnable: "
       + runnable
       + "; state="
       + modalityState
       + (expired.value(null) ? "; expired" : "")
       + "] ";
 }
 @NotNull
 private static <T> Set<T> packCollection(
     @NotNull Collection<T> set, @NotNull Condition<T> condition) {
   final Set<T> result = new LinkedHashSet<T>();
   for (T t : set) {
     if (condition.value(t)) {
       result.add(t);
     }
   }
   return result;
 }
  private static void printImpl(
      JTree tree,
      Object root,
      Collection<String> strings,
      int level,
      boolean withSelection,
      @Nullable Condition<String> nodePrintCondition) {
    DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) root;

    final Object userObject = defaultMutableTreeNode.getUserObject();
    String nodeText;
    if (userObject != null) {
      nodeText = toString(userObject, null);
    } else {
      nodeText = "null";
    }

    if (nodePrintCondition != null && !nodePrintCondition.value(nodeText)) return;

    final StringBuilder buff = new StringBuilder();
    StringUtil.repeatSymbol(buff, ' ', level);

    final boolean expanded = tree.isExpanded(new TreePath(defaultMutableTreeNode.getPath()));
    if (!defaultMutableTreeNode.isLeaf()) {
      buff.append(expanded ? "-" : "+");
    }

    final boolean selected =
        tree.getSelectionModel().isPathSelected(new TreePath(defaultMutableTreeNode.getPath()));
    if (withSelection && selected) {
      buff.append("[");
    }

    buff.append(nodeText);

    if (withSelection && selected) {
      buff.append("]");
    }

    strings.add(buff.toString());

    int childCount = tree.getModel().getChildCount(root);
    if (expanded) {
      for (int i = 0; i < childCount; i++) {
        printImpl(
            tree,
            tree.getModel().getChild(root, i),
            strings,
            level + 1,
            withSelection,
            nodePrintCondition);
      }
    }
  }
 public boolean satisfies(@NotNull PsiElement element, @NotNull ResolveState state) {
   final String name = PsiUtilCore.getName(element);
   if (StringUtil.isNotEmpty(name) && (myMatcher == null || myMatcher.value(name))) {
     if (myFilter.isClassAcceptable(element.getClass())
         && myFilter.isAcceptable(
             new CandidateInfo(element, state.get(PsiSubstitutor.KEY)), myElement)) {
       return true;
     }
   }
   return false;
 }
Exemple #18
0
 private static boolean processClasses(
     @NotNull PsiScopeProcessor processor,
     @NotNull ResolveState state,
     @NotNull PsiClass[] classes,
     @NotNull Condition<String> nameCondition) {
   for (PsiClass aClass : classes) {
     String name = aClass.getName();
     if (name != null && nameCondition.value(name) && !processor.execute(aClass, state))
       return false;
   }
   return true;
 }
 private static void addSomeItems(
     LinkedHashSet<LookupElement> model,
     Iterator<LookupElement> iterator,
     Condition<LookupElement> stopWhen) {
   while (iterator.hasNext()) {
     LookupElement item = iterator.next();
     model.add(item);
     if (stopWhen.value(item)) {
       break;
     }
   }
 }
 public static void updateDependenciesOnDartPackagesLibrary(
     @NotNull final Project project,
     @NotNull final Condition<Module> moduleFilter,
     @NotNull final Library library) {
   for (Module module : ModuleManager.getInstance(project).getModules()) {
     if (moduleFilter.value(module)) {
       addDependencyOnDartPackagesLibrary(module, library);
     } else {
       removeDependencyOnDartPackagesLibrary(module);
     }
   }
 }
 @NotNull
 private IDevice[] getFilteredDevices(AndroidDebugBridge bridge) {
   final List<IDevice> filteredDevices = new ArrayList<IDevice>();
   for (IDevice device : bridge.getDevices()) {
     if (myFilter == null || myFilter.value(device)) {
       filteredDevices.add(device);
     }
   }
   // Do not filter launching cloud devices as they are just unselectable progress markers
   // that are replaced with the actual cloud devices as soon as they are up and the actual cloud
   // devices will be filtered above.
   return filteredDevices.toArray(new IDevice[filteredDevices.size()]);
 }
 public static void processFilesToRecompile(
     final CompileContext context,
     final ModuleChunk chunk,
     final Condition<JpsModule> moduleFilter,
     final FileProcessor processor)
     throws IOException {
   final BuildFSState fsState = context.getProjectDescriptor().fsState;
   for (ModuleBuildTarget target : chunk.getTargets()) {
     if (moduleFilter.value(target.getModule())) {
       fsState.processFilesToRecompile(context, target, processor);
     }
   }
 }
 private static int getDefaultOptionIndexFromSelectCondition(
     @Nullable Condition<AnAction> preselectActionCondition, @NotNull List<ActionItem> items) {
   int defaultOptionIndex = 0;
   if (preselectActionCondition != null) {
     for (int i = 0; i < items.size(); i++) {
       final AnAction action = items.get(i).getAction();
       if (preselectActionCondition.value(action)) {
         defaultOptionIndex = i;
         break;
       }
     }
   }
   return defaultOptionIndex;
 }
 public static List<Element> removeChildren(
     final Element element, final Condition<Element> filter) {
   List<Element> toRemove = new ArrayList<Element>();
   final List<Element> list = element.getChildren();
   for (Element e : list) {
     if (filter.value(e)) {
       toRemove.add(e);
     }
   }
   for (Element e : toRemove) {
     element.removeContent(e);
   }
   return toRemove;
 }
  public Collection<ClassDescriptor> getJetClassesDescriptors(
      @NotNull Condition<String> acceptedShortNameCondition, @NotNull KotlinCodeAnalyzer analyzer) {
    Collection<ClassDescriptor> classDescriptors = new ArrayList<ClassDescriptor>();

    for (String fqName : JetFullClassNameIndex.getInstance().getAllKeys(project)) {
      FqName classFQName = new FqName(fqName);
      if (acceptedShortNameCondition.value(classFQName.shortName().getName())) {
        classDescriptors.addAll(
            ResolveSessionUtils.getClassDescriptorsByFqName(analyzer, classFQName));
      }
    }

    return classDescriptors;
  }
Exemple #26
0
 @NotNull
 @Override
 public Collection<? extends CustomLiveTemplateLookupElement> getLookupElements(
     @NotNull PsiFile file, @NotNull Editor editor, int offset) {
   String key =
       computeTemplateKeyWithoutContextChecking(editor.getDocument().getCharsSequence(), offset);
   if (key != null) {
     Map<String, CustomLiveTemplateLookupElement> result = ContainerUtil.newHashMap();
     Condition<PostfixTemplate> isApplicationTemplateFunction =
         createIsApplicationTemplateFunction(key, file, editor);
     for (Map.Entry<String, PostfixTemplate> entry : myTemplates.entrySet()) {
       PostfixTemplate postfixTemplate = entry.getValue();
       if (entry.getKey().startsWith(key)
           && isApplicationTemplateFunction.value(postfixTemplate)) {
         result.put(
             postfixTemplate.getKey(),
             new PostfixTemplateLookupElement(
                 this, postfixTemplate, postfixTemplate.getKey(), false));
       }
     }
     return result.values();
   }
   return super.getLookupElements(file, editor, offset);
 }
 @NotNull
 public List<RunContentDescriptor> getRunningDescriptors(
     @NotNull Condition<RunnerAndConfigurationSettings> condition) {
   List<RunContentDescriptor> result = new SmartList<>();
   for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity :
       myRunningConfigurations) {
     if (trinity.getSecond() != null && condition.value(trinity.getSecond())) {
       ProcessHandler processHandler = trinity.getFirst().getProcessHandler();
       if (processHandler != null /*&& !processHandler.isProcessTerminating()*/
           && !processHandler.isProcessTerminated()) {
         result.add(trinity.getFirst());
       }
     }
   }
   return result;
 }
 public void update(AnActionEvent e) {
   final Presentation presentation = e.getPresentation();
   presentation.setEnabled(false);
   final TreePath[] selectionPath = myTree.getSelectionPaths();
   if (selectionPath != null) {
     Object[] nodes =
         ContainerUtil.map2Array(
             selectionPath,
             new Function<TreePath, Object>() {
               @Override
               public Object fun(TreePath treePath) {
                 return treePath.getLastPathComponent();
               }
             });
     if (!myCondition.value(nodes)) return;
     presentation.setEnabled(true);
   }
 }
 @Override
 public void run() {
   boolean b = invokeLaterScheduled.compareAndSet(true, false);
   assert b;
   if (stopped || myShutUpCondition.value(null)) {
     stop();
     return;
   }
   long start = System.currentTimeMillis();
   int processed = 0;
   while (processNext()) {
     processed++;
     long finish = System.currentTimeMillis();
     if (myMaxUnitOfWorkThresholdMs != -1 && finish - start > myMaxUnitOfWorkThresholdMs)
       break;
   }
   if (!isEmpty()) {
     scheduleUpdate();
   }
 }
 public static void addChildAfter(
     final Element parent,
     final Element child,
     final Condition<Element> filter,
     boolean addFirstIfNotFound) {
   List list = parent.getContent();
   for (int i = 0; i < list.size(); i++) {
     Object o = list.get(i);
     if (o instanceof Element && filter.value((Element) o)) {
       if (i < list.size() - 1) {
         parent.addContent(i + 1, child);
       } else {
         parent.addContent(child);
       }
       return;
     }
   }
   if (addFirstIfNotFound) {
     parent.addContent(0, child);
   }
 }