use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class JumpToColorsAndFontsAction method actionPerformed.
@Override
public void actionPerformed(AnActionEvent e) {
// todo handle ColorKey's as well
Project project = e.getData(CommonDataKeys.PROJECT);
Editor editor = e.getData(CommonDataKeys.EDITOR);
if (project == null || editor == null)
return;
Map<TextAttributesKey, Pair<ColorSettingsPage, AttributesDescriptor>> keyMap = ContainerUtil.newHashMap();
Processor<RangeHighlighterEx> processor = r -> {
Object tt = r.getErrorStripeTooltip();
TextAttributesKey key = tt instanceof HighlightInfo ? ObjectUtils.chooseNotNull(((HighlightInfo) tt).forcedTextAttributesKey, ((HighlightInfo) tt).type.getAttributesKey()) : null;
Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
if (p != null)
keyMap.put(key, p);
return true;
};
JBIterable<Editor> editors = editor instanceof EditorWindow ? JBIterable.of(editor, ((EditorWindow) editor).getDelegate()) : JBIterable.of(editor);
for (Editor ed : editors) {
TextRange selection = EditorUtil.getSelectionInAnyMode(ed);
MarkupModel forDocument = DocumentMarkupModel.forDocument(ed.getDocument(), project, false);
if (forDocument != null) {
((MarkupModelEx) forDocument).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
}
((MarkupModelEx) ed.getMarkupModel()).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
EditorHighlighter highlighter = ed instanceof EditorEx ? ((EditorEx) ed).getHighlighter() : null;
SyntaxHighlighter syntaxHighlighter = highlighter instanceof LexerEditorHighlighter ? ((LexerEditorHighlighter) highlighter).getSyntaxHighlighter() : null;
if (syntaxHighlighter != null) {
HighlighterIterator iterator = highlighter.createIterator(selection.getStartOffset());
while (!iterator.atEnd()) {
for (TextAttributesKey key : syntaxHighlighter.getTokenHighlights(iterator.getTokenType())) {
Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
if (p != null)
keyMap.put(key, p);
}
if (iterator.getEnd() >= selection.getEndOffset())
break;
iterator.advance();
}
}
}
if (keyMap.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No text attributes found");
} else if (keyMap.size() == 1) {
Pair<ColorSettingsPage, AttributesDescriptor> p = keyMap.values().iterator().next();
if (!openSettingsAndSelectKey(project, p.first, p.second)) {
HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
}
} else {
ArrayList<Pair<ColorSettingsPage, AttributesDescriptor>> attrs = ContainerUtil.newArrayList(keyMap.values());
Collections.sort(attrs, (o1, o2) -> StringUtil.naturalCompare(o1.first.getDisplayName() + o1.second.getDisplayName(), o2.first.getDisplayName() + o2.second.getDisplayName()));
EditorColorsScheme colorsScheme = editor.getColorsScheme();
JBList<Pair<ColorSettingsPage, AttributesDescriptor>> list = new JBList<>(attrs);
list.setCellRenderer(new ColoredListCellRenderer<Pair<ColorSettingsPage, AttributesDescriptor>>() {
@Override
protected void customizeCellRenderer(@NotNull JList<? extends Pair<ColorSettingsPage, AttributesDescriptor>> list, Pair<ColorSettingsPage, AttributesDescriptor> value, int index, boolean selected, boolean hasFocus) {
TextAttributes ta = colorsScheme.getAttributes(value.second.getKey());
Color fg = ObjectUtils.chooseNotNull(ta.getForegroundColor(), colorsScheme.getDefaultForeground());
Color bg = ObjectUtils.chooseNotNull(ta.getBackgroundColor(), colorsScheme.getDefaultBackground());
SimpleTextAttributes sa = fromTextAttributes(ta);
SimpleTextAttributes saOpaque = sa.derive(STYLE_OPAQUE | sa.getStyle(), fg, bg, null);
SimpleTextAttributes saSelected = REGULAR_ATTRIBUTES.derive(sa.getStyle(), null, null, null);
SimpleTextAttributes saCur = REGULAR_ATTRIBUTES;
List<String> split = StringUtil.split(value.first.getDisplayName() + "//" + value.second.getDisplayName(), "//");
for (int i = 0, len = split.size(); i < len; i++) {
boolean last = i == len - 1;
saCur = !last ? REGULAR_ATTRIBUTES : selected ? saSelected : saOpaque;
if (last)
append(" ", saCur);
append(split.get(i), saCur);
if (last)
append(" ", saCur);
else
append(" > ", GRAYED_ATTRIBUTES);
}
Color stripeColor = ta.getErrorStripeColor();
boolean addStripe = stripeColor != null && stripeColor != saCur.getBgColor();
boolean addBoxed = ta.getEffectType() == EffectType.BOXED && ta.getEffectColor() != null;
if (addBoxed) {
append("▢" + (addStripe ? "" : " "), saCur.derive(-1, ta.getEffectColor(), null, null));
}
if (addStripe) {
append(" ", saCur.derive(STYLE_OPAQUE, null, stripeColor, null));
}
}
});
JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle(StringUtil.notNullize(e.getPresentation().getText())).setMovable(false).setResizable(false).setRequestFocus(true).setItemChoosenCallback(() -> {
Pair<ColorSettingsPage, AttributesDescriptor> p = list.getSelectedValue();
if (p != null && !openSettingsAndSelectKey(project, p.first, p.second)) {
HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
}
}).createPopup().showInBestPositionFor(editor);
}
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class InjectedLanguageManagerImpl method startRunInjectors.
@Override
public void startRunInjectors(@NotNull final Document hostDocument, final boolean synchronously) {
if (myProject.isDisposed())
return;
if (!synchronously && ApplicationManager.getApplication().isWriteAccessAllowed())
return;
// use cached to avoid recreate PSI in alien project
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
final PsiFile hostPsiFile = documentManager.getCachedPsiFile(hostDocument);
if (hostPsiFile == null)
return;
final ConcurrentList<DocumentWindow> injected = InjectedLanguageUtil.getCachedInjectedDocuments(hostPsiFile);
if (injected.isEmpty())
return;
if (myProgress.isCanceled()) {
myProgress = new DaemonProgressIndicator();
}
final Set<DocumentWindow> newDocuments = Collections.synchronizedSet(new THashSet<>());
final Processor<DocumentWindow> commitProcessor = documentWindow -> {
if (myProject.isDisposed())
return false;
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null && indicator.isCanceled())
return false;
if (documentManager.isUncommited(hostDocument) || !hostPsiFile.isValid())
return false;
InjectedLanguageUtil.enumerate(documentWindow, hostPsiFile, (injectedPsi, places) -> {
DocumentWindow newDocument = (DocumentWindow) injectedPsi.getViewProvider().getDocument();
if (newDocument != null) {
PsiDocumentManagerBase.checkConsistency(injectedPsi, newDocument);
newDocuments.add(newDocument);
}
});
return true;
};
final Runnable commitInjectionsRunnable = () -> {
if (myProgress.isCanceled())
return;
JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList<>(injected), myProgress, true, commitProcessor);
synchronized (ourInjectionPsiLock) {
injected.clear();
injected.addAll(newDocuments);
}
};
if (synchronously) {
if (Thread.holdsLock(PsiLock.LOCK)) {
// hack for the case when docCommit was called from within PSI modification, e.g. in formatter.
// we can't spawn threads to do injections there, otherwise a deadlock is imminent
ContainerUtil.process(new ArrayList<>(injected), commitProcessor);
} else {
commitInjectionsRunnable.run();
}
} else {
JobLauncher.getInstance().submitToJobThread(() -> ApplicationManagerEx.getApplicationEx().tryRunReadAction(commitInjectionsRunnable), null);
}
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class BaseRefactoringProcessor method previewRefactoring.
protected void previewRefactoring(@NotNull UsageInfo[] usages) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
if (!PREVIEW_IN_TESTS)
throw new RuntimeException("Unexpected preview in tests: " + StringUtil.join(usages, info -> info.toString(), ", "));
ensureElementsWritable(usages, createUsageViewDescriptor(usages));
execute(usages);
return;
}
final UsageViewDescriptor viewDescriptor = createUsageViewDescriptor(usages);
final PsiElement[] elements = viewDescriptor.getElements();
final PsiElement2UsageTargetAdapter[] targets = PsiElement2UsageTargetAdapter.convert(elements);
Factory<UsageSearcher> factory = new Factory<UsageSearcher>() {
@Override
public UsageSearcher create() {
return new UsageInfoSearcherAdapter() {
@Override
public void generate(@NotNull final Processor<Usage> processor) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
for (int i = 0; i < elements.length; i++) {
elements[i] = targets[i].getElement();
}
refreshElements(elements);
}
});
processUsages(processor, myProject);
}
@NotNull
@Override
protected UsageInfo[] findUsages() {
return BaseRefactoringProcessor.this.findUsages();
}
};
}
};
showUsageView(viewDescriptor, factory, usages);
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class JavaClassInheritorsSearcher method getOrComputeSubClasses.
@NotNull
private static Iterable<PsiClass> getOrComputeSubClasses(@NotNull Project project, @NotNull PsiClass baseClass, @NotNull SearchScope searchScopeForNonPhysical) {
ConcurrentMap<PsiClass, Iterable<PsiClass>> map = HighlightingCaches.getInstance(project).ALL_SUB_CLASSES;
Iterable<PsiClass> cached = map.get(baseClass);
if (cached == null) {
// returns lazy collection of subclasses. Each call to next() leads to calculation of next batch of subclasses.
Function<PsiAnchor, PsiClass> converter = anchor -> ReadAction.compute(() -> (PsiClass) anchor.retrieve());
Predicate<PsiClass> applicableFilter = candidate -> !(candidate instanceof PsiAnonymousClass) && candidate != null && !candidate.hasModifierProperty(PsiModifier.FINAL);
// for non-physical elements ignore the cache completely because non-physical elements created so often/unpredictably so I can't figure out when to clear caches in this case
boolean isPhysical = ReadAction.compute(baseClass::isPhysical);
SearchScope scopeToUse = isPhysical ? GlobalSearchScope.allScope(project) : searchScopeForNonPhysical;
LazyConcurrentCollection.MoreElementsGenerator<PsiAnchor, PsiClass> generator = (candidate, processor) -> DirectClassInheritorsSearch.search(candidate, scopeToUse).forEach(subClass -> {
ProgressManager.checkCanceled();
PsiAnchor pointer = ReadAction.compute(() -> PsiAnchor.create(subClass));
processor.consume(pointer);
return true;
});
PsiAnchor seed = ReadAction.compute(() -> PsiAnchor.create(baseClass));
// lazy collection: store underlying queue as PsiAnchors, generate new elements by running direct inheritors
Iterable<PsiClass> computed = new LazyConcurrentCollection<>(seed, converter, applicableFilter, generator);
// make sure concurrent calls of this method always return the same collection to avoid expensive duplicate work
cached = isPhysical ? ConcurrencyUtil.cacheOrGet(map, baseClass, computed) : computed;
}
return cached;
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class ReferenceChainLink method getGlobalMembers.
@Nullable
List<PsiMember> getGlobalMembers(VirtualFile placeFile, Project project) {
if (isExpensive(project))
return null;
List<PsiMember> candidates = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
Processor<PsiMember> processor = member -> {
if (!(member instanceof PsiMethod && !ApproximateResolver.canHaveArgCount((PsiMethod) member, argCount))) {
candidates.add(member);
}
return count.incrementAndGet() < 42;
};
PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);
GlobalSearchScope scope = ResolveScopeManager.getInstance(project).getDefaultResolveScope(placeFile);
if (isCall) {
if (!cache.processMethodsWithName(referenceName, processor, scope, null)) {
markExpensive(project);
return null;
}
} else {
PsiPackage pkg = JavaPsiFacade.getInstance(project).findPackage(referenceName);
if (pkg != null && pkg.getDirectories(scope).length > 0)
return null;
if (!cache.processFieldsWithName(referenceName, processor, scope, null)) {
markExpensive(project);
return null;
}
}
if (!cache.processClassesWithName(referenceName, processor, scope, null)) {
markExpensive(project);
return null;
}
return candidates.stream().filter(candidate -> canBeAccessible(placeFile, candidate)).collect(Collectors.toList());
}
Aggregations