下面列出了com.intellij.psi.PsiWhiteSpace#com.intellij.openapi.util.Condition 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Get array string values mapped with their PsiElements
*
* ["value", "value2"]
*/
@NotNull
static public Map<String, PsiElement> getArrayValuesAsMap(@NotNull ArrayCreationExpression arrayCreationExpression) {
List<PsiElement> arrayValues = PhpPsiUtil.getChildren(arrayCreationExpression, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement psiElement) {
return psiElement.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE;
}
});
Map<String, PsiElement> keys = new HashMap<String, PsiElement>();
for (PsiElement child : arrayValues) {
String stringValue = PhpElementsUtil.getStringValue(child.getFirstChild());
if(stringValue != null && StringUtils.isNotBlank(stringValue)) {
keys.put(stringValue, child);
}
}
return keys;
}
@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;
}
private Condition<? super T> buildExpandConditionForChildren(T parent) {
// implements: or2(forceExpandAndSkip, not(childFilter));
// and handles JBIterable.StatefulTransform and EdgeFilter conditions
Cond copy = null;
boolean invert = true;
Cond c = regard;
while (c != null) {
Condition impl = JBIterable.Stateful.copy(c.impl);
if (impl != (invert ? Condition.TRUE : Condition.FALSE)) {
copy = new Cond<Object>(invert ? not(impl) : impl, copy);
if (impl instanceof EdgeFilter) {
((EdgeFilter)impl).edgeSource = parent;
}
}
if (c.next == null) {
c = invert ? forceDisregard : null;
invert = false;
}
else {
c = c.next;
}
}
return copy == null ? Condition.FALSE : copy.OR;
}
/**
* Use this method to check if the given project is a VSTS/TFS project
*
* @param project
* @return
*/
public static boolean isVstsRepo(final Project project) {
if (project != null) {
if (isTfVcs(project)) {
return true;
}
if (!isGitVcs(project)) {
return false;
}
return ContainerUtil.exists(GitUtil.getRepositoryManager(project).getRepositories(), new Condition<GitRepository>() {
@Override
public boolean value(GitRepository gitRepository) {
return TfGitHelper.isTfGitRepository(gitRepository);
}
});
}
return false;
}
@Nullable
protected Pair<PsiElement, TextRange> getRangePair(final PsiFile file, final Editor editor) {
final int offset = editor.getCaretModel().getOffset();
final PsiLanguageInjectionHost host =
PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiLanguageInjectionHost.class, false);
if (host == null || ElementManipulators.getManipulator(host) == null) return null;
final List<Pair<PsiElement, TextRange>> injections = InjectedLanguageManager.getInstance(host.getProject()).getInjectedPsiFiles(host);
if (injections == null || injections.isEmpty()) return null;
final int offsetInElement = offset - host.getTextRange().getStartOffset();
final Pair<PsiElement, TextRange> rangePair = ContainerUtil.find(injections, new Condition<Pair<PsiElement, TextRange>>() {
@Override
public boolean value(final Pair<PsiElement, TextRange> pair) {
return pair.second.containsRange(offsetInElement, offsetInElement);
}
});
if (rangePair != null) {
final Language language = rangePair.first.getContainingFile().getLanguage();
final Object action = language.getUserData(EDIT_ACTION_AVAILABLE);
if (action != null && action.equals(false)) return null;
myLastLanguageName = language.getDisplayName();
}
return rangePair;
}
public ActionGroupPopup(String title,
@Nonnull ActionGroup actionGroup,
@Nonnull DataContext dataContext,
boolean showNumbers,
boolean useAlphaAsNumbers,
boolean showDisabledActions,
boolean honorActionMnemonics,
Runnable disposeCallback,
int maxRowCount,
Condition<? super AnAction> preselectActionCondition,
@Nullable final String actionPlace,
@Nullable PresentationFactory presentationFactory,
boolean autoSelection) {
this(null, createStep(title, actionGroup, dataContext, showNumbers, useAlphaAsNumbers, showDisabledActions, honorActionMnemonics, preselectActionCondition, actionPlace, presentationFactory,
autoSelection), disposeCallback, dataContext, actionPlace, maxRowCount);
}
public ActionPopupStep(@Nonnull List<PopupFactoryImpl.ActionItem> items,
String title,
@Nonnull Supplier<? extends DataContext> context,
@Nullable String actionPlace,
boolean enableMnemonics,
@Nullable Condition<? super AnAction> preselectActionCondition,
boolean autoSelection,
boolean showDisabledActions,
@Nullable PresentationFactory presentationFactory) {
myItems = items;
myTitle = title;
myContext = context;
myActionPlace = ObjectUtils.notNull(actionPlace, ActionPlaces.UNKNOWN);
myEnableMnemonics = enableMnemonics;
myPresentationFactory = presentationFactory;
myDefaultOptionIndex = getDefaultOptionIndexFromSelectCondition(preselectActionCondition, items);
myPreselectActionCondition = preselectActionCondition;
myAutoSelectionEnabled = autoSelection;
myShowDisabledActions = showDisabledActions;
}
@Nonnull
public static ListPopupStep<PopupFactoryImpl.ActionItem> createActionsStep(@Nonnull ActionGroup actionGroup,
@Nonnull DataContext dataContext,
boolean showNumbers,
boolean useAlphaAsNumbers,
boolean showDisabledActions,
String title,
boolean honorActionMnemonics,
boolean autoSelectionEnabled,
Supplier<? extends DataContext> contextSupplier,
@Nullable String actionPlace,
Condition<? super AnAction> preselectCondition,
int defaultOptionIndex,
@Nullable PresentationFactory presentationFactory) {
List<PopupFactoryImpl.ActionItem> items = createActionItems(actionGroup, dataContext, showNumbers, useAlphaAsNumbers, showDisabledActions, honorActionMnemonics, actionPlace, presentationFactory);
boolean enableMnemonics = showNumbers || honorActionMnemonics && items.stream().anyMatch(actionItem -> actionItem.getAction().getTemplatePresentation().getMnemonic() != 0);
return new ActionPopupStep(items, title, contextSupplier, actionPlace, enableMnemonics,
preselectCondition != null ? preselectCondition : action -> defaultOptionIndex >= 0 && defaultOptionIndex < items.size() && items.get(defaultOptionIndex).getAction().equals(action),
autoSelectionEnabled, showDisabledActions, presentationFactory);
}
/**
* When appropriate, automatically reduce the indentation for else tags "{:else}"
*/
private void adjustFormatting(Project project, int offset, Editor editor, PsiFile file, FileViewProvider provider) {
PsiElement elementAtCaret = provider.findElementAt(offset - 1, DustLanguage.class);
PsiElement elseParent = PsiTreeUtil.findFirstParent(elementAtCaret, true, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement element) {
return element != null
&& (element instanceof DustElseTag);
}
});
// run the formatter if the user just completed typing a SIMPLE_INVERSE or a CLOSE_BLOCK_STACHE
if (elseParent != null) {
// grab the current caret position (AutoIndentLinesHandler is about to mess with it)
PsiDocumentManager.getInstance(project).commitAllDocuments();
CaretModel caretModel = editor.getCaretModel();
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
codeStyleManager.adjustLineIndent(file, editor.getDocument().getLineStartOffset(caretModel.getLogicalPosition().line));
}
}
public static boolean addUnversioned(@Nonnull Project project,
@Nonnull List<VirtualFile> files,
@Nonnull Condition<FileStatus> unversionedFileCondition,
@Nullable ChangesBrowserBase browser) {
boolean result = true;
if (!files.isEmpty()) {
FileDocumentManager.getInstance().saveAllDocuments();
@SuppressWarnings("unchecked") Consumer<List<Change>> consumer = browser == null ? null : changes -> {
browser.rebuildList();
browser.getViewer().excludeChanges((List)files);
browser.getViewer().includeChanges((List)changes);
};
ChangeListManagerImpl manager = ChangeListManagerImpl.getInstanceImpl(project);
LocalChangeList targetChangeList = browser == null ? manager.getDefaultChangeList() : (LocalChangeList)browser.getSelectedChangeList();
List<VcsException> exceptions = manager.addUnversionedFiles(targetChangeList, files, unversionedFileCondition, consumer);
result = exceptions.isEmpty();
}
return result;
}
@Override
@Nullable
public CommitId findCommitId(@Nonnull final Condition<CommitId> condition) {
checkDisposed();
try {
final Ref<CommitId> hashRef = Ref.create();
myCommitIdEnumerator.iterateData(new CommonProcessors.FindProcessor<CommitId>() {
@Override
protected boolean accept(CommitId commitId) {
boolean matches = condition.value(commitId);
if (matches) {
hashRef.set(commitId);
}
return matches;
}
});
return hashRef.get();
}
catch (IOException e) {
myExceptionReporter.consume(this, e);
return null;
}
}
@Nullable
@Override
public HaxeNamedComponent findArrayAccessGetter() {
HaxeNamedComponent accessor = ContainerUtil.find(getHaxeMethods(), new Condition<HaxeNamedComponent>() {
@Override
public boolean value(HaxeNamedComponent component) {
if (component instanceof HaxeMethod) {
HaxeMethodModel model = ((HaxeMethod)component).getModel();
return model != null && model.isArrayAccessor() && model.getParameterCount() == 1;
}
return false;
}
});
// Maybe old style getter?
if (null == accessor) {
accessor = findHaxeMethodByName("__get");
}
return accessor;
}
@Nonnull
private List<R> getRepositories(@Nonnull Collection<String> urls) {
final List<R> repositories = myRepositoryManager.getRepositories();
return ContainerUtil.mapNotNull(urls, new NullableFunction<String, R>() {
@Nullable
@Override
public R fun(final String s) {
return ContainerUtil.find(repositories, new Condition<R>() {
@Override
public boolean value(R repository) {
return s.equals(repository.getPresentableUrl());
}
});
}
});
}
private static void tryNavigateToSuperMethod(Editor editor,
HaxeMethod methodDeclaration,
List<HaxeNamedComponent> superItems) {
final String methodName = methodDeclaration.getName();
if (methodName == null) {
return;
}
final List<HaxeNamedComponent> filteredSuperItems = ContainerUtil.filter(superItems, new Condition<HaxeNamedComponent>() {
@Override
public boolean value(HaxeNamedComponent component) {
return methodName.equals(component.getName());
}
});
if (!filteredSuperItems.isEmpty()) {
PsiElementListNavigator.openTargets(editor, HaxeResolveUtil.getComponentNames(filteredSuperItems)
.toArray(new NavigatablePsiElement[filteredSuperItems.size()]),
DaemonBundle.message("navigation.title.super.method", methodName),
null,
new DefaultPsiElementCellRenderer());
}
}
@Nonnull
public Collection<FilePatch> filterBadFileTypePatches() {
List<Pair<VirtualFile, ApplyTextFilePatch>> failedTextPatches =
ContainerUtil.findAll(myTextPatches, new Condition<Pair<VirtualFile, ApplyTextFilePatch>>() {
@Override
public boolean value(Pair<VirtualFile, ApplyTextFilePatch> textPatch) {
final VirtualFile file = textPatch.getFirst();
if (file.isDirectory()) return false;
return !isFileTypeOk(file);
}
});
myTextPatches.removeAll(failedTextPatches);
return ContainerUtil.map(failedTextPatches, new Function<Pair<VirtualFile, ApplyTextFilePatch>, FilePatch>() {
@Override
public FilePatch fun(Pair<VirtualFile, ApplyTextFilePatch> patchInfo) {
return patchInfo.getSecond().getPatch();
}
});
}
private static boolean isAnnotated(AnActionEvent e) {
Project project = e.getRequiredData(CommonDataKeys.PROJECT);
VirtualFile file = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE_ARRAY)[0];
List<Editor> editors = VcsAnnotateUtil.getEditors(project, file);
return ContainerUtil.exists(editors, new Condition<Editor>() {
@Override
public boolean value(Editor editor) {
return editor.getGutter().isAnnotationsShown();
}
});
}
private static int getDefaultOptionIndexFromSelectCondition(@Nullable Condition<? super AnAction> preselectActionCondition, @Nonnull List<? extends PopupFactoryImpl.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;
}
private static <T> List<T> removeIndices(@Nonnull JList<T> list, @Nonnull int[] indices, @Nullable Condition<? super T> condition) {
if (indices.length == 0) {
return new ArrayList<>(0);
}
ListModel<T> model = list.getModel();
ListModelExtension<T, ListModel<T>> extension = getExtension(model);
int firstSelectedIndex = indices[0];
ArrayList<T> removedItems = new ArrayList<>();
int deletedCount = 0;
for (int idx1 : indices) {
int index = idx1 - deletedCount;
if (index < 0 || index >= model.getSize()) continue;
T obj = extension.get(model, index);
if (condition == null || condition.value(obj)) {
removedItems.add(obj);
extension.remove(model, index);
deletedCount++;
}
}
if (model.getSize() == 0) {
list.clearSelection();
}
else if (list.getSelectedValue() == null) {
// if nothing remains selected, set selected row
if (firstSelectedIndex >= model.getSize()) {
list.setSelectedIndex(model.getSize() - 1);
}
else {
list.setSelectedIndex(firstSelectedIndex);
}
}
return removedItems;
}
private int idIndex(final String id) {
return ContainerUtil.indexOf(myMembers, new Condition<ClassifierFactory<LookupElement>>() {
@Override
public boolean value(ClassifierFactory<LookupElement> factory) {
return id.equals(factory.getId());
}
});
}
public static void registerFileMaskFilter(@Nonnull AbstractLayoutCodeProcessor processor, @Nullable String fileTypeMask) {
if (fileTypeMask == null)
return;
final Condition<CharSequence> patternCondition = getFileTypeMaskPattern(fileTypeMask);
processor.addFileFilter(file -> patternCondition.value(file.getNameSequence()));
}
/**
* Constructs a QueueProcessor with the given processor and autostart setting.
* By default QueueProcessor starts processing when it receives the first element. Pass <code>false</code> to alternate its behavior.
*
* @param processor processor of queue elements.
* @param autostart if <code>true</code> (which is by default), the queue will be processed immediately when it receives the first element.
* If <code>false</code>, then it will wait for the {@link #start()} command.
* After QueueProcessor has started once, autostart setting doesn't matter anymore: all other elements will be processed immediately.
*/
public QueueProcessor(@Nonnull PairConsumer<T, Runnable> processor,
boolean autostart,
@Nonnull ThreadToUse threadToUse,
@Nonnull Condition<?> deathCondition) {
myProcessor = processor;
myStarted = autostart;
myThreadToUse = threadToUse;
myDeathCondition = deathCondition;
}
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();
}
}
private static void fillGroupIgnorePopupFlag(ActionGroup actionGroup, Group group, Condition<AnAction> filtered) {
AnAction[] mainMenuTopGroups = actionGroup instanceof DefaultActionGroup
? ((DefaultActionGroup)actionGroup).getChildActionsOrStubs()
: actionGroup.getChildren(null);
for (AnAction action : mainMenuTopGroups) {
if (!(action instanceof ActionGroup)) continue;
Group subGroup = createGroup((ActionGroup)action, false, filtered);
if (subGroup.getSize() > 0) {
group.addGroup(subGroup);
}
}
}
@Nullable
public String findScalaLibId() {
return ContainerUtil.find(
libraries,
new Condition<String>() {
@Override
public boolean value(String libraryId) {
return PantsScalaUtil.isScalaLibraryLib(libraryId);
}
}
);
}
public static Optional<VirtualFile> findPexVersionFile(@NotNull VirtualFile folderWithPex, @NotNull String pantsVersion) {
final String filePrefix = "pants-" + pantsVersion;
return Optional.ofNullable(ContainerUtil.find(
folderWithPex.getChildren(), new Condition<VirtualFile>() {
@Override
public boolean value(VirtualFile virtualFile) {
return "pex".equalsIgnoreCase(virtualFile.getExtension()) && virtualFile.getName().startsWith(filePrefix);
}
}
));
}
public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Condition<V> condition) {
final Map<K, V> result = new HashMap<>(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
final K key = entry.getKey();
final V value = entry.getValue();
if (condition.value(value)) {
result.put(key, value);
}
}
return result;
}
public static ASTNode getOperator(PsiElement element) {
PsiElement binary = PsiTreeUtil.findFirstParent(element, new Condition<PsiElement>() {
@Override
public boolean value(PsiElement psiElement) {
return psiElement instanceof JSBinaryExpression;
}
});
return binary == null ? null : binary.getNode().getChildren(BINARY_OPERATIONS)[0];
}
public boolean containsForcePushTarget(@Nonnull final String remote, @Nonnull final String branch) {
return ContainerUtil.exists(myState.FORCE_PUSH_TARGETS, new Condition<ForcePushTargetInfo>() {
@Override
public boolean value(ForcePushTargetInfo info) {
return info.targetRemoteName.equals(remote) && info.targetBranchName.equals(branch);
}
});
}
private static void waitFor(final Condition<Void> condition) {
new WaitFor(10000) {
@Override
protected boolean condition() {
gc();
return condition.value(null);
}
}.assertCompleted(condition.toString());
}
private boolean isSyncStrategiesAllowed() {
return !mySingleRepoProject &&
ContainerUtil.and(getAffectedSupports(), new Condition<PushSupport<Repository, PushSource, PushTarget>>() {
@Override
public boolean value(PushSupport<Repository, PushSource, PushTarget> support) {
return support.mayChangeTargetsSync();
}
});
}