com.intellij.openapi.util.Conditions Java Examples

The following examples show how to use com.intellij.openapi.util.Conditions. 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: VcsSelectionHistoryDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Object getData(@Nonnull @NonNls Key<?> dataId) {
  if (CommonDataKeys.PROJECT == dataId) {
    return myProject;
  }
  else if (VcsDataKeys.VCS_VIRTUAL_FILE == dataId) {
    return myFile;
  }
  else if (VcsDataKeys.VCS_FILE_REVISION == dataId) {
    VcsFileRevision selectedObject = myList.getSelectedObject();
    return selectedObject instanceof CurrentRevision ? null : selectedObject;
  }
  else if (VcsDataKeys.VCS_FILE_REVISIONS == dataId) {
    List<VcsFileRevision> revisions = ContainerUtil.filter(myList.getSelectedObjects(), Conditions.notEqualTo(myLocalRevision));
    return ArrayUtil.toObjectArray(revisions, VcsFileRevision.class);
  }
  else if (VcsDataKeys.VCS == dataId) {
    return myActiveVcs.getKeyInstanceMethod();
  }
  else if (PlatformDataKeys.HELP_ID == dataId) {
    return myHelpId;
  }
  return null;
}
 
Example #2
Source File: CurrentBranchHighlighter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public VcsCommitStyle getStyle(@Nonnull VcsShortCommitDetails details, boolean isSelected) {
  if (isSelected || !myLogUi.isHighlighterEnabled(Factory.ID)) return VcsCommitStyle.DEFAULT;
  Condition<CommitId> condition = myConditions.get(details.getRoot());
  if (condition == null) {
    VcsLogProvider provider = myLogData.getLogProvider(details.getRoot());
    String currentBranch = provider.getCurrentBranch(details.getRoot());
    if (!HEAD.equals(mySingleFilteredBranch) && currentBranch != null && !(currentBranch.equals(mySingleFilteredBranch))) {
      condition = myLogData.getContainingBranchesGetter().getContainedInBranchCondition(currentBranch, details.getRoot());
      myConditions.put(details.getRoot(), condition);
    }
    else {
      condition = Conditions.alwaysFalse();
    }
  }
  if (condition != null && condition.value(new CommitId(details.getId(), details.getRoot()))) {
    return VcsCommitStyleFactory.background(CURRENT_BRANCH_BG);
  }
  return VcsCommitStyle.DEFAULT;
}
 
Example #3
Source File: ContainingBranchesGetter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public Condition<CommitId> getContainedInBranchCondition(@Nonnull final String branchName, @Nonnull final VirtualFile root) {
  LOG.assertTrue(EventQueue.isDispatchThread());

  DataPack dataPack = myLogData.getDataPack();
  if (dataPack == DataPack.EMPTY) return Conditions.alwaysFalse();

  PermanentGraph<Integer> graph = dataPack.getPermanentGraph();
  VcsLogRefs refs = dataPack.getRefsModel();

  ContainedInBranchCondition condition = myConditions.get(root);
  if (condition == null || !condition.getBranch().equals(branchName)) {
    VcsRef branchRef = ContainerUtil.find(refs.getBranches(),
                                          vcsRef -> vcsRef.getRoot().equals(root) && vcsRef.getName().equals(branchName));
    if (branchRef == null) return Conditions.alwaysFalse();
    condition = new ContainedInBranchCondition(graph.getContainedInBranchCondition(
      Collections.singleton(myLogData.getCommitIndex(branchRef.getCommitHash(), branchRef.getRoot()))), branchName);
    myConditions.put(root, condition);
  }
  return condition;
}
 
Example #4
Source File: InspectionEngine.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Map<String, List<ProblemDescriptor>> inspectEx(@Nonnull final List<LocalInspectionToolWrapper> toolWrappers,
                                                             @Nonnull final PsiFile file,
                                                             @Nonnull final InspectionManager iManager,
                                                             final boolean isOnTheFly,
                                                             boolean failFastOnAcquireReadAction,
                                                             @Nonnull final ProgressIndicator indicator) {
  if (toolWrappers.isEmpty()) return Collections.emptyMap();


  TextRange range = file.getTextRange();
  List<Divider.DividedElements> allDivided = new ArrayList<>();
  Divider.divideInsideAndOutsideAllRoots(file, range, range, Conditions.alwaysTrue(), new CommonProcessors.CollectProcessor<>(allDivided));

  List<PsiElement> elements = ContainerUtil.concat(
          (List<List<PsiElement>>)ContainerUtil.map(allDivided, d -> ContainerUtil.concat(d.inside, d.outside, d.parents)));

  return inspectElements(toolWrappers, file, iManager, isOnTheFly, failFastOnAcquireReadAction, indicator, elements,
                         calcElementDialectIds(elements));
}
 
Example #5
Source File: BaseProjectTreeBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public Promise<Object> revalidateElement(@Nonnull Object element) {
  if (!(element instanceof AbstractTreeNode)) {
    return Promises.rejectedPromise();
  }

  final AsyncPromise<Object> result = new AsyncPromise<>();
  AbstractTreeNode node = (AbstractTreeNode)element;
  final Object value = node.getValue();
  final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(ObjectUtils.tryCast(value, PsiElement.class));
  batch(indicator -> {
    final Ref<Object> target = new Ref<>();
    Promise<Object> callback = _select(element, virtualFile, true, Conditions.alwaysTrue());
    callback.onSuccess(it -> result.setResult(target.get())).onError(e -> result.setError(e));
  });
  return result;
}
 
Example #6
Source File: UpdaterTreeState.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void invalidateToSelectWithRefsToParent(DefaultMutableTreeNode actionNode) {
  if (actionNode != null) {
    Object readyElement = myUi.getElementFor(actionNode);
    if (readyElement != null) {
      Iterator<Object> toSelect = myToSelect.keySet().iterator();
      while (toSelect.hasNext()) {
        Object eachToSelect = toSelect.next();
        if (readyElement.equals(myUi.getTreeStructure().getParentElement(eachToSelect))) {
          List<Object> children = myUi.getLoadedChildrenFor(readyElement);
          if (!children.contains(eachToSelect)) {
            toSelect.remove();
            if (!myToSelect.containsKey(readyElement) && !myUi.getSelectedElements().contains(eachToSelect)) {
              addAdjustedSelection(eachToSelect, Conditions.alwaysFalse(), null);
            }
          }
        }
      }
    }
  }
}
 
Example #7
Source File: LogFilesManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void addLogConsoles(@Nonnull RunConfigurationBase runConfiguration, @Nullable ProcessHandler startedProcess) {
  for (LogFileOptions logFileOptions : runConfiguration.getAllLogFiles()) {
    if (logFileOptions.isEnabled()) {
      addConfigurationConsoles(logFileOptions, Conditions.<String>alwaysTrue(), logFileOptions.getPaths(), runConfiguration);
    }
  }
  runConfiguration.createAdditionalTabComponents(myManager, startedProcess);
}
 
Example #8
Source File: SdkComboBox.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Condition<Sdk> getSdkFilter(@Nullable final Condition<SdkTypeId> filter) {
  return filter == null ? Conditions.<Sdk>alwaysTrue() : new Condition<Sdk>() {
    @Override
    public boolean value(Sdk sdk) {
      return filter.value(sdk.getSdkType());
    }
  };
}
 
Example #9
Source File: BraceHighlightingHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
static EditorHighlighter getLazyParsableHighlighterIfAny(Project project, Editor editor, PsiFile psiFile) {
  if (!PsiDocumentManager.getInstance(project).isCommitted(editor.getDocument())) {
    return ((EditorEx)editor).getHighlighter();
  }
  PsiElement elementAt = psiFile.findElementAt(editor.getCaretModel().getOffset());
  for (PsiElement e : SyntaxTraverser.psiApi().parents(elementAt).takeWhile(Conditions.notEqualTo(psiFile))) {
    if (!(PsiUtilCore.getElementType(e) instanceof ILazyParseableElementType)) continue;
    Language language = ILazyParseableElementType.LANGUAGE_KEY.get(e.getNode());
    if (language == null) continue;
    TextRange range = e.getTextRange();
    final int offset = range.getStartOffset();
    SyntaxHighlighter syntaxHighlighter =
            SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, psiFile.getVirtualFile());
    LexerEditorHighlighter highlighter = new LexerEditorHighlighter(syntaxHighlighter, editor.getColorsScheme()) {
      @Nonnull
      @Override
      public HighlighterIterator createIterator(int startOffset) {
        return new HighlighterIteratorWrapper(super.createIterator(Math.max(startOffset - offset, 0))) {
          @Override
          public int getStart() {
            return super.getStart() + offset;
          }

          @Override
          public int getEnd() {
            return super.getEnd() + offset;
          }
        };
      }
    };
    highlighter.setText(editor.getDocument().getText(range));
    return highlighter;
  }
  return ((EditorEx)editor).getHighlighter();
}
 
Example #10
Source File: ReformatCodeAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Condition<CharSequence> getFileTypeMaskPattern(@Nullable String mask) {
  try {
    return FindInProjectUtil.createFileMaskCondition(mask);
  } catch (PatternSyntaxException e) {
    LOG.info("Error while processing file mask: ", e);
    return Conditions.alwaysTrue();
  }
}
 
Example #11
Source File: UsingNamespaceFix.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
private static void collectAvailableNamespaces(final CSharpReferenceExpression ref, Set<NamespaceReference> set, String referenceName)
{
	if(ref.getQualifier() != null)
	{
		return;
	}
	Collection<DotNetTypeDeclaration> tempTypes;
	Collection<DotNetLikeMethodDeclaration> tempMethods;

	PsiElement parent = ref.getParent();
	if(parent instanceof CSharpAttribute)
	{
		final Condition<DotNetTypeDeclaration> cond = typeDeclaration -> DotNetInheritUtil.isAttribute(typeDeclaration);

		tempTypes = getTypesWithGeneric(ref, referenceName);
		collect(set, tempTypes, cond);

		tempTypes = getTypesWithGeneric(ref, referenceName + AttributeByNameSelector.AttributeSuffix);
		collect(set, tempTypes, cond);
	}
	else
	{
		tempTypes = getTypesWithGeneric(ref, referenceName);

		collect(set, tempTypes, Conditions.<DotNetTypeDeclaration>alwaysTrue());

		tempMethods = MethodIndex.getInstance().get(referenceName, ref.getProject(), ref.getResolveScope());

		collect(set, tempMethods, method -> (method.getParent() instanceof DotNetNamespaceDeclaration || method.getParent() instanceof PsiFile) && method instanceof CSharpMethodDeclaration && (
				(CSharpMethodDeclaration) method).isDelegate());
	}
}
 
Example #12
Source File: CSharpFilePropertyPusher.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public void persistAttribute(@Nonnull Project project, @Nonnull VirtualFile virtualFile, @Nonnull CSharpFileAttribute newAttribute) throws IOException
{
	DataInputStream inputStream = ourFileAttribute.readAttribute(virtualFile);
	if(inputStream != null)
	{
		try
		{
			CSharpFileAttribute oldAttribute = CSharpFileAttribute.read(inputStream);
			if(oldAttribute.equals(newAttribute))
			{
				return;
			}
		}
		catch(IOException e)
		{
			inputStream.close();
		}
	}

	if(newAttribute != CSharpFileAttribute.DEFAULT || inputStream != null)
	{
		try (DataOutputStream oStream = ourFileAttribute.writeAttribute(virtualFile))
		{
			CSharpFileAttribute.write(oStream, newAttribute);
		}

		PushedFilePropertiesUpdater.getInstance(project).filePropertiesChanged(virtualFile, Conditions.alwaysTrue());
	}
}
 
Example #13
Source File: GitStatusWidget.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public ListPopup getPopupStep() {
  if (visible.get() && rootActions.update()) {
    String title = ResBundle.message("statusBar.status.menu.title");
    return new StatusActionGroupPopup(title, rootActions, myProject, Conditions.alwaysTrue());
  } else {
    return null;
  }
}
 
Example #14
Source File: SdksConfigurable.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
protected ArrayList<AnAction> createActions(final boolean fromPopup) {
  final ArrayList<AnAction> actions = new ArrayList<AnAction>();
  DefaultActionGroup group = new DefaultActionGroup(ProjectBundle.message("add.action.name"), true);
  group.getTemplatePresentation().setIcon(IconUtil.getAddIcon());
  mySdksModel.createAddActions(group, myTree, projectJdk -> {
    addNode(new MyNode(new SdkConfigurable(((SdkImpl)projectJdk), mySdksModel, TREE_UPDATER, myHistory, myProject), false), myRoot);
    selectNodeInTree(findNodeByObject(myRoot, projectJdk));
  }, SdkListConfigurable.ADD_SDK_FILTER);
  actions.add(new MyActionGroupWrapper(group));
  actions.add(new MyDeleteAction(forAll(Conditions.alwaysTrue())));
  return actions;
}
 
Example #15
Source File: TransferToEDTQueue.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static TransferToEDTQueue<Runnable> createRunnableMerger(@Nonnull @NonNls String name, int maxUnitOfWorkThresholdMs) {
  return new TransferToEDTQueue<Runnable>(name, new Processor<Runnable>() {
    @Override
    public boolean process(Runnable runnable) {
      runnable.run();
      return true;
    }
  }, Conditions.alwaysFalse(), maxUnitOfWorkThresholdMs);
}
 
Example #16
Source File: FindInProjectUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static Condition<CharSequence> createFileMaskCondition(@Nullable String filter) throws PatternSyntaxException {
  if (filter == null) {
    return Conditions.alwaysTrue();
  }

  String pattern = "";
  String negativePattern = "";
  final List<String> masks = StringUtil.split(filter, ",");

  for (String mask : masks) {
    mask = mask.trim();
    if (StringUtil.startsWith(mask, "!")) {
      negativePattern += (negativePattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask.substring(1)) + ")";
    }
    else {
      pattern += (pattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask) + ")";
    }
  }

  if (pattern.isEmpty()) pattern = PatternUtil.convertToRegex("*");
  final String finalPattern = pattern;
  final String finalNegativePattern = negativePattern;

  return new Condition<CharSequence>() {
    final Pattern regExp = Pattern.compile(finalPattern, Pattern.CASE_INSENSITIVE);
    final Pattern negativeRegExp = StringUtil.isEmpty(finalNegativePattern) ? null : Pattern.compile(finalNegativePattern, Pattern.CASE_INSENSITIVE);

    @Override
    public boolean value(CharSequence input) {
      return regExp.matcher(input).matches() && (negativeRegExp == null || !negativeRegExp.matcher(input).matches());
    }
  };
}
 
Example #17
Source File: CommandProcessorBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FinalizableCommand takeNextCommand() {
  FinalizableCommand command = myList.remove(0);
  if (isEmpty()) {
    // memory leak otherwise
    myExpireCondition = Conditions.alwaysTrue();
  }
  return command;
}
 
Example #18
Source File: ActionUpdater.java    From consulo with Apache License 2.0 5 votes vote down vote up
private List<AnAction> getGroupChildren(ActionGroup group, UpdateStrategy strategy) {
  return myGroupChildren.computeIfAbsent(group, __ -> {
    AnAction[] children = strategy.getChildren.fun(group);
    int nullIndex = ArrayUtil.indexOf(children, null);
    if (nullIndex < 0) return Arrays.asList(children);

    LOG.error("action is null: i=" + nullIndex + " group=" + group + " group id=" + ActionManager.getInstance().getId(group));
    return ContainerUtil.filter(children, Conditions.notNull());
  });
}
 
Example #19
Source File: ConsoleExecuteAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ConsoleExecuteAction(@Nonnull LanguageConsoleView consoleView,
                            @Nonnull ConsoleExecuteActionHandler executeActionHandler,
                            @Nonnull String emptyExecuteActionId,
                            @Nullable Condition<LanguageConsoleView> enabledCondition) {
  super(null, null, AllIcons.Actions.Execute);

  myConsoleView = consoleView;
  myExecuteActionHandler = executeActionHandler;
  myEnabledCondition = enabledCondition == null ? Conditions.<LanguageConsoleView>alwaysTrue() : enabledCondition;

  EmptyAction.setupAction(this, emptyExecuteActionId, null);
}
 
Example #20
Source File: RunAnythingChooseContextAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ChooseContextPopupStep(List<PopupFactoryImpl.ActionItem> actions, DataContext dataContext, Runnable updateToolbar) {
  super(actions, IdeBundle.message("run.anything.context.title.working.directory"), () -> dataContext, null, true, Conditions.alwaysFalse(), false, true, null);
  myActions = actions;
  myUpdateToolbar = updateToolbar;
}
 
Example #21
Source File: ConsoleExecuteAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
public ConsoleExecuteAction(@Nonnull LanguageConsoleView console, @Nonnull BaseConsoleExecuteActionHandler executeActionHandler) {
  this(console, executeActionHandler, CONSOLE_EXECUTE_ACTION_ID, Conditions.<LanguageConsoleView>alwaysTrue());
}
 
Example #22
Source File: JBIterable.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the elements from this iterable that are instances of class {@code type}.
 * @param type the type of elements desired
 */
@Nonnull
public final <T> JBIterable<T> filter(@Nonnull Class<T> type) {
  return (JBIterable<T>)filter(Conditions.instanceOf(type));
}
 
Example #23
Source File: BaseProjectTreeBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated Use {@link #selectAsync}
 */
@Deprecated
@Nonnull
public ActionCallback select(Object element, VirtualFile file, final boolean requestFocus) {
  return Promises.toActionCallback(_select(element, file, requestFocus, Conditions.alwaysTrue()));
}
 
Example #24
Source File: BaseProjectTreeBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public Promise<Object> selectAsync(Object element, VirtualFile file, final boolean requestFocus) {
  return _select(element, file, requestFocus, Conditions.alwaysTrue());
}
 
Example #25
Source File: CopyPasteDelegator.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isCopyEnabled(@Nonnull DataContext dataContext) {
  PsiElement[] elements = getValidSelectedElements();
  return CopyHandler.canCopy(elements) || JBIterable.of(elements).filter(Conditions.instanceOf(PsiNamedElement.class)).isNotEmpty();
}
 
Example #26
Source File: WideSelectionTreeUI.java    From consulo with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public WideSelectionTreeUI() {
  this(true, Conditions.<Integer>alwaysTrue());
}
 
Example #27
Source File: MockComponentManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Condition getDisposed() {
  return Conditions.alwaysFalse();
}
 
Example #28
Source File: FilteringIterator.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static <T> Condition<T> alwaysTrueCondition(Class<T> aClass) {
  return Conditions.alwaysTrue();
}
 
Example #29
Source File: FilteringIterator.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static <Dom, T extends Dom> Iterator<T> create(Iterator<Dom> iterator, Condition<? super Dom> condition) {
  if (condition == Condition.TRUE || condition == Conditions.TRUE) return (Iterator<T>)iterator;
  return new FilteringIterator<Dom, T>(iterator, condition);
}
 
Example #30
Source File: TemplateSettingPanel.java    From EasyCode with MIT License 4 votes vote down vote up
private JBIterable<DasTable> getTables(DbDataSource dataSource) {
    return dataSource.getModel().traverser().expandAndSkip(Conditions.instanceOf(DasNamespace.class)).filter(DasTable.class);
}