Search in sources :

Example 36 with Consumer

use of com.intellij.util.Consumer in project android by JetBrains.

the class AndroidExtractAsIncludeAction method doRefactorForPsiRange.

@Override
protected void doRefactorForPsiRange(@NotNull final Project project, @NotNull final PsiFile file, @NotNull final PsiElement from, @NotNull final PsiElement to) {
    final PsiDirectory dir = file.getContainingDirectory();
    if (dir == null) {
        return;
    }
    final AndroidFacet facet = AndroidFacet.getInstance(from);
    assert facet != null;
    final XmlTag parentTag = PsiTreeUtil.getParentOfType(from, XmlTag.class);
    assert parentTag != null;
    final List<XmlTag> tagsInRange = collectAllTags(from, to);
    assert tagsInRange.size() > 0 : "there is no tag inside the range";
    final String fileName = myTestConfig != null ? myTestConfig.myLayoutFileName : null;
    final String dirName = dir.getName();
    final FolderConfiguration config = dirName.length() > 0 ? FolderConfiguration.getConfig(dirName.split(SdkConstants.RES_QUALIFIER_SEP)) : null;
    final String title = "Extract Android Layout";
    AsyncResult<DataContext> dataContextAsyncResult = DataManager.getInstance().getDataContextFromFocus();
    dataContextAsyncResult.doWhenDone((Consumer<DataContext>) dataContext -> CommandProcessor.getInstance().executeCommand(project, new Runnable() {

        @Override
        public void run() {
            final XmlFile newFile = CreateResourceFileAction.createFileResource(facet, ResourceFolderType.LAYOUT, fileName, "temp_root", config, true, title, null, dataContext);
            if (newFile != null) {
                ApplicationManager.getApplication().runWriteAction(new Runnable() {

                    @Override
                    public void run() {
                        doRefactor(facet, file, newFile, from, to, parentTag, tagsInRange.size() > 1);
                    }
                });
            }
        }
    }, title, null, UndoConfirmationPolicy.REQUEST_CONFIRMATION));
}
Also used : Include(org.jetbrains.android.dom.layout.Include) DataContext(com.intellij.openapi.actionSystem.DataContext) SdkConstants(com.android.SdkConstants) XmlFile(com.intellij.psi.xml.XmlFile) ResourceFolderType(com.android.resources.ResourceFolderType) Document(com.intellij.openapi.editor.Document) HashSet(com.intellij.util.containers.HashSet) NonNls(org.jetbrains.annotations.NonNls) ResourceType(com.android.resources.ResourceType) DomElement(com.intellij.util.xml.DomElement) CreateResourceFileAction(org.jetbrains.android.actions.CreateResourceFileAction) ArrayList(java.util.ArrayList) IncludeReference(com.android.tools.idea.rendering.IncludeReference) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) Project(com.intellij.openapi.project.Project) FolderConfiguration(com.android.ide.common.resources.configuration.FolderConfiguration) UndoConfirmationPolicy(com.intellij.openapi.command.UndoConfirmationPolicy) DataManager(com.intellij.ide.DataManager) AsyncResult(com.intellij.openapi.util.AsyncResult) XmlTag(com.intellij.psi.xml.XmlTag) ResourceHelper(com.android.tools.idea.res.ResourceHelper) LayoutViewElement(org.jetbrains.android.dom.layout.LayoutViewElement) XmlAttribute(com.intellij.psi.xml.XmlAttribute) Set(java.util.Set) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) TextRange(com.intellij.openapi.util.TextRange) AndroidCommonUtils(org.jetbrains.android.util.AndroidCommonUtils) TestOnly(org.jetbrains.annotations.TestOnly) CommandProcessor(com.intellij.openapi.command.CommandProcessor) Nullable(org.jetbrains.annotations.Nullable) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) List(java.util.List) ApplicationManager(com.intellij.openapi.application.ApplicationManager) com.intellij.psi(com.intellij.psi) DomManager(com.intellij.util.xml.DomManager) NotNull(org.jetbrains.annotations.NotNull) Consumer(com.intellij.util.Consumer) DataContext(com.intellij.openapi.actionSystem.DataContext) XmlFile(com.intellij.psi.xml.XmlFile) FolderConfiguration(com.android.ide.common.resources.configuration.FolderConfiguration) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) XmlTag(com.intellij.psi.xml.XmlTag)

Example 37 with Consumer

use of com.intellij.util.Consumer in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoRenameQuickFix method invoke.

@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    if (!FileModificationService.getInstance().preparePsiElementsForWrite(startElement))
        return;
    Runnable runnable = () -> {
        AsyncResult<DataContext> dataContextContainer = DataManager.getInstance().getDataContextFromFocus();
        dataContextContainer.doWhenDone(new Consumer<DataContext>() {

            @Override
            public void consume(DataContext dataContext) {
                RenameHandler renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext);
                if (renameHandler != null) {
                    renameHandler.invoke(project, new PsiElement[] { startElement }, dataContext);
                } else {
                    RefactoringActionHandler renameRefactoringHandler = RefactoringActionHandlerFactory.getInstance().createRenameHandler();
                    renameRefactoringHandler.invoke(project, new PsiElement[] { startElement }, dataContext);
                }
            }
        });
    };
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        runnable.run();
    } else {
        ApplicationManager.getApplication().invokeLater(runnable, project.getDisposed());
    }
}
Also used : DataContext(com.intellij.openapi.actionSystem.DataContext) Consumer(com.intellij.util.Consumer) RenameHandler(com.intellij.refactoring.rename.RenameHandler) RefactoringActionHandler(com.intellij.refactoring.RefactoringActionHandler) AsyncResult(com.intellij.openapi.util.AsyncResult)

Example 38 with Consumer

use of com.intellij.util.Consumer in project android by JetBrains.

the class AndroidGradleTestCase method invokeGradle.

@NotNull
private static GradleInvocationResult invokeGradle(@NotNull Project project, @NotNull Consumer<GradleBuildInvoker> gradleInvocationTask) throws InterruptedException {
    Ref<GradleInvocationResult> resultRef = new Ref<>();
    CountDownLatch latch = new CountDownLatch(1);
    GradleBuildInvoker gradleBuildInvoker = GradleBuildInvoker.getInstance(project);
    GradleBuildInvoker.AfterGradleInvocationTask task = result -> {
        resultRef.set(result);
        latch.countDown();
    };
    gradleBuildInvoker.add(task);
    try {
        gradleInvocationTask.consume(gradleBuildInvoker);
    } finally {
        gradleBuildInvoker.remove(task);
    }
    latch.await();
    GradleInvocationResult result = resultRef.get();
    assert result != null;
    return result;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Projects.isLegacyIdeaAndroidProject(com.android.tools.idea.gradle.util.Projects.isLegacyIdeaAndroidProject) TestFixtureBuilder(com.intellij.testFramework.fixtures.TestFixtureBuilder) PsiManager(com.intellij.psi.PsiManager) Matcher(java.util.regex.Matcher) ProjectManager(com.intellij.openapi.project.ProjectManager) JavaTestFixtureFactory(com.intellij.testFramework.fixtures.JavaTestFixtureFactory) GradleProjectImporter(com.android.tools.idea.gradle.project.importing.GradleProjectImporter) Messages(com.intellij.openapi.ui.Messages) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) GradleSyncInvoker(com.android.tools.idea.gradle.project.sync.GradleSyncInvoker) Truth.assertAbout(com.google.common.truth.Truth.assertAbout) IdeInfo(com.android.tools.idea.IdeInfo) PlatformTestCase(com.intellij.testFramework.PlatformTestCase) EmptyModuleType(com.intellij.openapi.module.EmptyModuleType) AndroidGradleProjectComponent(com.android.tools.idea.gradle.project.AndroidGradleProjectComponent) LocalProperties(com.android.tools.idea.gradle.util.LocalProperties) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) AndroidProjectInfo(com.android.tools.idea.project.AndroidProjectInfo) Nullable(org.jetbrains.annotations.Nullable) CountDownLatch(java.util.concurrent.CountDownLatch) FileSubject.file(com.android.tools.idea.testing.FileSubject.file) IdeaTestApplication(com.intellij.idea.IdeaTestApplication) Pattern(java.util.regex.Pattern) ConfigurationException(com.intellij.openapi.options.ConfigurationException) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) GradleSyncState(com.android.tools.idea.gradle.project.sync.GradleSyncState) Consumer(com.intellij.util.Consumer) GradleSyncListener(com.android.tools.idea.gradle.project.sync.GradleSyncListener) JDK_1_8(com.intellij.pom.java.LanguageLevel.JDK_1_8) WriteCommandAction.runWriteCommandAction(com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction) WriteAction(com.intellij.openapi.application.WriteAction) SdkConstants(com.android.SdkConstants) ModuleManager(com.intellij.openapi.module.ModuleManager) MINUTES(java.util.concurrent.TimeUnit.MINUTES) Lists(com.google.common.collect.Lists) IdeaProjectTestFixture(com.intellij.testFramework.fixtures.IdeaProjectTestFixture) Files(com.google.common.io.Files) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) ModuleType(com.intellij.openapi.module.ModuleType) AndroidModuleModel(com.android.tools.idea.gradle.project.model.AndroidModuleModel) AndroidTestBase(org.jetbrains.android.AndroidTestBase) VfsUtilCore.virtualToIoFile(com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile) Charsets(com.google.common.base.Charsets) SIMPLE_APPLICATION(com.android.tools.idea.testing.TestProjectPaths.SIMPLE_APPLICATION) Files.write(com.google.common.io.Files.write) GradleBuildInvoker(com.android.tools.idea.gradle.project.build.invoker.GradleBuildInvoker) ProjectManagerEx(com.intellij.openapi.project.ex.ProjectManagerEx) AndroidFacet(org.jetbrains.android.facet.AndroidFacet) IOException(java.io.IOException) StringUtil.isEmpty(com.intellij.openapi.util.text.StringUtil.isEmpty) GradleWrapper(com.android.tools.idea.gradle.util.GradleWrapper) TestDialog(com.intellij.openapi.ui.TestDialog) Truth.assertThat(com.google.common.truth.Truth.assertThat) Sdk(com.intellij.openapi.projectRoots.Sdk) RegEx(javax.annotation.RegEx) File(java.io.File) IdeSdks(com.android.tools.idea.sdk.IdeSdks) TestUtils.getWorkspaceFile(com.android.testutils.TestUtils.getWorkspaceFile) TestUtils.getSdk(com.android.testutils.TestUtils.getSdk) Result(com.intellij.openapi.application.Result) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) Jdks(com.android.tools.idea.sdk.Jdks) IdeaTestFixtureFactory(com.intellij.testFramework.fixtures.IdeaTestFixtureFactory) ModuleFileType(com.intellij.ide.highlighter.ModuleFileType) GradleInvocationResult(com.android.tools.idea.gradle.project.build.invoker.GradleInvocationResult) Ref(com.intellij.openapi.util.Ref) CountDownLatch(java.util.concurrent.CountDownLatch) GradleBuildInvoker(com.android.tools.idea.gradle.project.build.invoker.GradleBuildInvoker) NotNull(org.jetbrains.annotations.NotNull)

Example 39 with Consumer

use of com.intellij.util.Consumer in project android by JetBrains.

the class ErrorReporter method submit.

@Override
public boolean submit(@NotNull IdeaLoggingEvent[] events, @Nullable String description, @Nullable Component parentComponent, @NotNull Consumer<SubmittedReportInfo> callback) {
    IdeaLoggingEvent event = events[0];
    ErrorBean bean = new ErrorBean(event.getThrowable(), IdeaLogger.ourLastActionId);
    final DataContext dataContext = DataManager.getInstance().getDataContext(parentComponent);
    bean.setDescription(description);
    bean.setMessage(event.getMessage());
    Throwable t = event.getThrowable();
    if (t != null) {
        final PluginId pluginId = IdeErrorsDialog.findPluginId(t);
        if (pluginId != null) {
            final IdeaPluginDescriptor ideaPluginDescriptor = PluginManager.getPlugin(pluginId);
            if (ideaPluginDescriptor != null && (!ideaPluginDescriptor.isBundled() || ideaPluginDescriptor.allowBundledUpdate())) {
                bean.setPluginName(ideaPluginDescriptor.getName());
                bean.setPluginVersion(ideaPluginDescriptor.getVersion());
            }
        }
    }
    Object data = event.getData();
    // Early escape (and no UI impact) if these are analytics events being pushed from the platform
    if (handleAnalyticsReports(t, data)) {
        return true;
    }
    if (data instanceof AbstractMessage) {
        bean.setAttachments(((AbstractMessage) data).getIncludedAttachments());
    }
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    Consumer<String> successCallback = token -> {
        final SubmittedReportInfo reportInfo = new SubmittedReportInfo(null, "Issue " + token, SubmittedReportInfo.SubmissionStatus.NEW_ISSUE);
        callback.consume(reportInfo);
        ReportMessages.GROUP.createNotification(ReportMessages.ERROR_REPORT, "Submitted", NotificationType.INFORMATION, null).setImportant(false).notify(project);
    };
    Consumer<Exception> errorCallback = e -> {
        String message = AndroidBundle.message("error.report.at.b.android", e.getMessage());
        ReportMessages.GROUP.createNotification(ReportMessages.ERROR_REPORT, message, NotificationType.ERROR, NotificationListener.URL_OPENING_LISTENER).setImportant(false).notify(project);
    };
    Task.Backgroundable feedbackTask;
    if (data instanceof ErrorReportCustomizer) {
        feedbackTask = ((ErrorReportCustomizer) data).makeReportingTask(project, FEEDBACK_TASK_TITLE, true, bean, successCallback, errorCallback);
    } else {
        List<Pair<String, String>> kv = IdeaITNProxy.getKeyValuePairs(null, null, bean, IdeaLogger.getOurCompilationTimestamp(), ApplicationManager.getApplication(), (ApplicationInfoEx) ApplicationInfo.getInstance(), ApplicationNamesInfo.getInstance(), UpdateSettings.getInstance());
        feedbackTask = new SubmitCrashReportTask(project, FEEDBACK_TASK_TITLE, true, t, pair2map(kv), successCallback, errorCallback);
    }
    if (project == null) {
        feedbackTask.run(new EmptyProgressIndicator());
    } else {
        ProgressManager.getInstance().run(feedbackTask);
    }
    return true;
}
Also used : SubmittedReportInfo(com.intellij.openapi.diagnostic.SubmittedReportInfo) DataContext(com.intellij.openapi.actionSystem.DataContext) IdeErrorsDialog(com.intellij.diagnostic.IdeErrorsDialog) ReportMessages(com.intellij.diagnostic.ReportMessages) Task(com.intellij.openapi.progress.Task) CrashReport(com.android.tools.idea.diagnostics.crash.CrashReport) ApplicationInfo(com.intellij.openapi.application.ApplicationInfo) Map(java.util.Map) ApplicationNamesInfo(com.intellij.openapi.application.ApplicationNamesInfo) Project(com.intellij.openapi.project.Project) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) ApplicationInfoEx(com.intellij.openapi.application.ex.ApplicationInfoEx) ErrorReportSubmitter(com.intellij.openapi.diagnostic.ErrorReportSubmitter) DataManager(com.intellij.ide.DataManager) IdeaPluginDescriptor(com.intellij.ide.plugins.IdeaPluginDescriptor) PluginManager(com.intellij.ide.plugins.PluginManager) ProgressManager(com.intellij.openapi.progress.ProgressManager) AndroidBundle(org.jetbrains.android.util.AndroidBundle) IdeaLogger(com.intellij.idea.IdeaLogger) IdeaLoggingEvent(com.intellij.openapi.diagnostic.IdeaLoggingEvent) Nullable(com.android.annotations.Nullable) Maps(com.google.common.collect.Maps) NotificationListener(com.intellij.notification.NotificationListener) NotificationType(com.intellij.notification.NotificationType) java.awt(java.awt) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) ErrorBean(com.intellij.errorreport.bean.ErrorBean) List(java.util.List) AbstractMessage(com.intellij.diagnostic.AbstractMessage) CrashReporter(com.android.tools.idea.diagnostics.crash.CrashReporter) UpdateSettings(com.intellij.openapi.updateSettings.impl.UpdateSettings) Pair(com.intellij.openapi.util.Pair) ApplicationManager(com.intellij.openapi.application.ApplicationManager) IdeaITNProxy(org.jetbrains.android.diagnostics.error.IdeaITNProxy) NotNull(org.jetbrains.annotations.NotNull) PluginId(com.intellij.openapi.extensions.PluginId) Consumer(com.intellij.util.Consumer) Task(com.intellij.openapi.progress.Task) AbstractMessage(com.intellij.diagnostic.AbstractMessage) EmptyProgressIndicator(com.intellij.openapi.progress.EmptyProgressIndicator) 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) ErrorBean(com.intellij.errorreport.bean.ErrorBean) SubmittedReportInfo(com.intellij.openapi.diagnostic.SubmittedReportInfo) Pair(com.intellij.openapi.util.Pair)

Example 40 with Consumer

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

the class ShowUiRouterStatesNewDiagramAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    UsageTrigger.trigger(USAGE_KEY);
    final Project project = e.getProject();
    if (project == null)
        return;
    final AngularUiRouterDiagramProvider diagramProvider = (AngularUiRouterDiagramProvider) DiagramProvider.findByID(AngularUiRouterDiagramProvider.ANGULAR_UI_ROUTER);
    if (diagramProvider == null)
        return;
    List<Pair<String, AngularUiRouterGraphBuilder>> graphBuilders = new ArrayList<>();
    ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
        ApplicationManager.getApplication().runReadAction(() -> {
            final AngularUiRouterDiagramBuilder builder = new AngularUiRouterDiagramBuilder(project);
            builder.build();
            final Map<VirtualFile, RootTemplate> rootTemplates = builder.getRootTemplates();
            for (Map.Entry<VirtualFile, Map<String, UiRouterState>> entry : builder.getDefiningFiles2States().entrySet()) {
                final AngularUiRouterGraphBuilder graphBuilder = new AngularUiRouterGraphBuilder(project, entry.getValue(), builder.getTemplatesMap(), null, entry.getKey());
                graphBuilders.add(Pair.create(entry.getKey().getName(), graphBuilder));
            }
            for (Map.Entry<VirtualFile, Map<String, UiRouterState>> entry : builder.getRootTemplates2States().entrySet()) {
                final AngularUiRouterGraphBuilder graphBuilder = new AngularUiRouterGraphBuilder(project, entry.getValue(), builder.getTemplatesMap(), rootTemplates.get(entry.getKey()), entry.getKey());
                graphBuilders.add(Pair.create(entry.getKey().getName(), graphBuilder));
            }
        });
    }, "Building " + diagramProvider.getPresentableName() + " diagram", false, project);
    final AngularUiRouterProviderContext routerProviderContext = AngularUiRouterProviderContext.getInstance(project);
    routerProviderContext.reset();
    final Consumer<AngularUiRouterGraphBuilder> consumer = graphBuilder -> {
        final AngularUiRouterGraphBuilder.GraphNodesBuilder nodesBuilder = graphBuilder.createDataModel(diagramProvider);
        routerProviderContext.registerNodesBuilder(nodesBuilder);
        final DiagramObject element = nodesBuilder.getRootNode().getIdentifyingElement();
        final Runnable callback = show(element, diagramProvider, project, null, Collections.emptyList());
        if (callback != null) {
            callback.run();
        }
    };
    if (graphBuilders.isEmpty()) {
        Messages.showInfoMessage(project, "No router states found.", DESCRIPTION);
        return;
    }
    if (graphBuilders.size() == 1)
        consumer.consume(graphBuilders.get(0).getSecond());
    else
        filterGraphBuilders(project, graphBuilders, consumer);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) DiagramProvider(com.intellij.diagram.DiagramProvider) ProgressManager(com.intellij.openapi.progress.ProgressManager) JBList(com.intellij.ui.components.JBList) ArrayUtil(com.intellij.util.ArrayUtil) VirtualFile(com.intellij.openapi.vfs.VirtualFile) AngularJSIcons(icons.AngularJSIcons) ArrayList(java.util.ArrayList) List(java.util.List) AngularIndexUtil(org.angularjs.index.AngularIndexUtil) JBPopupFactory(com.intellij.openapi.ui.popup.JBPopupFactory) ShowDiagram(com.intellij.uml.core.actions.ShowDiagram) Map(java.util.Map) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) Pair(com.intellij.openapi.util.Pair) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Project(com.intellij.openapi.project.Project) Messages(com.intellij.openapi.ui.Messages) Collections(java.util.Collections) Consumer(com.intellij.util.Consumer) UsageTrigger(com.intellij.internal.statistic.UsageTrigger) ArrayList(java.util.ArrayList) Project(com.intellij.openapi.project.Project) Map(java.util.Map) Pair(com.intellij.openapi.util.Pair)

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