Search in sources :

Example 46 with Computable

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

the class AndroidGotoRelatedProvider method collectRelatedJavaFiles.

@Nullable
private static Computable<List<GotoRelatedItem>> collectRelatedJavaFiles(@NotNull final XmlFile file, @NotNull final AndroidFacet facet) {
    final String resType = ResourceType.LAYOUT.getName();
    final String resourceName = AndroidCommonUtils.getResourceName(resType, file.getName());
    final PsiField[] fields = AndroidResourceUtil.findResourceFields(facet, resType, resourceName, true);
    if (fields.length == 0 || fields.length > 1) {
        return null;
    }
    final PsiField field = fields[0];
    final Module module = facet.getModule();
    final GlobalSearchScope scope = module.getModuleScope(false);
    return new Computable<List<GotoRelatedItem>>() {

        @Override
        public List<GotoRelatedItem> compute() {
            final JavaPsiFacade facade = JavaPsiFacade.getInstance(module.getProject());
            final List<PsiClass> psiContextClasses = new ArrayList<PsiClass>();
            // Explicitly chosen in the layout/menu file with a tools:context attribute?
            PsiClass declared = AndroidPsiUtils.getContextClass(module, file);
            if (declared != null) {
                return Collections.singletonList(new GotoRelatedItem(declared, "JAVA"));
            }
            for (String contextClassName : CONTEXT_CLASSES) {
                final PsiClass contextClass = facade.findClass(contextClassName, module.getModuleWithDependenciesAndLibrariesScope(false));
                if (contextClass != null) {
                    psiContextClasses.add(contextClass);
                }
            }
            if (psiContextClasses.isEmpty()) {
                return Collections.emptyList();
            }
            final List<GotoRelatedItem> result = new ArrayList<GotoRelatedItem>();
            ReferencesSearch.search(field, scope).forEach(new Processor<PsiReference>() {

                @Override
                public boolean process(PsiReference reference) {
                    PsiElement element = reference.getElement();
                    if (!(element instanceof PsiReferenceExpression)) {
                        return true;
                    }
                    element = element.getParent();
                    if (!(element instanceof PsiExpressionList)) {
                        return true;
                    }
                    element = element.getParent();
                    if (!(element instanceof PsiMethodCallExpression)) {
                        return true;
                    }
                    final String methodName = ((PsiMethodCallExpression) element).getMethodExpression().getReferenceName();
                    if ("setContentView".equals(methodName) || "inflate".equals(methodName)) {
                        final PsiClass relatedClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
                        if (relatedClass != null && isInheritorOfOne(relatedClass, psiContextClasses)) {
                            result.add(new GotoRelatedItem(relatedClass, "JAVA"));
                        }
                    }
                    return true;
                }
            });
            return result;
        }
    };
}
Also used : GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Module(com.intellij.openapi.module.Module) GotoRelatedItem(com.intellij.navigation.GotoRelatedItem) Computable(com.intellij.openapi.util.Computable) Nullable(org.jetbrains.annotations.Nullable)

Example 47 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 48 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 49 with Computable

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

the class ProgrammingLanguageUtils method getOrCreateMainFile.

@Nullable
private static PsiFile getOrCreateMainFile(@NotNull Project project, @NotNull VirtualFile parent, @NotNull SupportedLanguages language, @NotNull StepNode stepNode) {
    String fileName = language.getMainFileName();
    final VirtualFile[] file = { parent.findChild(fileName) };
    Application application = ApplicationManager.getApplication();
    if (file[0] == null) {
        application.invokeAndWait(() -> application.runWriteAction(() -> {
            try {
                file[0] = parent.createChildData(null, fileName);
                String template = null;
                StepikApiClient stepikApiClient = authAndGetStepikApiClient();
                User user = getCurrentUser();
                if (!user.isGuest()) {
                    try {
                        Submissions submissions = stepikApiClient.submissions().get().user(user.getId()).order(Order.DESC).step(stepNode.getId()).execute();
                        if (!submissions.isEmpty()) {
                            Optional<Submission> lastSubmission = submissions.getItems().stream().filter(submission -> SupportedLanguages.langOfName(submission.getReply().getLanguage()) == language).limit(1).findFirst();
                            if (lastSubmission.isPresent()) {
                                template = lastSubmission.get().getReply().getCode();
                            }
                        }
                    } catch (StepikClientException e) {
                        logger.warn(e);
                    }
                }
                if (template == null) {
                    template = stepNode.getTemplate(language);
                }
                file[0].setBinaryContent(template.getBytes());
            } catch (IOException e) {
                file[0] = null;
            }
        }));
    }
    return application.runReadAction((Computable<PsiFile>) () -> PsiManager.getInstance(project).findFile(file[0]));
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) StepikAuthManager.authAndGetStepikApiClient(org.stepik.core.stepik.StepikAuthManager.authAndGetStepikApiClient) Application(com.intellij.openapi.application.Application) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) ProjectFilesUtils.getOrCreateSrcPsiDirectory(org.stepik.core.utils.ProjectFilesUtils.getOrCreateSrcPsiDirectory) Computable(com.intellij.openapi.util.Computable) StepikClientException(org.stepik.api.exceptions.StepikClientException) User(org.stepik.api.objects.users.User) PsiManager(com.intellij.psi.PsiManager) ArrayList(java.util.ArrayList) ProjectView(com.intellij.ide.projectView.ProjectView) FileEditorManager(com.intellij.openapi.fileEditor.FileEditorManager) ProjectFilesUtils.getOrCreatePsiDirectory(org.stepik.core.utils.ProjectFilesUtils.getOrCreatePsiDirectory) Metrics(org.stepik.core.metrics.Metrics) StepikAuthManager.getCurrentUser(org.stepik.core.stepik.StepikAuthManager.getCurrentUser) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) Logger(com.intellij.openapi.diagnostic.Logger) SUCCESSFUL(org.stepik.core.metrics.MetricsStatus.SUCCESSFUL) Submission(org.stepik.api.objects.submissions.Submission) SupportedLanguages(org.stepik.core.SupportedLanguages) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) StepNode(org.stepik.core.courseFormat.StepNode) IOException(java.io.IOException) StudyUtils(org.stepik.core.StudyUtils) MoveFilesOrDirectoriesUtil(com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil) Nullable(org.jetbrains.annotations.Nullable) EduNames(org.stepik.core.core.EduNames) Submissions(org.stepik.api.objects.submissions.Submissions) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Optional(java.util.Optional) PsiDirectory(com.intellij.psi.PsiDirectory) StepikApiClient(org.stepik.api.client.StepikApiClient) NotNull(org.jetbrains.annotations.NotNull) Order(org.stepik.api.queries.Order) StepikAuthManager.authAndGetStepikApiClient(org.stepik.core.stepik.StepikAuthManager.authAndGetStepikApiClient) StepikApiClient(org.stepik.api.client.StepikApiClient) User(org.stepik.api.objects.users.User) StepikAuthManager.getCurrentUser(org.stepik.core.stepik.StepikAuthManager.getCurrentUser) Optional(java.util.Optional) PsiFile(com.intellij.psi.PsiFile) IOException(java.io.IOException) Application(com.intellij.openapi.application.Application) Submissions(org.stepik.api.objects.submissions.Submissions) StepikClientException(org.stepik.api.exceptions.StepikClientException) Nullable(org.jetbrains.annotations.Nullable)

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