Search in sources :

Example 36 with Computable

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

the class JavaOverridingMethodsSearcher method compute.

@NotNull
private static Iterable<PsiMethod> compute(@NotNull PsiMethod method, @NotNull Project project) {
    Application application = ApplicationManager.getApplication();
    final PsiClass containingClass = application.runReadAction((Computable<PsiClass>) method::getContainingClass);
    assert containingClass != null;
    Collection<PsiMethod> result = new LinkedHashSet<>();
    Processor<PsiClass> inheritorsProcessor = inheritor -> {
        PsiMethod found = application.runReadAction((Computable<PsiMethod>) () -> findOverridingMethod(project, inheritor, method, containingClass));
        if (found != null) {
            result.add(found);
        }
        return true;
    };
    // use wider scope to handle public method defined in package-private class which is subclassed by public class in the same package which is subclassed by public class from another package with redefined method
    SearchScope allScope = GlobalSearchScope.allScope(project);
    boolean success = ClassInheritorsSearch.search(containingClass, allScope, true).forEach(inheritorsProcessor);
    assert success;
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ProgressManager(com.intellij.openapi.progress.ProgressManager) TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) Application(com.intellij.openapi.application.Application) MethodSignatureUtil(com.intellij.psi.util.MethodSignatureUtil) VirtualFile(com.intellij.openapi.vfs.VirtualFile) QueryExecutor(com.intellij.util.QueryExecutor) OverridingMethodsSearch(com.intellij.psi.search.searches.OverridingMethodsSearch) Collection(java.util.Collection) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Computable(com.intellij.openapi.util.Computable) SearchScope(com.intellij.psi.search.SearchScope) ReadAction(com.intellij.openapi.application.ReadAction) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Nullable(org.jetbrains.annotations.Nullable) PsiSearchScopeUtil(com.intellij.psi.search.PsiSearchScopeUtil) MethodSignature(com.intellij.psi.util.MethodSignature) Processor(com.intellij.util.Processor) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Project(com.intellij.openapi.project.Project) com.intellij.psi(com.intellij.psi) ClassInheritorsSearch(com.intellij.psi.search.searches.ClassInheritorsSearch) NotNull(org.jetbrains.annotations.NotNull) LinkedHashSet(java.util.LinkedHashSet) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) SearchScope(com.intellij.psi.search.SearchScope) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Application(com.intellij.openapi.application.Application) Computable(com.intellij.openapi.util.Computable) NotNull(org.jetbrains.annotations.NotNull)

Example 37 with Computable

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

the class GitPull method displayDialog.

@Override
protected DialogState displayDialog(@NotNull Project project, @NotNull List<VirtualFile> gitRoots, @NotNull VirtualFile defaultRoot) {
    final GitPullDialog dialog = new GitPullDialog(project, gitRoots, defaultRoot);
    if (!dialog.showAndGet()) {
        return null;
    }
    GitRepositoryManager repositoryManager = GitUtil.getRepositoryManager(project);
    GitRepository repository = repositoryManager.getRepositoryForRoot(dialog.gitRoot());
    assert repository != null : "Repository can't be null for root " + dialog.gitRoot();
    String remoteOrUrl = dialog.getRemote();
    if (remoteOrUrl == null) {
        return null;
    }
    GitRemote remote = GitUtil.findRemoteByName(repository, remoteOrUrl);
    final List<String> urls = remote == null ? Collections.singletonList(remoteOrUrl) : remote.getUrls();
    Computable<GitLineHandler> handlerProvider = new Computable<GitLineHandler>() {

        @Override
        public GitLineHandler compute() {
            return dialog.makeHandler(urls);
        }
    };
    return new DialogState(dialog.gitRoot(), GitBundle.message("pulling.title", dialog.getRemote()), handlerProvider);
}
Also used : GitRemote(git4idea.repo.GitRemote) GitRepository(git4idea.repo.GitRepository) GitPullDialog(git4idea.merge.GitPullDialog) GitLineHandler(git4idea.commands.GitLineHandler) GitRepositoryManager(git4idea.repo.GitRepositoryManager) Computable(com.intellij.openapi.util.Computable)

Example 38 with Computable

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

the class ExportTestResultsAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    LOG.assertTrue(project != null);
    final ExportTestResultsConfiguration config = ExportTestResultsConfiguration.getInstance(project);
    final String name = ExecutionBundle.message("export.test.results.filename", PathUtil.suggestFileName(myRunConfiguration.getName()));
    String filename = name + "." + config.getExportFormat().getDefaultExtension();
    boolean showDialog = true;
    while (showDialog) {
        final ExportTestResultsDialog d = new ExportTestResultsDialog(project, config, filename);
        if (!d.showAndGet()) {
            return;
        }
        filename = d.getFileName();
        showDialog = getOutputFile(config, project, filename).exists() && Messages.showOkCancelDialog(project, ExecutionBundle.message("export.test.results.file.exists.message", filename), ExecutionBundle.message("export.test.results.file.exists.title"), Messages.getQuestionIcon()) != Messages.OK;
    }
    final String filename_ = filename;
    ProgressManager.getInstance().run(new Task.Backgroundable(project, ExecutionBundle.message("export.test.results.task.name"), false, new PerformInBackgroundOption() {

        @Override
        public boolean shouldStartInBackground() {
            return true;
        }

        @Override
        public void processSentToBackground() {
        }
    }) {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
            final File outputFile = getOutputFile(config, project, filename_);
            final String outputText;
            try {
                outputText = getOutputText(config);
                if (outputText == null) {
                    return;
                }
            } catch (IOException | SAXException | TransformerException ex) {
                LOG.warn(ex);
                showBalloon(project, MessageType.ERROR, ExecutionBundle.message("export.test.results.failed", ex.getMessage()), null);
                return;
            } catch (RuntimeException ex) {
                ExportTestResultsConfiguration c = new ExportTestResultsConfiguration();
                c.setExportFormat(ExportTestResultsConfiguration.ExportFormat.Xml);
                c.setOpenResults(false);
                try {
                    String xml = getOutputText(c);
                    LOG.error(LogMessageEx.createEvent("Failed to export test results", ExceptionUtil.getThrowableText(ex), null, null, new Attachment("dump.xml", xml)));
                } catch (Throwable ignored) {
                    LOG.error("Failed to export test results", ex);
                }
                return;
            }
            final Ref<VirtualFile> result = new Ref<>();
            final Ref<String> error = new Ref<>();
            ApplicationManager.getApplication().invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    result.set(ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() {

                        @Override
                        public VirtualFile compute() {
                            outputFile.getParentFile().mkdirs();
                            final VirtualFile parent = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(outputFile.getParentFile());
                            if (parent == null || !parent.isValid()) {
                                error.set(ExecutionBundle.message("failed.to.create.output.file", outputFile.getPath()));
                                return null;
                            }
                            try {
                                VirtualFile result = parent.findChild(outputFile.getName());
                                if (result == null) {
                                    result = parent.createChildData(this, outputFile.getName());
                                }
                                VfsUtil.saveText(result, outputText);
                                return result;
                            } catch (IOException e) {
                                LOG.warn(e);
                                error.set(e.getMessage());
                                return null;
                            }
                        }
                    }));
                }
            });
            if (!result.isNull()) {
                if (config.isOpenResults()) {
                    openEditorOrBrowser(result.get(), project, config.getExportFormat() == ExportTestResultsConfiguration.ExportFormat.Xml);
                } else {
                    HyperlinkListener listener = new HyperlinkListener() {

                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                openEditorOrBrowser(result.get(), project, config.getExportFormat() == ExportTestResultsConfiguration.ExportFormat.Xml);
                            }
                        }
                    };
                    showBalloon(project, MessageType.INFO, ExecutionBundle.message("export.test.results.succeeded", outputFile.getName()), listener);
                }
            } else {
                showBalloon(project, MessageType.ERROR, ExecutionBundle.message("export.test.results.failed", error.get()), null);
            }
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) HyperlinkEvent(javax.swing.event.HyperlinkEvent) Attachment(com.intellij.openapi.diagnostic.Attachment) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) Ref(com.intellij.openapi.util.Ref) HyperlinkListener(javax.swing.event.HyperlinkListener) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) Computable(com.intellij.openapi.util.Computable)

Example 39 with Computable

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

the class TodoCheckinHandlerWorker method execute.

public void execute() {
    for (Change change : changes) {
        ProgressManager.checkCanceled();
        if (change.getAfterRevision() == null)
            continue;
        final VirtualFile afterFile = getFileWithRefresh(change.getAfterRevision().getFile());
        if (afterFile == null || afterFile.isDirectory() || afterFile.getFileType().isBinary())
            continue;
        myPsiFile = null;
        if (afterFile.isValid()) {
            myPsiFile = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {

                @Override
                public PsiFile compute() {
                    return myPsiManager.findFile(afterFile);
                }
            });
        }
        if (myPsiFile == null) {
            mySkipped.add(Pair.create(change.getAfterRevision().getFile(), ourInvalidFile));
            continue;
        }
        myNewTodoItems = new ArrayList<>(Arrays.asList(ApplicationManager.getApplication().runReadAction(new Computable<TodoItem[]>() {

            @Override
            public TodoItem[] compute() {
                return mySearchHelper.findTodoItems(myPsiFile);
            }
        })));
        applyFilterAndRemoveDuplicates(myNewTodoItems, myTodoFilter);
        if (change.getBeforeRevision() == null) {
            // take just all todos
            if (myNewTodoItems.isEmpty())
                continue;
            myAddedOrEditedTodos.addAll(myNewTodoItems);
        } else {
            myEditedFileProcessor.process(change, myNewTodoItems);
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) TodoItem(com.intellij.psi.search.TodoItem) Change(com.intellij.openapi.vcs.changes.Change) Computable(com.intellij.openapi.util.Computable)

Example 40 with Computable

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

the class RenameProcessor method preprocessUsages.

@Override
public boolean preprocessUsages(@NotNull final Ref<UsageInfo[]> refUsages) {
    UsageInfo[] usagesIn = refUsages.get();
    MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    RenameUtil.addConflictDescriptions(usagesIn, conflicts);
    RenamePsiElementProcessor.forElement(myPrimaryElement).findExistingNameConflicts(myPrimaryElement, myNewName, conflicts, myAllRenames);
    if (!conflicts.isEmpty()) {
        final RefactoringEventData conflictData = new RefactoringEventData();
        conflictData.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts.values());
        myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).conflictsDetected("refactoring.rename", conflictData);
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            throw new ConflictsInTestsException(conflicts.values());
        }
        ConflictsDialog conflictsDialog = prepareConflictsDialog(conflicts, refUsages.get());
        if (!conflictsDialog.showAndGet()) {
            if (conflictsDialog.isShowConflicts())
                prepareSuccessful();
            return false;
        }
    }
    final List<UsageInfo> variableUsages = new ArrayList<>();
    if (!myRenamers.isEmpty()) {
        if (!findRenamedVariables(variableUsages))
            return false;
        final LinkedHashMap<PsiElement, String> renames = new LinkedHashMap<>();
        for (final AutomaticRenamer renamer : myRenamers) {
            final List<? extends PsiNamedElement> variables = renamer.getElements();
            for (final PsiNamedElement variable : variables) {
                final String newName = renamer.getNewName(variable);
                if (newName != null) {
                    addElement(variable, newName);
                    prepareRenaming(variable, newName, renames);
                }
            }
        }
        if (!renames.isEmpty()) {
            for (PsiElement element : renames.keySet()) {
                assertNonCompileElement(element);
            }
            myAllRenames.putAll(renames);
            final Runnable runnable = () -> {
                for (final Map.Entry<PsiElement, String> entry : renames.entrySet()) {
                    final UsageInfo[] usages = ApplicationManager.getApplication().runReadAction(new Computable<UsageInfo[]>() {

                        @Override
                        public UsageInfo[] compute() {
                            return RenameUtil.findUsages(entry.getKey(), entry.getValue(), mySearchInComments, mySearchTextOccurrences, myAllRenames);
                        }
                    });
                    Collections.addAll(variableUsages, usages);
                }
            };
            if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, RefactoringBundle.message("searching.for.variables"), true, myProject)) {
                return false;
            }
        }
    }
    final int[] choice = myAllRenames.size() > 1 ? new int[] { -1 } : null;
    try {
        for (Iterator<Map.Entry<PsiElement, String>> iterator = myAllRenames.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<PsiElement, String> entry = iterator.next();
            if (entry.getKey() instanceof PsiFile) {
                final PsiFile file = (PsiFile) entry.getKey();
                final PsiDirectory containingDirectory = file.getContainingDirectory();
                if (CopyFilesOrDirectoriesHandler.checkFileExist(containingDirectory, choice, file, entry.getValue(), "Rename")) {
                    iterator.remove();
                    continue;
                }
            }
            RenameUtil.checkRename(entry.getKey(), entry.getValue());
        }
    } catch (IncorrectOperationException e) {
        CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("rename.title"), e.getMessage(), getHelpID(), myProject);
        return false;
    }
    final Set<UsageInfo> usagesSet = ContainerUtil.newLinkedHashSet(usagesIn);
    usagesSet.addAll(variableUsages);
    final List<UnresolvableCollisionUsageInfo> conflictUsages = RenameUtil.removeConflictUsages(usagesSet);
    if (conflictUsages != null) {
        mySkippedUsages.addAll(conflictUsages);
    }
    refUsages.set(usagesSet.toArray(new UsageInfo[usagesSet.size()]));
    prepareSuccessful();
    return PsiElementRenameHandler.canRename(myProject, null, myPrimaryElement);
}
Also used : AutomaticRenamer(com.intellij.refactoring.rename.naming.AutomaticRenamer) MultiMap(com.intellij.util.containers.MultiMap) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) ConflictsDialog(com.intellij.refactoring.ui.ConflictsDialog) UsageInfo(com.intellij.usageView.UsageInfo) MoveRenameUsageInfo(com.intellij.refactoring.util.MoveRenameUsageInfo) NonCodeUsageInfo(com.intellij.refactoring.util.NonCodeUsageInfo) RelatedUsageInfo(com.intellij.refactoring.util.RelatedUsageInfo) Computable(com.intellij.openapi.util.Computable) IncorrectOperationException(com.intellij.util.IncorrectOperationException) MultiMap(com.intellij.util.containers.MultiMap)

Aggregations

Computable (com.intellij.openapi.util.Computable)49 VirtualFile (com.intellij.openapi.vfs.VirtualFile)15 NotNull (org.jetbrains.annotations.NotNull)11 Nullable (org.jetbrains.annotations.Nullable)11 Project (com.intellij.openapi.project.Project)10 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)8 PsiFile (com.intellij.psi.PsiFile)6 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)6 IncorrectOperationException (com.intellij.util.IncorrectOperationException)6 Application (com.intellij.openapi.application.Application)5 Task (com.intellij.openapi.progress.Task)5 IOException (java.io.IOException)5 ApplicationManager (com.intellij.openapi.application.ApplicationManager)4 Editor (com.intellij.openapi.editor.Editor)4 Ref (com.intellij.openapi.util.Ref)4 Module (com.intellij.openapi.module.Module)3 PsiDirectory (com.intellij.psi.PsiDirectory)3 PsiElement (com.intellij.psi.PsiElement)3 UsageInfo (com.intellij.usageView.UsageInfo)3 Logger (com.intellij.openapi.diagnostic.Logger)2