Search in sources :

Example 26 with Computable

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

the class CreateFileResourceQuickFix method applyFix.

@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final VirtualFile resourceDir = myFacet.getPrimaryResourceDir();
    if (resourceDir == null) {
        return;
    }
    final PsiDirectory psiResDir = PsiManager.getInstance(project).findDirectory(resourceDir);
    if (psiResDir == null) {
        return;
    }
    final String resDirName = myResourceType.getName();
    PsiDirectory resSubdir = psiResDir.findSubdirectory(resDirName);
    if (resSubdir == null) {
        resSubdir = ApplicationManager.getApplication().runWriteAction(new Computable<PsiDirectory>() {

            @Override
            public PsiDirectory compute() {
                return psiResDir.createSubdirectory(resDirName);
            }
        });
    }
    try {
        AndroidResourceUtil.createFileResource(myResourceName, resSubdir, CreateTypedResourceFileAction.getDefaultRootTagByResourceType(myResourceType), resDirName, false);
        UndoUtil.markPsiFileForUndo(myFile);
    } catch (Exception e) {
        LOG.error(e);
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiDirectory(com.intellij.psi.PsiDirectory) Computable(com.intellij.openapi.util.Computable) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 27 with Computable

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

the class FlashUmlTest method doTestImpl.

private DiagramBuilder doTestImpl(@Nullable File projectRoot, String[] files, String[] additionalClasses, Computable<GlobalSearchScope> scopeProvider, @Nullable EnumSet<FlashUmlDependenciesSettingsOption> dependencies, @Nullable String expectedFileNamePrefix) throws Exception {
    List<VirtualFile> vFiles = new ArrayList<>(files.length);
    for (String file : files) {
        vFiles.add(getVirtualFile(BASE_PATH + file));
    }
    ApplicationManager.getApplication().runWriteAction(() -> {
        final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule);
        final ModifiableRootModel rootModel = rootManager.getModifiableModel();
        ContentEntry[] contentEntries = rootModel.getContentEntries();
        for (ContentEntry contentEntry : contentEntries) {
            rootModel.removeContentEntry(contentEntry);
        }
        rootModel.commit();
    });
    configureByFiles(projectRoot, VfsUtilCore.toVirtualFileArray(vFiles));
    final LinkedHashMap<Integer, String> markers = JSTestUtils.extractPositionMarkers(getProject(), getEditor().getDocument());
    assertFalse(markers.isEmpty());
    DiagramBuilder builder = null;
    int i = 1;
    for (Map.Entry<Integer, String> marker : markers.entrySet()) {
        getEditor().getCaretModel().moveToOffset(marker.getKey());
        i++;
        String expectedPrefix = StringUtil.isNotEmpty(marker.getValue()) ? marker.getValue() : expectedFileNamePrefix;
        final DataContext dataContext = DataManager.getInstance().getDataContext();
        final DiagramProvider[] providers = DiagramProvider.findProviders(dataContext, "unknown");
        final FlashUmlProvider provider = ContainerUtil.findInstance(providers, FlashUmlProvider.class);
        assertNotNull("Flash UML provider not found", provider);
        final String actualOriginFqn = provider.getVfsResolver().getQualifiedName(provider.getElementManager().findInDataContext(dataContext));
        final Object actualOrigin = provider.getVfsResolver().resolveElementByFQN(actualOriginFqn, getProject());
        builder = UmlGraphBuilderFactory.create(myProject, provider, actualOrigin, null);
        Disposer.register(getTestRootDisposable(), builder);
        final DiagramDataModel<Object> model = builder.getDataModel();
        DiagramConfiguration configuration = DiagramConfiguration.getConfiguration();
        String originalCategories = configuration.categories.get(provider.getID());
        if (dependencies != null) {
            model.setShowDependencies(true);
            EnumSet<FlashUmlDependenciesSettingsOption> disabledOptions = EnumSet.complementOf(dependencies);
            configuration.categories.put(provider.getID(), StringUtil.join(disabledOptions, option -> option.getDisplayName(), ";"));
        } else {
            model.setShowDependencies(false);
        }
        try {
            model.refreshDataModel();
            // first limit elements by scope
            Collection<DiagramNode<Object>> nodesToRemove = new ArrayList<>();
            for (DiagramNode<Object> node : model.getNodes()) {
                if (node.getIdentifyingElement() instanceof JSClass && !scopeProvider.compute().contains(((JSClass) node.getIdentifyingElement()).getContainingFile().getVirtualFile())) {
                    nodesToRemove.add(node);
                }
            }
            for (DiagramNode<Object> node : nodesToRemove) {
                model.removeNode(node);
            }
            builder.updateGraph();
            // then add explicitly required classes
            for (String aClass : additionalClasses) {
                JSClass c = JSTestUtils.findClassByQName(aClass, GlobalSearchScope.allScope(myProject));
                final DiagramNode node = model.addElement(c);
                if (node != null) {
                    builder.createDraggedNode(node, node.getTooltip(), DiagramUtils.getBestPositionForNode(builder));
                    builder.updateGraph();
                }
            }
            assertModel(expectedPrefix, provider, actualOriginFqn, model);
        } finally {
            configuration.categories.put(provider.getID(), originalCategories);
        }
    }
    assert builder != null;
    return builder;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) VfsRootAccess(com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ContentEntry(com.intellij.openapi.roots.ContentEntry) FlexStylesIndexableSetContributor(com.intellij.javascript.flex.css.FlexStylesIndexableSetContributor) ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) Disposer(com.intellij.openapi.util.Disposer) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) LoadTextUtil(com.intellij.openapi.fileEditor.impl.LoadTextUtil) DiagramBuilder(com.intellij.diagram.DiagramBuilder) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) ModifiableFlexBuildConfiguration(com.intellij.lang.javascript.flex.projectStructure.model.ModifiableFlexBuildConfiguration) JDOMCompare(com.intellij.util.JDOMCompare) Nullable(org.jetbrains.annotations.Nullable) JSClass(com.intellij.lang.javascript.psi.ecmal4.JSClass) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) VfsUtilCore.convertFromUrl(com.intellij.openapi.vfs.VfsUtilCore.convertFromUrl) UmlDataModelDumper(com.intellij.diagram.util.UmlDataModelDumper) JdomKt(com.intellij.util.JdomKt) JSTestOptions(com.intellij.lang.javascript.JSTestOptions) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) ApplicationManager(com.intellij.openapi.application.ApplicationManager) DiagramProvider(com.intellij.diagram.DiagramProvider) VfsUtilCore.urlToPath(com.intellij.openapi.vfs.VfsUtilCore.urlToPath) java.util(java.util) CodeInsightTestCase(com.intellij.codeInsight.CodeInsightTestCase) ArrayUtil(com.intellij.util.ArrayUtil) DataContext(com.intellij.openapi.actionSystem.DataContext) JSTestOption(com.intellij.lang.javascript.JSTestOption) FlexModuleType(com.intellij.lang.javascript.flex.FlexModuleType) DiagramConfiguration(com.intellij.diagram.settings.DiagramConfiguration) FlashUmlDataModel(com.intellij.lang.javascript.uml.FlashUmlDataModel) Computable(com.intellij.openapi.util.Computable) ContainerUtil(com.intellij.util.containers.ContainerUtil) JDOMResult(org.jdom.transform.JDOMResult) UmlGraphBuilderFactory(com.intellij.uml.UmlGraphBuilderFactory) JDOMUtil(com.intellij.openapi.util.JDOMUtil) ModuleType(com.intellij.openapi.module.ModuleType) FlexTestUtils(com.intellij.flex.util.FlexTestUtils) DataManager(com.intellij.ide.DataManager) VfsUtilCore(com.intellij.openapi.vfs.VfsUtilCore) StringUtil(com.intellij.openapi.util.text.StringUtil) FlexSchemaHandler(com.intellij.javascript.flex.mxml.schema.FlexSchemaHandler) DiagramUtils(com.intellij.diagram.util.DiagramUtils) FlashUmlDependenciesSettingsOption(com.intellij.lang.javascript.uml.FlashUmlDependenciesSettingsOption) Sdk(com.intellij.openapi.projectRoots.Sdk) File(java.io.File) JSTestUtils(com.intellij.lang.javascript.JSTestUtils) SkipInHeadlessEnvironment(com.intellij.testFramework.SkipInHeadlessEnvironment) FlashUmlProvider(com.intellij.lang.javascript.uml.FlashUmlProvider) DiagramNode(com.intellij.diagram.DiagramNode) TargetElementUtil(com.intellij.codeInsight.TargetElementUtil) DiagramDataModel(com.intellij.diagram.DiagramDataModel) Element(org.jdom.Element) DiagramNode(com.intellij.diagram.DiagramNode) ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) DiagramBuilder(com.intellij.diagram.DiagramBuilder) DataContext(com.intellij.openapi.actionSystem.DataContext) DiagramConfiguration(com.intellij.diagram.settings.DiagramConfiguration) FlashUmlProvider(com.intellij.lang.javascript.uml.FlashUmlProvider) FlashUmlDependenciesSettingsOption(com.intellij.lang.javascript.uml.FlashUmlDependenciesSettingsOption) DiagramProvider(com.intellij.diagram.DiagramProvider) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) ContentEntry(com.intellij.openapi.roots.ContentEntry) JSClass(com.intellij.lang.javascript.psi.ecmal4.JSClass)

Example 28 with Computable

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

the class StaticInheritanceFix method doFix.

@Override
public void doFix(final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
    final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) descriptor.getPsiElement();
    final PsiClass iface = (PsiClass) referenceElement.resolve();
    assert iface != null;
    final PsiField[] allFields = iface.getAllFields();
    final PsiClass implementingClass = ClassUtils.getContainingClass(referenceElement);
    final PsiManager manager = referenceElement.getManager();
    assert implementingClass != null;
    final PsiFile file = implementingClass.getContainingFile();
    ProgressManager.getInstance().run(new Task.Modal(project, "Replacing usages of " + iface.getName(), false) {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            for (final PsiField field : allFields) {
                SearchScope scope = ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {

                    @Override
                    public SearchScope compute() {
                        return implementingClass.getUseScope();
                    }
                });
                final Query<PsiReference> search = ReferencesSearch.search(field, scope, false);
                for (PsiReference reference : search) {
                    if (!(reference instanceof PsiReferenceExpression)) {
                        continue;
                    }
                    final PsiReferenceExpression referenceExpression = (PsiReferenceExpression) reference;
                    if (!myReplaceInWholeProject) {
                        boolean isInheritor = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {

                            @Override
                            public Boolean compute() {
                                boolean isInheritor = false;
                                PsiClass aClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
                                while (aClass != null) {
                                    isInheritor = InheritanceUtil.isInheritorOrSelf(aClass, implementingClass, true);
                                    if (isInheritor)
                                        break;
                                    aClass = PsiTreeUtil.getParentOfType(aClass, PsiClass.class);
                                }
                                return isInheritor;
                            }
                        });
                        if (!isInheritor)
                            continue;
                    }
                    final Runnable runnable = () -> {
                        if (!FileModificationService.getInstance().preparePsiElementsForWrite(referenceExpression)) {
                            return;
                        }
                        final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
                        final PsiReferenceExpression qualified = (PsiReferenceExpression) elementFactory.createExpressionFromText("xxx." + referenceExpression.getText(), referenceExpression);
                        final PsiReferenceExpression newReference = (PsiReferenceExpression) referenceExpression.replace(qualified);
                        final PsiReferenceExpression qualifier = (PsiReferenceExpression) newReference.getQualifierExpression();
                        assert qualifier != null : DebugUtil.psiToString(newReference, false);
                        final PsiClass containingClass = field.getContainingClass();
                        qualifier.bindToElement(containingClass);
                    };
                    invokeWriteAction(runnable, file);
                }
            }
            final Runnable runnable = () -> {
                PsiClassType classType = JavaPsiFacade.getInstance(project).getElementFactory().createType(iface);
                IntentionAction fix = QuickFixFactory.getInstance().createExtendsListFix(implementingClass, classType, false);
                fix.invoke(project, null, file);
            };
            invokeWriteAction(runnable, file);
        }
    });
}
Also used : Task(com.intellij.openapi.progress.Task) Query(com.intellij.util.Query) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) SearchScope(com.intellij.psi.search.SearchScope) Computable(com.intellij.openapi.util.Computable)

Example 29 with Computable

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

the class SliceUsage method processChildren.

public void processChildren(@NotNull Processor<SliceUsage> processor) {
    final PsiElement element = ApplicationManager.getApplication().runReadAction((Computable<PsiElement>) this::getElement);
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    indicator.checkCanceled();
    final Processor<SliceUsage> uniqueProcessor = new CommonProcessors.UniqueProcessor<>(processor, new TObjectHashingStrategy<SliceUsage>() {

        @Override
        public int computeHashCode(final SliceUsage object) {
            return object.getUsageInfo().hashCode();
        }

        @Override
        public boolean equals(final SliceUsage o1, final SliceUsage o2) {
            return o1.getUsageInfo().equals(o2.getUsageInfo());
        }
    });
    ApplicationManager.getApplication().runReadAction(() -> {
        if (params.dataFlowToThis) {
            processUsagesFlownDownTo(element, uniqueProcessor);
        } else {
            processUsagesFlownFromThe(element, uniqueProcessor);
        }
    });
}
Also used : ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) PsiElement(com.intellij.psi.PsiElement) Computable(com.intellij.openapi.util.Computable)

Example 30 with Computable

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

the class ConfigurableCardPanel method createConfigurableComponent.

/**
   * Creates UI component for the specified configurable.
   * If a component is created successfully the configurable will be reset.
   * If the configurable implements {@link MasterDetails},
   * created component will not have the following modifications.
   * If the configurable does not implement {@link Configurable.NoMargin},
   * this method sets an empty border with default margins for created component.
   * If the configurable does not implement {@link Configurable.NoScroll},
   * this method adds a scroll bars for created component.
   */
public static JComponent createConfigurableComponent(Configurable configurable) {
    return configurable == null ? null : ApplicationManager.getApplication().runReadAction(new Computable<JComponent>() {

        @Override
        public JComponent compute() {
            JComponent component = null;
            long time = System.currentTimeMillis();
            try {
                component = configurable.createComponent();
            } catch (Exception unexpected) {
                LOG.error("cannot create configurable component", unexpected);
            } finally {
                warn(configurable, "create", time);
            }
            if (component != null) {
                reset(configurable);
                if (ConfigurableWrapper.cast(MasterDetails.class, configurable) == null) {
                    if (ConfigurableWrapper.cast(Configurable.NoMargin.class, configurable) == null) {
                        if (!component.getClass().equals(JPanel.class)) {
                            // some custom components do not support borders
                            JPanel panel = new JPanel(new BorderLayout());
                            panel.add(BorderLayout.CENTER, component);
                            component = panel;
                        }
                        component.setBorder(JBUI.Borders.empty(5, 10, 10, 10));
                    }
                    if (ConfigurableWrapper.cast(Configurable.NoScroll.class, configurable) == null) {
                        JScrollPane scroll = ScrollPaneFactory.createScrollPane(null, true);
                        scroll.setViewport(new GradientViewport(component, JBUI.insetsTop(5), true));
                        component = scroll;
                    }
                }
            }
            return component;
        }
    });
}
Also used : MasterDetails(com.intellij.openapi.options.MasterDetails) BorderLayout(java.awt.BorderLayout) Computable(com.intellij.openapi.util.Computable) GradientViewport(com.intellij.ui.components.GradientViewport)

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