com.intellij.util.PairProcessor Java Examples

The following examples show how to use com.intellij.util.PairProcessor. 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: PatternCondition.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean processParameters(final PairProcessor<String, Object> processor) {
  for (Class aClass = getClass(); aClass != null; aClass = aClass.getSuperclass()) {
    for (final Field field : aClass.getDeclaredFields()) {
      if (!Modifier.isStatic(field.getModifiers()) &&
          (((field.getModifiers() & 0x1000 /*Modifer.SYNTHETIC*/) == 0 && !aClass.equals(PatternCondition.class))
           || field.getName().startsWith(PARAMETER_FIELD_PREFIX))) {
        final String name = field.getName();
        final String fixedName = name.startsWith(PARAMETER_FIELD_PREFIX) ?
                                 name.substring(PARAMETER_FIELD_PREFIX.length()) : name;
        final Object value = getFieldValue(field);
        if (!processor.process(fixedName, value)) return false;
      }
    }
  }
  return true;
}
 
Example #2
Source File: MembershipMap.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void optimizeMap(final PairProcessor<Val, Val> valuesAreas) {
  int i = 0;
  for (Iterator<Key> iterator = myKeys.iterator(); iterator.hasNext();) {
    final Key key = iterator.next();
    final Val value = myMap.get(key);

    // go for parents
    for (int j = i - 1; j >= 0; -- j) {
      final Key innerKey = myKeys.get(j);
      if (myKeysResemblance.process(innerKey, key)) {
        if (valuesAreas.process(myMap.get(innerKey), value)) {
          -- i;
          iterator.remove();
          myMap.remove(key);
        }
        // otherwise we found a "parent", and do not remove the child
        break;
      }
    }
    ++ i;
  }
}
 
Example #3
Source File: AreaMap.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void getSimiliar(final Key key, final PairProcessor<Key, Val> consumer) {
  final int idx = Collections.binarySearch(myKeys, key, myComparator);
  if (idx < 0) {
    final int insertionIdx = - idx - 1;
    // take item before
    final int itemBeforeIdx = insertionIdx - 1;
    if (itemBeforeIdx >= 0) {
      for (ListIterator<Key> iterator = myKeys.listIterator(itemBeforeIdx + 1); iterator.hasPrevious(); ) {
        final Key candidate = iterator.previous();
        if (! myKeysResemblance.process(candidate, key)) continue;
        if (consumer.process(candidate, myMap.get(candidate))) break;     // if need only a part of keys
      }
    }
  } else {
    consumer.process(key, myMap.get(key));
  }
}
 
Example #4
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public Runnable startNonCustomTemplates(final Map<TemplateImpl, String> template2argument, final Editor editor, @Nullable final PairProcessor<String, String> processor) {
  final int caretOffset = editor.getCaretModel().getOffset();
  final Document document = editor.getDocument();
  final CharSequence text = document.getCharsSequence();

  if (template2argument == null || template2argument.isEmpty()) {
    return null;
  }

  return () -> {
    if (template2argument.size() == 1) {
      TemplateImpl template = template2argument.keySet().iterator().next();
      String argument = template2argument.get(template);
      int templateStart = getTemplateStart(template, argument, caretOffset, text);
      startTemplateWithPrefix(editor, template, templateStart, processor, argument);
    }
    else {
      ListTemplatesHandler.showTemplatesLookup(myProject, editor, template2argument);
    }
  };
}
 
Example #5
Source File: QuerySearchRequest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public QuerySearchRequest(@Nonnull Query<PsiReference> query,
                          @Nonnull final SearchRequestCollector collector,
                          boolean inReadAction,
                          @Nonnull final PairProcessor<? super PsiReference, ? super SearchRequestCollector> processor) {
  this.query = query;
  this.collector = collector;
  if (inReadAction) {
    this.processor = new ReadActionProcessor<PsiReference>() {
      @Override
      public boolean processInReadAction(PsiReference psiReference) {
        return processor.process(psiReference, collector);
      }
    };
  }
  else {
    this.processor = psiReference -> processor.process(psiReference, collector);
  }
}
 
Example #6
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void startTemplateWithPrefix(final Editor editor,
                                    final TemplateImpl template,
                                    final int templateStart,
                                    @Nullable final PairProcessor<String, String> processor,
                                    @Nullable final String argument) {
  final int caretOffset = editor.getCaretModel().getOffset();
  final TemplateState templateState = initTemplateState(editor);
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(myProject, () -> {
    editor.getDocument().deleteString(templateStart, caretOffset);
    editor.getCaretModel().moveToOffset(templateStart);
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    editor.getSelectionModel().removeSelection();
    Map<String, String> predefinedVarValues = null;
    if (argument != null) {
      predefinedVarValues = new HashMap<>();
      predefinedVarValues.put(TemplateImpl.ARG, argument);
    }
    templateState.start(template, processor, predefinedVarValues);
  }, CodeInsightBundle.message("insert.code.template.command"), null);
}
 
Example #7
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Pair<PsiFile, Editor> chooseBetweenHostAndInjected(@Nonnull PsiFile hostFile,
                                                                 @Nonnull Editor hostEditor,
                                                                 @Nullable PsiFile injectedFile,
                                                                 @Nonnull PairProcessor<? super PsiFile, ? super Editor> predicate) {
  Editor editorToApply = null;
  PsiFile fileToApply = null;

  Editor injectedEditor = null;
  if (injectedFile != null) {
    injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, injectedFile);
    if (predicate.process(injectedFile, injectedEditor)) {
      editorToApply = injectedEditor;
      fileToApply = injectedFile;
    }
  }

  if (editorToApply == null && hostEditor != injectedEditor && predicate.process(hostFile, hostEditor)) {
    editorToApply = hostEditor;
    fileToApply = hostFile;
  }
  if (editorToApply == null) return null;
  return Pair.create(fileToApply, editorToApply);
}
 
Example #8
Source File: PatternCondition.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void appendParams(final StringBuilder builder, final String indent) {
  processParameters(new PairProcessor<String, Object>() {
    int count;
    String prevName;
    int prevOffset;

    @Override
    public boolean process(String name, Object value) {
      count ++;
      if (count == 2) builder.insert(prevOffset, prevName +"=");
      if (count > 1) builder.append(", ");
      prevOffset = builder.length();
      if (count > 1) builder.append(name).append("=");
      appendValue(builder, indent, value);
      prevName = name;
      return true;
    }
  });
}
 
Example #9
Source File: ConfigurationErrors.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void _do(@Nonnull final ConfigurationError error, @Nonnull final Project project,
                       @Nonnull final PairProcessor<ConfigurationErrors, ConfigurationError> fun) {
  if (!project.isInitialized()) {
    StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() {
       @Override
       public void run() {
         fun.process(project.getMessageBus().syncPublisher(TOPIC), error);
       }
     });

    return;
  }

  final MessageBus bus = project.getMessageBus();
  if (EventQueue.isDispatchThread()) fun.process(bus.syncPublisher(TOPIC), error);
  else {
    //noinspection SSBasedInspection
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        fun.process(bus.syncPublisher(TOPIC), error);
      }
    });
  }
}
 
Example #10
Source File: TreeElementPattern.java    From consulo with Apache License 2.0 6 votes vote down vote up
public Self withSuperParent(final int level, @Nonnull final ElementPattern<? extends ParentType> pattern) {
  return with(new PatternConditionPlus<T, ParentType>(level == 1 ? "withParent" : "withSuperParent", pattern) {

    @Override
    public boolean processValues(T t,
                                 ProcessingContext context,
                                 PairProcessor<ParentType, ProcessingContext> processor) {
      ParentType parent = t;
      for (int i = 0; i < level; i++) {
        if (parent == null) return true;
        parent = getParent(parent);
      }
      return processor.process(parent, context);
    }
  });
}
 
Example #11
Source File: VariableInplaceRenamer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void collectAdditionalElementsToRename(final List<Pair<PsiElement, TextRange>> stringUsages) {
  final String stringToSearch = myElementToRename.getName();
  final PsiFile currentFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
  if (stringToSearch != null) {
    TextOccurrencesUtil
      .processUsagesInStringsAndComments(myElementToRename, stringToSearch, true, new PairProcessor<PsiElement, TextRange>() {
        @Override
        public boolean process(PsiElement psiElement, TextRange textRange) {
          if (psiElement.getContainingFile() == currentFile) {
            stringUsages.add(Pair.create(psiElement, textRange));
          }
          return true;
        }
      });
  }
}
 
Example #12
Source File: TextOccurrencesUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean processUsagesInStringsAndComments(@Nonnull final PsiElement element,
                                                        @Nonnull final String stringToSearch,
                                                        final boolean ignoreReferences,
                                                        @Nonnull final PairProcessor<PsiElement, TextRange> processor) {
  PsiSearchHelper helper = PsiSearchHelper.SERVICE.getInstance(element.getProject());
  SearchScope scope = helper.getUseScope(element);
  scope = GlobalSearchScope.projectScope(element.getProject()).intersectWith(scope);
  Processor<PsiElement> commentOrLiteralProcessor = new Processor<PsiElement>() {
    @Override
    public boolean process(PsiElement literal) {
      return processTextIn(literal, stringToSearch, ignoreReferences, processor);
    }
  };
  return processStringLiteralsContainingIdentifier(stringToSearch, scope, helper, commentOrLiteralProcessor) &&
         helper.processCommentsContainingIdentifier(stringToSearch, scope, commentOrLiteralProcessor);
}
 
Example #13
Source File: TextOccurrencesUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void addUsagesInStringsAndComments(@Nonnull PsiElement element,
                                                 @Nonnull String stringToSearch,
                                                 @Nonnull final Collection<UsageInfo> results,
                                                 @Nonnull final UsageInfoFactory factory) {
  final Object lock = new Object();
  processUsagesInStringsAndComments(element, stringToSearch, false, new PairProcessor<PsiElement, TextRange>() {
    @Override
    public boolean process(PsiElement commentOrLiteral, TextRange textRange) {
      UsageInfo usageInfo = factory.createUsageInfo(commentOrLiteral, textRange.getStartOffset(), textRange.getEndOffset());
      if (usageInfo != null) {
        synchronized (lock) {
          results.add(usageInfo);
        }
      }
      return true;
    }
  });
}
 
Example #14
Source File: ConfigurationErrors.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void removeError(@Nonnull final ConfigurationError error, @Nonnull final Project project) {
  _do(error, project, new PairProcessor<ConfigurationErrors, ConfigurationError>() {
    @Override
    public boolean process(final ConfigurationErrors configurationErrors, final ConfigurationError configurationError) {
      configurationErrors.removeError(configurationError);
      return false;
    }
  });
}
 
Example #15
Source File: FileUtilTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveAncestors() throws Exception {
  final String[] arr = {"/a/b/c", "/a", "/a/b", "/d/e", "/b/c", "/a/d", "/b/c/ttt", "/a/ewq.euq"};
  final String[] expectedResult = {"/a","/b/c","/d/e"};
  @SuppressWarnings("unchecked") final Collection<String> result = FileUtil.removeAncestors(Arrays.asList(arr), Convertor.SELF, PairProcessor.TRUE);
  assertArrayEquals(expectedResult, ArrayUtil.toStringArray(result));
}
 
Example #16
Source File: ConfigurationErrors.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void addError(@Nonnull final ConfigurationError error, @Nonnull final Project project) {
  _do(error, project, new PairProcessor<ConfigurationErrors, ConfigurationError>() {
    @Override
    public boolean process(final ConfigurationErrors configurationErrors, final ConfigurationError configurationError) {
      configurationErrors.addError(configurationError);
      return false;
    }
  });
}
 
Example #17
Source File: NavBarModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected List<Object> getChildren(final Object object) {
  final List<Object> result = new ArrayList<>();
  PairProcessor<Object, NavBarModelExtension> processor = (o, ext) -> {
    ContainerUtil.addIfNotNull(result, o instanceof PsiElement && ext.normalizeChildren() ? normalize((PsiElement)o) : o);
    return true;
  };

  processChildrenWithExtensions(object, processor);

  result.sort(new SiblingsComparator());
  return result;
}
 
Example #18
Source File: NavBarModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean processChildrenWithExtensions(Object object, @Nonnull PairProcessor<Object, NavBarModelExtension> pairProcessor) {
  if (!isValid(object)) return true;
  final Object rootElement = size() > 1 ? getElement(1) : null;
  if (rootElement != null && !isValid(rootElement)) return true;

  for (NavBarModelExtension modelExtension : NavBarModelExtension.EP_NAME.getExtensionList()) {
    if (!modelExtension.processChildren(object, rootElement, o -> pairProcessor.process(o, modelExtension))) return false;
  }
  return true;
}
 
Example #19
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void startTemplateWithPrefix(final Editor editor, final TemplateImpl template, @Nullable final PairProcessor<String, String> processor, @Nullable String argument) {
  final int caretOffset = editor.getCaretModel().getOffset();
  String key = template.getKey();
  int startOffset = caretOffset - key.length();
  if (argument != null) {
    if (!isDelimiter(key.charAt(key.length() - 1))) {
      // pass space
      startOffset--;
    }
    startOffset -= argument.length();
  }
  startTemplateWithPrefix(editor, template, startOffset, processor, argument);
}
 
Example #20
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void startTemplate(final Editor editor,
                           final String selectionString,
                           final Template template,
                           boolean inSeparateCommand,
                           TemplateEditingListener listener,
                           final PairProcessor<String, String> processor,
                           final Map<String, String> predefinedVarValues) {
  final TemplateState templateState = initTemplateState(editor);

  //noinspection unchecked
  templateState.getProperties().put(ExpressionContext.SELECTION, selectionString);

  if (listener != null) {
    templateState.addTemplateStateListener(listener);
  }
  Runnable r = () -> {
    if (selectionString != null) {
      ApplicationManager.getApplication().runWriteAction(() -> EditorModificationUtil.deleteSelectedText(editor));
    }
    else {
      editor.getSelectionModel().removeSelection();
    }
    templateState.start((TemplateImpl)template, processor, predefinedVarValues);
  };
  if (inSeparateCommand) {
    CommandProcessor.getInstance().executeCommand(myProject, r, CodeInsightBundle.message("insert.code.template.command"), null);
  }
  else {
    r.run();
  }

  if (shouldSkipInTests()) {
    if (!templateState.isFinished()) templateState.gotoEnd(false);
  }
}
 
Example #21
Source File: CachesHolder.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void iterateAllRepositoryLocations(final PairProcessor<RepositoryLocation, AbstractVcs> locationProcessor) {
  final AbstractVcs[] vcses = myPlManager.getAllActiveVcss();
  for (AbstractVcs vcs : vcses) {
    final CommittedChangesProvider provider = vcs.getCommittedChangesProvider();
    if (provider instanceof CachingCommittedChangesProvider) {
      final Map<VirtualFile, RepositoryLocation> map = getAllRootsUnderVcs(vcs);
      for (VirtualFile root : map.keySet()) {
        final RepositoryLocation location = map.get(root);
        if (! Boolean.TRUE.equals(locationProcessor.process(location, vcs))) {
          return;
        }
      }
    }
  }
}
 
Example #22
Source File: JavaClassQualifiedNameReference.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static PatternCondition<PsiElementBase> nameCondition(final ElementPattern pattern) {
  return new PatternConditionPlus<PsiElementBase, String>("_withPsiName", pattern) {
    @Override
    public boolean processValues(
        PsiElementBase t,
        ProcessingContext context,
        PairProcessor<String, ProcessingContext> processor) {
      return processor.process(t.getName(), context);
    }
  };
}
 
Example #23
Source File: ObjectPattern.java    From consulo with Apache License 2.0 5 votes vote down vote up
public Self and(final ElementPattern pattern) {
  return with(new PatternConditionPlus<T, T>("and", pattern) {
    @Override
    public boolean processValues(T t, ProcessingContext context, PairProcessor<T, ProcessingContext> processor) {
      return processor.process(t, context);
    }
  });
}
 
Example #24
Source File: TreeElementPattern.java    From consulo with Apache License 2.0 5 votes vote down vote up
public Self withChildren(@Nonnull final ElementPattern<Collection<ParentType>> pattern) {
  return with(new PatternConditionPlus<T, Collection<ParentType>>("withChildren", pattern) {
    @Override
    public boolean processValues(T t,
                                 ProcessingContext context,
                                 PairProcessor<Collection<ParentType>, ProcessingContext> processor) {
      return processor.process(Arrays.asList(getChildren(t)), context);
    }
  });
}
 
Example #25
Source File: TreeElementPattern.java    From consulo with Apache License 2.0 5 votes vote down vote up
public Self inside(final boolean strict, @Nonnull final ElementPattern<? extends ParentType> pattern) {
  return with(new PatternConditionPlus<T, ParentType>("inside", pattern) {
    @Override
    public boolean processValues(T t,
                                 ProcessingContext context,
                                 PairProcessor<ParentType, ProcessingContext> processor) {
      ParentType element = strict ? getParent(t) : t;
      while (element != null) {
        if (!processor.process(element, context)) return false;
        element = getParent(element);
      }
      return true;
    }
  });
}
 
Example #26
Source File: PsiElementPattern.java    From consulo with Apache License 2.0 5 votes vote down vote up
public Self withTextLength(@Nonnull final ElementPattern lengthPattern) {
  return with(new PatternConditionPlus<T, Integer>("withTextLength", lengthPattern) {
    @Override
    public boolean processValues(T t,
                                 ProcessingContext context,
                                 PairProcessor<Integer, ProcessingContext> integerProcessingContextPairProcessor) {
      return integerProcessingContextPairProcessor.process(t.getTextLength(), context);
    }
  });
}
 
Example #27
Source File: PsiElementPattern.java    From consulo with Apache License 2.0 5 votes vote down vote up
private PatternCondition<T> _withText(final ElementPattern pattern) {
  return new PatternConditionPlus<T, String>("_withText", pattern) {
    @Override
    public boolean processValues(T t,
                                 ProcessingContext context,
                                 PairProcessor<String, ProcessingContext> processor) {
      return processor.process(t.getText(), context);
    }
  };
}
 
Example #28
Source File: SoftArrayHashMap.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean processLeafEntries(final PairProcessor<T, V> processor) {
  if (myValuesMap != null) {
    for (T t : myValuesMap.keySet()) {
      if (!processor.process(t, myValuesMap.get(t))) return false;
    }
  }
  if (myContinuationMap != null) {
    for (SoftArrayHashMap<T, V> map : myContinuationMap.values()) {
      if (!map.processLeafEntries(processor)) return false;
    }
  }
  return true;
}
 
Example #29
Source File: CollectionModelEditor.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void processModifiedItems(@Nonnull final PairProcessor<T, T> processor) {
  // don't want to expose TObjectObjectProcedure - avoid implementation details
  helper.process(new TObjectObjectProcedure<T, T>() {
    @Override
    public boolean execute(T newItem, T oldItem) {
      return processor.process(newItem, oldItem);
    }
  });
}
 
Example #30
Source File: PsiTreeUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean treeWalkUp(@Nonnull final PsiElement entrance, @Nullable final PsiElement maxScope, PairProcessor<PsiElement, PsiElement> eachScopeAndLastParent) {
  PsiElement prevParent = null;
  PsiElement scope = entrance;

  while (scope != null) {
    if (!eachScopeAndLastParent.process(scope, prevParent)) return false;

    if (scope == maxScope) break;
    prevParent = scope;
    scope = prevParent.getContext();
  }

  return true;

}