use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class RepositoryAttachHandler method doResolveInner.
public static void doResolveInner(Project project, final MavenId mavenId, List<MavenExtraArtifactType> extraTypes, Collection<MavenRepositoryInfo> repositories, @Nullable final Processor<List<MavenArtifact>> resultProcessor, ProgressIndicator indicator) {
boolean cancelled = false;
final Collection<MavenArtifact> result = new LinkedHashSet<>();
MavenEmbeddersManager manager = MavenProjectsManager.getInstance(project).getEmbeddersManager();
MavenEmbedderWrapper embedder = manager.getEmbedder(MavenEmbeddersManager.FOR_DOWNLOAD, null, null);
try {
final MavenGeneralSettings mavenGeneralSettings = MavenProjectsManager.getInstance(project).getGeneralSettings();
embedder.customizeForResolve(new SoutMavenConsole(mavenGeneralSettings.getOutputLevel(), mavenGeneralSettings.isPrintErrorStackTraces()), new MavenProgressIndicator(indicator));
List<MavenRemoteRepository> remoteRepositories = convertRepositories(repositories);
List<MavenArtifactInfo> artifacts = Collections.singletonList(new MavenArtifactInfo(mavenId, "jar", null));
List<MavenArtifact> firstResult = embedder.resolveTransitively(artifacts, remoteRepositories);
for (MavenArtifact artifact : firstResult) {
if (!artifact.isResolved() || MavenConstants.SCOPE_TEST.equals(artifact.getScope())) {
continue;
}
result.add(artifact);
}
// download docs & sources
if (!extraTypes.isEmpty()) {
Set<String> allowedClassifiers = JBIterable.from(extraTypes).transform(extraType -> extraType.getDefaultClassifier()).toSet();
List<MavenArtifactInfo> resolve = JBIterable.from(extraTypes).transform(extraType -> new MavenArtifactInfo(mavenId, extraType.getDefaultExtension(), extraType.getDefaultClassifier())).toList();
// skip sources/javadoc for dependencies
for (MavenArtifact artifact : embedder.resolveTransitively(new ArrayList<>(resolve), remoteRepositories)) {
if (!artifact.isResolved() || MavenConstants.SCOPE_TEST.equals(artifact.getScope()) || !allowedClassifiers.contains(artifact.getClassifier())) {
continue;
}
result.add(artifact);
}
}
} catch (MavenProcessCanceledException e) {
cancelled = true;
} finally {
manager.release(embedder);
if (!cancelled && resultProcessor != null) {
ApplicationManager.getApplication().invokeAndWait(() -> resultProcessor.process(new ArrayList<>(result)));
}
}
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class UsedIconsListingAction method actionPerformed.
@Override
public void actionPerformed(AnActionEvent e) {
final Project project = LangDataKeys.PROJECT.getData(e.getDataContext());
final MultiMap<String, PsiExpression> calls = new MultiMap<>();
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
Processor<PsiReference> consumer = new Processor<PsiReference>() {
@Override
public boolean process(PsiReference reference) {
PsiCallExpression call = PsiTreeUtil.getParentOfType(reference.getElement(), PsiCallExpression.class, false);
if (call == null)
return true;
if (call.getArgumentList() == null)
return true;
if (call.getArgumentList().getExpressions() == null)
return true;
PsiFile file = reference.getElement().getContainingFile();
if ("AllIcons.java".equals(file.getName()))
return true;
PsiClass container = PsiUtil.getTopLevelClass(reference.getElement());
if (container != null && container.getQualifiedName().startsWith("icons."))
return true;
for (PsiExpression arg : call.getArgumentList().getExpressions()) {
if (arg instanceof PsiLiteralExpression) {
Object value = ((PsiLiteralExpression) arg).getValue();
processValue(value, call, file);
} else {
Object value = psiFacade.getConstantEvaluationHelper().computeConstantExpression(arg, false);
processValue(value, call, file);
}
}
return true;
}
private void processValue(Object value, PsiCallExpression call, PsiFile file) {
if (value instanceof String) {
String str = StringUtil.unquoteString((String) value, '\"');
if (!str.startsWith("/")) {
if (file instanceof PsiClassOwner) {
str = "/" + ((PsiClassOwner) file).getPackageName().replace('.', '/') + "/" + str;
}
}
calls.putValue(str, call);
}
}
};
GlobalSearchScope allScope = GlobalSearchScope.allScope(project);
PsiClass iconLoader = psiFacade.findClass("com.intellij.openapi.util.IconLoader", allScope);
PsiMethod getIconMethod = iconLoader.findMethodsByName("getIcon", false)[0];
PsiMethod findIconMethod = iconLoader.findMethodsByName("findIcon", false)[0];
if (true) {
MethodReferencesSearch.search(getIconMethod, false).forEach(consumer);
MethodReferencesSearch.search(findIconMethod, false).forEach(consumer);
}
final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
if (true) {
PsiClass javaeeIcons = psiFacade.findClass("com.intellij.javaee.oss.JavaeeIcons", allScope);
MethodReferencesSearch.search(javaeeIcons.findMethodsByName("getIcon", false)[0], false).forEach(consumer);
MethodReferencesSearch.search(findIconMethod, false).forEach(consumer);
}
final List<XmlAttribute> xmlAttributes = new ArrayList<>();
PsiSearchHelper.SERVICE.getInstance(project).processAllFilesWithWordInText("icon", new DelegatingGlobalSearchScope(GlobalSearchScope.projectScope(project)) {
@Override
public boolean contains(@NotNull VirtualFile file) {
return super.contains(file) && file.getFileType() == XmlFileType.INSTANCE && index.isInSource(file);
}
}, new Processor<PsiFile>() {
@Override
public boolean process(PsiFile file) {
file.accept(new XmlRecursiveElementVisitor() {
@Override
public void visitXmlTag(XmlTag tag) {
super.visitXmlTag(tag);
String icon = tag.getAttributeValue("icon");
if (icon != null) {
xmlAttributes.add(tag.getAttribute("icon"));
}
}
});
return true;
}
}, true);
PsiClass presentation = psiFacade.findClass("com.intellij.ide.presentation.Presentation", allScope);
final MultiMap<String, PsiAnnotation> annotations = new MultiMap<>();
AnnotationTargetsSearch.search(presentation).forEach(owner -> {
PsiAnnotation annotation = owner.getModifierList().findAnnotation("com.intellij.ide.presentation.Presentation");
PsiAnnotationMemberValue icon = annotation.findAttributeValue("icon");
if (icon instanceof PsiLiteralExpression) {
Object value = ((PsiLiteralExpression) icon).getValue();
if (value instanceof String) {
annotations.putValue((String) value, annotation);
}
}
return true;
});
doReplacements(project, calls, xmlAttributes, annotations, psiFacade.findClass("com.intellij.icons.AllIcons", allScope));
for (PsiClass iconClass : psiFacade.findPackage("icons").getClasses(allScope)) {
if (iconClass.getName().endsWith("Icons")) {
doReplacements(project, calls, xmlAttributes, annotations, iconClass);
}
}
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class InjectedGeneralHighlightingPass method getInjectedPsiFiles.
@NotNull
private Set<PsiFile> getInjectedPsiFiles(@NotNull final List<PsiElement> elements1, @NotNull final List<PsiElement> elements2, @NotNull final ProgressIndicator progress) {
ApplicationManager.getApplication().assertReadAccessAllowed();
List<DocumentWindow> injected = InjectedLanguageUtil.getCachedInjectedDocuments(myFile);
final Collection<PsiElement> hosts = new THashSet<>(elements1.size() + elements2.size() + injected.size());
//since change in one place can lead to invalidation of injected PSI in (completely) other place.
for (DocumentWindow documentRange : injected) {
progress.checkCanceled();
if (!documentRange.isValid())
continue;
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(documentRange);
if (file == null)
continue;
PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file);
if (context != null && context.isValid() && !file.getProject().isDisposed() && (myUpdateAll || myRestrictRange.intersects(context.getTextRange()))) {
hosts.add(context);
}
}
InjectedLanguageManagerImpl injectedLanguageManager = InjectedLanguageManagerImpl.getInstanceImpl(myProject);
Processor<PsiElement> collectInjectableProcessor = Processors.cancelableCollectProcessor(hosts);
injectedLanguageManager.processInjectableElements(elements1, collectInjectableProcessor);
injectedLanguageManager.processInjectableElements(elements2, collectInjectableProcessor);
final Set<PsiFile> outInjected = new THashSet<>();
final PsiLanguageInjectionHost.InjectedPsiVisitor visitor = new PsiLanguageInjectionHost.InjectedPsiVisitor() {
@Override
public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
synchronized (outInjected) {
outInjected.add(injectedPsi);
}
}
};
if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(new ArrayList<>(hosts), progress, true, element -> {
ApplicationManager.getApplication().assertReadAccessAllowed();
progress.checkCanceled();
InjectedLanguageUtil.enumerate(element, myFile, false, visitor);
return true;
})) {
throw new ProcessCanceledException();
}
synchronized (outInjected) {
return outInjected;
}
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class DocumentationManager method showInPopup.
private void showInPopup(@NotNull final PsiElement element, boolean requestFocus, PopupUpdateProcessor updateProcessor, final PsiElement originalElement, @Nullable final Runnable closeCallback) {
final DocumentationComponent component = myTestDocumentationComponent == null ? new DocumentationComponent(this) : myTestDocumentationComponent;
component.setNavigateCallback(psiElement -> {
final AbstractPopup jbPopup = (AbstractPopup) getDocInfoHint();
if (jbPopup != null) {
final String title = getTitle(psiElement, false);
jbPopup.setCaption(title);
AccessibleContextUtil.setName(component, title);
}
});
Processor<JBPopup> pinCallback = popup -> {
createToolWindow(element, originalElement);
myToolWindow.setAutoHide(false);
popup.cancel();
return false;
};
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createToolWindow(element, originalElement);
final JBPopup hint = getDocInfoHint();
if (hint != null && hint.isVisible())
hint.cancel();
}
};
List<Pair<ActionListener, KeyStroke>> actions = ContainerUtil.newSmartList();
AnAction quickDocAction = ActionManager.getInstance().getAction(IdeActions.ACTION_QUICK_JAVADOC);
for (Shortcut shortcut : quickDocAction.getShortcutSet().getShortcuts()) {
if (!(shortcut instanceof KeyboardShortcut))
continue;
actions.add(Pair.create(actionListener, ((KeyboardShortcut) shortcut).getFirstKeyStroke()));
}
boolean hasLookup = LookupManager.getActiveLookup(myEditor) != null;
final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component).setProject(element.getProject()).addListener(updateProcessor).addUserData(updateProcessor).setKeyboardActions(actions).setDimensionServiceKey(myProject, JAVADOC_LOCATION_AND_SIZE, false).setResizable(true).setMovable(true).setRequestFocus(requestFocus).setCancelOnClickOutside(// otherwise selecting lookup items by mouse would close the doc
!hasLookup).setTitle(getTitle(element, false)).setCouldPin(pinCallback).setModalContext(false).setCancelCallback(() -> {
myCloseOnSneeze = false;
if (closeCallback != null) {
closeCallback.run();
}
if (fromQuickSearch()) {
((ChooseByNameBase.JPanelProvider) myPreviouslyFocused.getParent()).unregisterHint();
}
Disposer.dispose(component);
myEditor = null;
myPreviouslyFocused = null;
return Boolean.TRUE;
}).setKeyEventHandler(e -> {
if (myCloseOnSneeze) {
closeDocHint();
}
if (AbstractPopup.isCloseRequest(e) && getDocInfoHint() != null) {
closeDocHint();
return true;
}
return false;
}).createPopup();
component.setHint(hint);
if (myEditor == null) {
// subsequent invocation of javadoc popup from completion will have myEditor == null because of cancel invoked,
// so reevaluate the editor for proper popup placement
Lookup lookup = LookupManager.getInstance(myProject).getActiveLookup();
myEditor = lookup != null ? lookup.getEditor() : null;
}
fetchDocInfo(getDefaultCollector(element, originalElement), component);
myDocInfoHintRef = new WeakReference<>(hint);
if (fromQuickSearch() && myPreviouslyFocused != null) {
((ChooseByNameBase.JPanelProvider) myPreviouslyFocused.getParent()).registerHint(hint);
}
}
use of com.intellij.util.Processor in project intellij-community by JetBrains.
the class ShowIntentionsPass method collectIntentionsFromDoNotShowLeveledInspections.
/**
* Can be invoked in EDT, each inspection should be fast
*/
private static void collectIntentionsFromDoNotShowLeveledInspections(@NotNull final Project project, @NotNull final PsiFile hostFile, PsiElement psiElement, final int offset, @NotNull final IntentionsInfo intentions) {
if (psiElement != null) {
if (!psiElement.isPhysical()) {
VirtualFile virtualFile = hostFile.getVirtualFile();
String text = hostFile.getText();
LOG.error("not physical: '" + psiElement.getText() + "' @" + offset + psiElement.getTextRange() + " elem:" + psiElement + " (" + psiElement.getClass().getName() + ")" + " in:" + psiElement.getContainingFile() + " host:" + hostFile + "(" + hostFile.getClass().getName() + ")", new Attachment(virtualFile != null ? virtualFile.getPresentableUrl() : "null", text != null ? text : "null"));
}
if (DumbService.isDumb(project)) {
return;
}
final List<LocalInspectionToolWrapper> intentionTools = new ArrayList<>();
final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
final InspectionToolWrapper[] tools = profile.getInspectionTools(hostFile);
for (InspectionToolWrapper toolWrapper : tools) {
if (toolWrapper instanceof LocalInspectionToolWrapper && !((LocalInspectionToolWrapper) toolWrapper).isUnfair()) {
final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName());
if (profile.isToolEnabled(key, hostFile) && HighlightDisplayLevel.DO_NOT_SHOW.equals(profile.getErrorLevel(key, hostFile))) {
intentionTools.add((LocalInspectionToolWrapper) toolWrapper);
}
}
}
if (!intentionTools.isEmpty()) {
final List<PsiElement> elements = new ArrayList<>();
PsiElement el = psiElement;
while (el != null) {
elements.add(el);
if (el instanceof PsiFile)
break;
el = el.getParent();
}
final Set<String> dialectIds = InspectionEngine.calcElementDialectIds(elements);
final LocalInspectionToolSession session = new LocalInspectionToolSession(hostFile, 0, hostFile.getTextLength());
final Processor<LocalInspectionToolWrapper> processor = toolWrapper -> {
final LocalInspectionTool localInspectionTool = toolWrapper.getTool();
final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName());
final String displayName = toolWrapper.getDisplayName();
final ProblemsHolder holder = new ProblemsHolder(InspectionManager.getInstance(project), hostFile, true) {
@Override
public void registerProblem(@NotNull ProblemDescriptor problemDescriptor) {
super.registerProblem(problemDescriptor);
if (problemDescriptor instanceof ProblemDescriptorBase) {
final TextRange range = ((ProblemDescriptorBase) problemDescriptor).getTextRange();
if (range != null && range.contains(offset)) {
final QuickFix[] fixes = problemDescriptor.getFixes();
if (fixes != null) {
for (int k = 0; k < fixes.length; k++) {
final IntentionAction intentionAction = QuickFixWrapper.wrap(problemDescriptor, k);
final HighlightInfo.IntentionActionDescriptor actionDescriptor = new HighlightInfo.IntentionActionDescriptor(intentionAction, null, displayName, null, key, null, HighlightSeverity.INFORMATION);
intentions.intentionsToShow.add(actionDescriptor);
}
}
}
}
}
};
InspectionEngine.createVisitorAndAcceptElements(localInspectionTool, holder, true, session, elements, dialectIds, InspectionEngine.getDialectIdsSpecifiedForTool(toolWrapper));
localInspectionTool.inspectionFinished(session, holder);
return true;
};
JobLauncher.getInstance().invokeConcurrentlyUnderProgress(intentionTools, new DaemonProgressIndicator(), false, processor);
}
}
}
Aggregations