Search in sources :

Example 6 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class GrMainCompletionProvider method completeReference.

@NotNull
static Runnable completeReference(final CompletionParameters parameters, final GrReferenceElement reference, final JavaCompletionSession inheritorsHolder, final PrefixMatcher matcher, final Consumer<LookupElement> _consumer) {
    final Consumer<LookupElement> consumer = new Consumer<LookupElement>() {

        final Set<LookupElement> added = ContainerUtil.newHashSet();

        @Override
        public void consume(LookupElement element) {
            if (added.add(element)) {
                _consumer.consume(element);
            }
        }
    };
    final Map<PsiModifierListOwner, LookupElement> staticMembers = ContainerUtil.newHashMap();
    final PsiElement qualifier = reference.getQualifier();
    final PsiType qualifierType = GroovyCompletionUtil.getQualifierType(qualifier);
    if (reference instanceof GrReferenceExpression && (qualifier instanceof GrExpression || qualifier == null)) {
        for (String string : CompleteReferencesWithSameQualifier.getVariantsWithSameQualifier((GrReferenceExpression) reference, matcher, (GrExpression) qualifier)) {
            consumer.consume(LookupElementBuilder.create(string).withItemTextUnderlined(true));
        }
        if (parameters.getInvocationCount() < 2 && qualifier != null && qualifierType == null && !(qualifier instanceof GrReferenceExpression && ((GrReferenceExpression) qualifier).resolve() instanceof PsiPackage)) {
            if (parameters.getInvocationCount() == 1) {
                showInfo();
            }
            return EmptyRunnable.INSTANCE;
        }
    }
    final List<LookupElement> zeroPriority = ContainerUtil.newArrayList();
    PsiClass qualifierClass = com.intellij.psi.util.PsiUtil.resolveClassInClassTypeOnly(qualifierType);
    final boolean honorExcludes = qualifierClass == null || !JavaCompletionUtil.isInExcludedPackage(qualifierClass, false);
    GroovyCompletionUtil.processVariants(reference, matcher, parameters, lookupElement -> {
        Object object = lookupElement.getObject();
        if (object instanceof GroovyResolveResult) {
            object = ((GroovyResolveResult) object).getElement();
        }
        if (isLightElementDeclaredDuringCompletion(object)) {
            return;
        }
        if (!(lookupElement instanceof LookupElementBuilder) && inheritorsHolder.alreadyProcessed(lookupElement)) {
            return;
        }
        if (honorExcludes && object instanceof PsiMember && JavaCompletionUtil.isInExcludedPackage((PsiMember) object, true)) {
            return;
        }
        if (!(object instanceof PsiClass)) {
            int priority = assignPriority(lookupElement, qualifierType);
            lookupElement = JavaCompletionUtil.highlightIfNeeded(qualifierType, PrioritizedLookupElement.withPriority(lookupElement, priority), object, reference);
        }
        if ((object instanceof PsiMethod || object instanceof PsiField) && ((PsiModifierListOwner) object).hasModifierProperty(PsiModifier.STATIC)) {
            if (lookupElement.getLookupString().equals(((PsiMember) object).getName())) {
                staticMembers.put(CompletionUtil.getOriginalOrSelf((PsiModifierListOwner) object), lookupElement);
            }
        }
        PrioritizedLookupElement prio = lookupElement.as(PrioritizedLookupElement.CLASS_CONDITION_KEY);
        if (prio == null || prio.getPriority() == 0) {
            zeroPriority.add(lookupElement);
        } else {
            consumer.consume(lookupElement);
        }
    });
    for (LookupElement element : zeroPriority) {
        consumer.consume(element);
    }
    if (qualifier == null) {
        return addStaticMembers(parameters, matcher, staticMembers, consumer);
    }
    return EmptyRunnable.INSTANCE;
}
Also used : Set(java.util.Set) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) LookupElement(com.intellij.codeInsight.lookup.LookupElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) PairConsumer(com.intellij.util.PairConsumer) Consumer(com.intellij.util.Consumer) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) NotNull(org.jetbrains.annotations.NotNull)

Example 7 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class SvnHistoryProvider method reportAppendableHistory.

public void reportAppendableHistory(FilePath path, final VcsAppendableHistorySessionPartner partner, @Nullable final SVNRevision from, @Nullable final SVNRevision to, final int limit, SVNRevision peg, final boolean forceBackwards) throws VcsException {
    FilePath committedPath = path;
    Change change = ChangeListManager.getInstance(myVcs.getProject()).getChange(path);
    if (change != null) {
        final ContentRevision beforeRevision = change.getBeforeRevision();
        final ContentRevision afterRevision = change.getAfterRevision();
        if (beforeRevision != null && afterRevision != null && !beforeRevision.getFile().equals(afterRevision.getFile()) && afterRevision.getFile().equals(path)) {
            committedPath = beforeRevision.getFile();
        }
        // revision can be VcsRevisionNumber.NULL
        if (peg == null && change.getBeforeRevision() != null && change.getBeforeRevision().getRevisionNumber() instanceof SvnRevisionNumber) {
            peg = ((SvnRevisionNumber) change.getBeforeRevision().getRevisionNumber()).getRevision();
        }
    }
    boolean showMergeSources = myVcs.getSvnConfiguration().isShowMergeSourcesInAnnotate();
    final LogLoader logLoader;
    if (path.isNonLocal()) {
        logLoader = new RepositoryLoader(myVcs, committedPath, from, to, limit, peg, forceBackwards, showMergeSources);
    } else {
        logLoader = new LocalLoader(myVcs, committedPath, from, to, limit, peg, showMergeSources);
    }
    try {
        logLoader.preliminary();
    } catch (SVNException e) {
        throw new VcsException(e);
    }
    logLoader.check();
    if (showMergeSources) {
        logLoader.initSupports15();
    }
    final SvnHistorySession historySession = new SvnHistorySession(myVcs, Collections.emptyList(), committedPath, showMergeSources && Boolean.TRUE.equals(logLoader.mySupport15), null, false, !path.isNonLocal());
    final Ref<Boolean> sessionReported = new Ref<>();
    final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    if (indicator != null) {
        indicator.setText(SvnBundle.message("progress.text2.collecting.history", path.getName()));
    }
    final Consumer<VcsFileRevision> consumer = vcsFileRevision -> {
        if (!Boolean.TRUE.equals(sessionReported.get())) {
            partner.reportCreatedEmptySession(historySession);
            sessionReported.set(true);
        }
        partner.acceptRevision(vcsFileRevision);
    };
    logLoader.setConsumer(consumer);
    logLoader.load();
    logLoader.check();
}
Also used : FilePath(com.intellij.openapi.vcs.FilePath) UIUtil(com.intellij.util.ui.UIUtil) SvnBindException(org.jetbrains.idea.svn.commandLine.SvnBindException) SvnRevisionNumber(org.jetbrains.idea.svn.SvnRevisionNumber) Change(com.intellij.openapi.vcs.changes.Change) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Date(java.util.Date) ContentRevision(com.intellij.openapi.vcs.changes.ContentRevision) ThrowableConsumer(com.intellij.util.ThrowableConsumer) ColumnInfo(com.intellij.util.ui.ColumnInfo) TableCellRenderer(javax.swing.table.TableCellRenderer) ActionManager(com.intellij.openapi.actionSystem.ActionManager) ShowAllAffectedGenericAction(com.intellij.openapi.vcs.annotate.ShowAllAffectedGenericAction) SVNErrorManager(org.tmatesoft.svn.core.internal.wc.SVNErrorManager) VcsConfiguration(com.intellij.openapi.vcs.VcsConfiguration) SvnUtil(org.jetbrains.idea.svn.SvnUtil) Charset(java.nio.charset.Charset) StatusText(com.intellij.util.ui.StatusText) SvnVcs(org.jetbrains.idea.svn.SvnVcs) VcsException(com.intellij.openapi.vcs.VcsException) FilePath(com.intellij.openapi.vcs.FilePath) PlatformIcons(com.intellij.util.PlatformIcons) ProgressManager(com.intellij.openapi.progress.ProgressManager) SVNCancelException(org.tmatesoft.svn.core.SVNCancelException) ChangeListManager(com.intellij.openapi.vcs.changes.ChangeListManager) SVNException(org.tmatesoft.svn.core.SVNException) StringUtil(com.intellij.openapi.util.text.StringUtil) AnAction(com.intellij.openapi.actionSystem.AnAction) Info(org.jetbrains.idea.svn.info.Info) com.intellij.openapi.vcs.history(com.intellij.openapi.vcs.history) com.intellij.ui(com.intellij.ui) MouseEvent(java.awt.event.MouseEvent) SvnBundle(org.jetbrains.idea.svn.SvnBundle) java.awt(java.awt) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) VcsActions(com.intellij.openapi.vcs.VcsActions) List(java.util.List) TableLinkMouseListener(com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener) SVNRevision(org.tmatesoft.svn.core.wc.SVNRevision) SVNLogType(org.tmatesoft.svn.util.SVNLogType) SVNURL(org.tmatesoft.svn.core.SVNURL) SVNPathUtil(org.tmatesoft.svn.core.internal.util.SVNPathUtil) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) SvnTarget(org.tmatesoft.svn.core.wc2.SvnTarget) Collections(java.util.Collections) Consumer(com.intellij.util.Consumer) javax.swing(javax.swing) ContentRevision(com.intellij.openapi.vcs.changes.ContentRevision) Change(com.intellij.openapi.vcs.changes.Change) SVNException(org.tmatesoft.svn.core.SVNException) SvnRevisionNumber(org.jetbrains.idea.svn.SvnRevisionNumber) Ref(com.intellij.openapi.util.Ref) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) VcsException(com.intellij.openapi.vcs.VcsException)

Example 8 with Consumer

use of com.intellij.util.Consumer in project smali by JesusFreke.

the class ErrorReporter method submit.

@Override
public boolean submit(IdeaLoggingEvent[] events, String additionalInfo, Component parentComponent, final Consumer<SubmittedReportInfo> consumer) {
    IdeaLoggingEvent event = events[0];
    ErrorBean bean = new ErrorBean(event.getThrowable(), IdeaLogger.ourLastActionId);
    final DataContext dataContext = DataManager.getInstance().getDataContext(parentComponent);
    bean.setDescription(additionalInfo);
    bean.setMessage(event.getMessage());
    Throwable throwable = event.getThrowable();
    if (throwable != null) {
        final PluginId pluginId = IdeErrorsDialog.findPluginId(throwable);
        if (pluginId != null) {
            final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId);
            if (ideaPluginDescriptor != null && !ideaPluginDescriptor.isBundled()) {
                bean.setPluginName(ideaPluginDescriptor.getName());
                bean.setPluginVersion(ideaPluginDescriptor.getVersion());
            }
        }
    }
    Object data = event.getData();
    if (data instanceof LogMessageEx) {
        bean.setAttachments(((LogMessageEx) data).getAttachments());
    }
    Map<String, String> reportValues = ITNProxy.createParameters(bean);
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    Consumer<String> successCallback = new Consumer<String>() {

        @Override
        public void consume(String token) {
            final SubmittedReportInfo reportInfo = new SubmittedReportInfo(null, "Issue " + token, SubmittedReportInfo.SubmissionStatus.NEW_ISSUE);
            consumer.consume(reportInfo);
            ReportMessages.GROUP.createNotification(ReportMessages.ERROR_REPORT, "Submitted", NotificationType.INFORMATION, null).setImportant(false).notify(project);
        }
    };
    Consumer<Exception> errorCallback = new Consumer<Exception>() {

        @Override
        public void consume(Exception e) {
            String message = String.format("<html>There was an error while creating a GitHub issue: %s<br>" + "Please consider manually creating an issue on the " + "<a href=\"https://github.com/JesusFreke/smali/issues\">Smali Issue Tracker</a></html>", e.getMessage());
            ReportMessages.GROUP.createNotification(ReportMessages.ERROR_REPORT, message, NotificationType.ERROR, NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project);
        }
    };
    GithubFeedbackTask task = new GithubFeedbackTask(project, "Submitting error report", true, reportValues, successCallback, errorCallback);
    if (project == null) {
        task.run(new EmptyProgressIndicator());
    } else {
        ProgressManager.getInstance().run(task);
    }
    return true;
}
Also used : EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) LogMessageEx(com.intellij.diagnostic.LogMessageEx) IdeaPluginDescriptor(com.intellij.ide.plugins.IdeaPluginDescriptor) PluginId(com.intellij.openapi.extensions.PluginId) IdeaLoggingEvent(com.intellij.openapi.diagnostic.IdeaLoggingEvent) Project(com.intellij.openapi.project.Project) DataContext(com.intellij.openapi.actionSystem.DataContext) Consumer(com.intellij.util.Consumer) ErrorBean(com.intellij.errorreport.bean.ErrorBean) SubmittedReportInfo(com.intellij.openapi.diagnostic.SubmittedReportInfo)

Example 9 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class ProjectTaskManagerImpl method run.

@Override
public void run(@NotNull ProjectTaskContext context, @NotNull ProjectTask projectTask, @Nullable ProjectTaskNotification callback) {
    List<Pair<ProjectTaskRunner, Collection<? extends ProjectTask>>> toRun = new SmartList<>();
    Consumer<Collection<? extends ProjectTask>> taskClassifier = tasks -> {
        Map<ProjectTaskRunner, ? extends List<? extends ProjectTask>> toBuild = tasks.stream().collect(Collectors.groupingBy(aTask -> {
            for (ProjectTaskRunner runner : getTaskRunners()) {
                if (runner.canRun(aTask))
                    return runner;
            }
            return myDefaultProjectTaskRunner;
        }));
        for (Map.Entry<ProjectTaskRunner, ? extends List<? extends ProjectTask>> entry : toBuild.entrySet()) {
            toRun.add(Pair.create(entry.getKey(), entry.getValue()));
        }
    };
    visitTasks(projectTask instanceof ProjectTaskList ? (ProjectTaskList) projectTask : Collections.singleton(projectTask), taskClassifier);
    if (toRun.isEmpty()) {
        sendSuccessNotify(callback);
        return;
    }
    AtomicInteger inProgressCounter = new AtomicInteger(toRun.size());
    AtomicInteger errorsCounter = new AtomicInteger();
    AtomicInteger warningsCounter = new AtomicInteger();
    AtomicBoolean abortedFlag = new AtomicBoolean(false);
    ProjectTaskNotification chunkStatusNotification = callback == null ? null : new ProjectTaskNotification() {

        @Override
        public void finished(@NotNull ProjectTaskResult executionResult) {
            int inProgress = inProgressCounter.decrementAndGet();
            int allErrors = errorsCounter.addAndGet(executionResult.getErrors());
            int allWarnings = warningsCounter.addAndGet(executionResult.getWarnings());
            if (executionResult.isAborted()) {
                abortedFlag.set(true);
            }
            if (inProgress == 0) {
                callback.finished(new ProjectTaskResult(abortedFlag.get(), allErrors, allWarnings));
            }
        }
    };
    toRun.forEach(pair -> {
        if (pair.second.isEmpty()) {
            sendSuccessNotify(chunkStatusNotification);
        } else {
            pair.first.run(myProject, context, chunkStatusNotification, pair.second);
        }
    });
}
Also used : java.util(java.util) ModuleManager(com.intellij.openapi.module.ModuleManager) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ProjectFileIndex(com.intellij.openapi.roots.ProjectFileIndex) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Artifact(com.intellij.packaging.artifacts.Artifact) ContainerUtil(com.intellij.util.containers.ContainerUtil) Collectors(java.util.stream.Collectors) Nullable(org.jetbrains.annotations.Nullable) ContainerUtil.list(com.intellij.util.containers.ContainerUtil.list) SmartList(com.intellij.util.SmartList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContainerUtil.map(com.intellij.util.containers.ContainerUtil.map) Pair(com.intellij.openapi.util.Pair) Project(com.intellij.openapi.project.Project) Module(com.intellij.openapi.module.Module) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) com.intellij.task(com.intellij.task) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SmartList(com.intellij.util.SmartList) SmartList(com.intellij.util.SmartList) Pair(com.intellij.openapi.util.Pair)

Example 10 with Consumer

use of com.intellij.util.Consumer in project intellij-community by JetBrains.

the class PsiElementListNavigator method navigateOrCreatePopup.

/**
   * listUpdaterTask should be started after alarm is initialized so one-item popup won't blink
   */
@Nullable
public static JBPopup navigateOrCreatePopup(@NotNull final NavigatablePsiElement[] targets, final String title, final String findUsagesTitle, final ListCellRenderer listRenderer, @Nullable final ListBackgroundUpdaterTask listUpdaterTask, @NotNull final Consumer<Object[]> consumer) {
    if (targets.length == 0)
        return null;
    if (targets.length == 1 && (listUpdaterTask == null || listUpdaterTask.isFinished())) {
        consumer.consume(targets);
        return null;
    }
    final CollectionListModel<NavigatablePsiElement> model = new CollectionListModel<>(targets);
    final JBList list = new JBList(model);
    HintUpdateSupply.installSimpleHintUpdateSupply(list);
    list.setTransferHandler(new TransferHandler() {

        @Nullable
        @Override
        protected Transferable createTransferable(JComponent c) {
            final Object[] selectedValues = list.getSelectedValues();
            final PsiElement[] copy = new PsiElement[selectedValues.length];
            for (int i = 0; i < selectedValues.length; i++) {
                copy[i] = (PsiElement) selectedValues[i];
            }
            return new PsiCopyPasteManager.MyTransferable(copy);
        }

        @Override
        public int getSourceActions(JComponent c) {
            return COPY;
        }
    });
    list.setCellRenderer(listRenderer);
    list.setFont(EditorUtil.getEditorFont());
    final PopupChooserBuilder builder = new PopupChooserBuilder(list);
    if (listRenderer instanceof PsiElementListCellRenderer) {
        ((PsiElementListCellRenderer) listRenderer).installSpeedSearch(builder);
    }
    PopupChooserBuilder popupChooserBuilder = builder.setTitle(title).setMovable(true).setResizable(true).setItemChoosenCallback(() -> {
        int[] ids = list.getSelectedIndices();
        if (ids == null || ids.length == 0)
            return;
        Object[] selectedElements = list.getSelectedValues();
        consumer.consume(selectedElements);
    }).setCancelCallback(() -> {
        HintUpdateSupply.hideHint(list);
        if (listUpdaterTask != null) {
            listUpdaterTask.cancelTask();
        }
        return true;
    });
    final Ref<UsageView> usageView = new Ref<>();
    if (findUsagesTitle != null) {
        popupChooserBuilder = popupChooserBuilder.setCouldPin(popup -> {
            final List<NavigatablePsiElement> items = model.getItems();
            usageView.set(FindUtil.showInUsageView(null, items.toArray(new PsiElement[items.size()]), findUsagesTitle, targets[0].getProject()));
            popup.cancel();
            return false;
        });
    }
    final JBPopup popup = popupChooserBuilder.createPopup();
    builder.getScrollPane().setBorder(null);
    builder.getScrollPane().setViewportBorder(null);
    if (listUpdaterTask != null) {
        listUpdaterTask.init((AbstractPopup) popup, list, usageView);
    }
    return popup;
}
Also used : EditorUtil(com.intellij.openapi.editor.ex.util.EditorUtil) Transferable(java.awt.datatransfer.Transferable) PsiCopyPasteManager(com.intellij.ide.PsiCopyPasteManager) PsiElement(com.intellij.psi.PsiElement) Logger(com.intellij.openapi.diagnostic.Logger) ProgressManager(com.intellij.openapi.progress.ProgressManager) JBList(com.intellij.ui.components.JBList) AbstractPopup(com.intellij.ui.popup.AbstractPopup) CollectionListModel(com.intellij.ui.CollectionListModel) NavigatablePsiElement(com.intellij.psi.NavigatablePsiElement) Editor(com.intellij.openapi.editor.Editor) JBPopup(com.intellij.openapi.ui.popup.JBPopup) MouseEvent(java.awt.event.MouseEvent) ListBackgroundUpdaterTask(com.intellij.codeInsight.navigation.ListBackgroundUpdaterTask) HintUpdateSupply(com.intellij.ui.popup.HintUpdateSupply) UsageView(com.intellij.usages.UsageView) Nullable(org.jetbrains.annotations.Nullable) PopupChooserBuilder(com.intellij.openapi.ui.popup.PopupChooserBuilder) List(java.util.List) FindUtil(com.intellij.find.FindUtil) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) RelativePoint(com.intellij.ui.awt.RelativePoint) PsiElementListCellRenderer(com.intellij.ide.util.PsiElementListCellRenderer) Consumer(com.intellij.util.Consumer) Alarm(com.intellij.util.Alarm) javax.swing(javax.swing) Transferable(java.awt.datatransfer.Transferable) PsiCopyPasteManager(com.intellij.ide.PsiCopyPasteManager) UsageView(com.intellij.usages.UsageView) Ref(com.intellij.openapi.util.Ref) JBList(com.intellij.ui.components.JBList) JBList(com.intellij.ui.components.JBList) List(java.util.List) CollectionListModel(com.intellij.ui.CollectionListModel) PopupChooserBuilder(com.intellij.openapi.ui.popup.PopupChooserBuilder) JBPopup(com.intellij.openapi.ui.popup.JBPopup) Nullable(org.jetbrains.annotations.Nullable) PsiElement(com.intellij.psi.PsiElement) NavigatablePsiElement(com.intellij.psi.NavigatablePsiElement) NavigatablePsiElement(com.intellij.psi.NavigatablePsiElement) PsiElementListCellRenderer(com.intellij.ide.util.PsiElementListCellRenderer) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

Consumer (com.intellij.util.Consumer)59 NotNull (org.jetbrains.annotations.NotNull)41 Project (com.intellij.openapi.project.Project)37 Nullable (org.jetbrains.annotations.Nullable)33 VirtualFile (com.intellij.openapi.vfs.VirtualFile)26 List (java.util.List)22 ApplicationManager (com.intellij.openapi.application.ApplicationManager)17 StringUtil (com.intellij.openapi.util.text.StringUtil)17 javax.swing (javax.swing)16 ContainerUtil (com.intellij.util.containers.ContainerUtil)15 Logger (com.intellij.openapi.diagnostic.Logger)14 Module (com.intellij.openapi.module.Module)12 java.awt (java.awt)12 Pair (com.intellij.openapi.util.Pair)11 java.util (java.util)11 File (java.io.File)10 Collection (java.util.Collection)10 PsiElement (com.intellij.psi.PsiElement)9 PsiFile (com.intellij.psi.PsiFile)9 DataContext (com.intellij.openapi.actionSystem.DataContext)8