Search in sources :

Example 21 with Computable

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

the class OverrideResourceAction method forkResourceFile.

private static void forkResourceFile(@NotNull Project project, @NotNull final ResourceFolderType folderType, @NotNull final VirtualFile file, @Nullable final XmlFile xmlFile, @Nullable String myNewFolder, @Nullable Configuration configuration, boolean open) {
    final FolderConfiguration folderConfig;
    if (myNewFolder == null) {
        // Open a file chooser to select the configuration to be created
        VirtualFile parentFolder = file.getParent();
        assert parentFolder != null;
        VirtualFile res = parentFolder.getParent();
        folderConfig = selectFolderConfig(project, res, folderType);
    } else {
        folderConfig = FolderConfiguration.getConfigForFolder(myNewFolder);
    }
    if (folderConfig == null) {
        return;
    }
    final Computable<Pair<String, VirtualFile>> computable = new Computable<Pair<String, VirtualFile>>() {

        @Override
        public Pair<String, VirtualFile> compute() {
            String folderName = folderConfig.getFolderName(folderType);
            try {
                VirtualFile parentFolder = file.getParent();
                assert parentFolder != null;
                VirtualFile res = parentFolder.getParent();
                VirtualFile newParentFolder = res.findChild(folderName);
                if (newParentFolder == null) {
                    newParentFolder = res.createChildDirectory(this, folderName);
                    if (newParentFolder == null) {
                        String message = String.format("Could not create folder %1$s in %2$s", folderName, res.getPath());
                        return Pair.of(message, null);
                    }
                }
                final VirtualFile existing = newParentFolder.findChild(file.getName());
                if (existing != null && existing.exists()) {
                    String message = String.format("File 'res/%1$s/%2$s' already exists!", folderName, file.getName());
                    return Pair.of(message, null);
                }
                // Attempt to get the document from the PSI file rather than the file on disk: get edited contents too
                String text;
                if (xmlFile != null) {
                    text = xmlFile.getText();
                } else {
                    text = StreamUtil.readText(file.getInputStream(), "UTF-8");
                }
                VirtualFile newFile = newParentFolder.createChildData(this, file.getName());
                VfsUtil.saveText(newFile, text);
                return Pair.of(null, newFile);
            } catch (IOException e2) {
                String message = String.format("Failed to create File 'res/%1$s/%2$s' : %3$s", folderName, file.getName(), e2.getMessage());
                return Pair.of(message, null);
            }
        }
    };
    WriteCommandAction<Pair<String, VirtualFile>> action = new WriteCommandAction<Pair<String, VirtualFile>>(project, "Add Resource") {

        @Override
        protected void run(@NotNull Result<Pair<String, VirtualFile>> result) throws Throwable {
            result.setResult(computable.compute());
        }
    };
    Pair<String, VirtualFile> result = action.execute().getResultObject();
    String error = result.getFirst();
    VirtualFile newFile = result.getSecond();
    if (error != null) {
        Messages.showErrorDialog(project, error, "Create Resource");
    } else {
        // First create a compatible configuration based on the current configuration
        if (configuration != null) {
            ConfigurationManager configurationManager = configuration.getConfigurationManager();
            configurationManager.createSimilar(newFile, file);
        }
        if (open) {
            OpenFileDescriptor descriptor = new OpenFileDescriptor(project, newFile, -1);
            FileEditorManager.getInstance(project).openEditor(descriptor, true);
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) FolderConfiguration(com.android.ide.common.resources.configuration.FolderConfiguration) IOException(java.io.IOException) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) OpenFileDescriptor(com.intellij.openapi.fileEditor.OpenFileDescriptor) ConfigurationManager(com.android.tools.idea.configurations.ConfigurationManager) Computable(com.intellij.openapi.util.Computable) Pair(com.android.utils.Pair)

Example 22 with Computable

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

the class AttributesTransaction method commit.

/**
   * Commits all the pending changes to the model. After this method has been called, no more writes or reads can be made from
   * this transaction.
   *
   * @return true if the XML was changed as result of this call
   */
public boolean commit() {
    ViewInfo viewInfo = myComponent.viewInfo;
    if (hasPendingRelayout && viewInfo != null) {
        View currentView = (View) viewInfo.getViewObject();
        if (currentView != myCachedView.get()) {
            // The view has changed since the last update so re-apply everything
            applyAllPendingAttributesToView(myComponent.viewInfo);
        }
        triggerViewRelayout((View) myComponent.viewInfo.getViewObject());
    }
    myLock.writeLock().lock();
    try {
        assert isValid;
        if (!myComponent.getTag().isValid()) {
            return finishTransaction();
        }
        if (!ApplicationManager.getApplication().isWriteAccessAllowed()) {
            return ApplicationManager.getApplication().runWriteAction((Computable<Boolean>) this::commit);
        }
        boolean modified = false;
        for (PendingAttribute attribute : myPendingAttributes.values()) {
            String originalValue = myOriginalValues.get(attributeKey(attribute.namespace, attribute.name));
            String currentValue = myComponent.getAttribute(attribute.namespace, attribute.name);
            if (!StringUtil.equals(currentValue, attribute.value)) {
                // The value has changed from what's in the XML
                if (!StringUtil.equals(originalValue, currentValue)) {
                    // The attribute value has changed since we started the transaction, deal with the conflict.
                    if (StringUtil.isEmpty(attribute.value)) {
                        // leave the attribute with the modified value.
                        continue;
                    } else if (StringUtil.equals(originalValue, attribute.value)) {
                        // The attribute has been modified without the change being send through this transaction. Leave the modified value.
                        continue;
                    }
                }
                modified = true;
                myComponent.setAttribute(attribute.namespace, attribute.name, attribute.value);
            }
        }
        isSuccessful = true;
        finishTransaction();
        return modified;
    } finally {
        myLock.writeLock().unlock();
    }
}
Also used : View(android.view.View) Computable(com.intellij.openapi.util.Computable) ViewInfo(com.android.ide.common.rendering.api.ViewInfo)

Example 23 with Computable

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

the class JavaLineMarkerProvider method collectSlowLineMarkers.

@Override
public void collectSlowLineMarkers(@NotNull final List<PsiElement> elements, @NotNull final Collection<LineMarkerInfo> result) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    List<Computable<List<LineMarkerInfo>>> tasks = new ArrayList<>();
    MultiMap<PsiClass, PsiMethod> byClass = MultiMap.create();
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < elements.size(); i++) {
        PsiElement element = elements.get(i);
        ProgressManager.checkCanceled();
        if (!(element instanceof PsiIdentifier))
            continue;
        PsiElement parent = element.getParent();
        if (parent instanceof PsiMethod) {
            final PsiMethod method = (PsiMethod) parent;
            PsiClass psiClass = method.getContainingClass();
            if (PsiUtil.canBeOverriden(method) && psiClass != null) {
                byClass.putValue(psiClass, method);
            }
        } else if (parent instanceof PsiClass && !(parent instanceof PsiTypeParameter)) {
            tasks.add(() -> collectInheritingClasses((PsiClass) parent));
        }
    }
    for (PsiClass psiClass : byClass.keySet()) {
        Collection<PsiMethod> methods = byClass.get(psiClass);
        tasks.add(() -> collectSiblingInheritedMethods(methods));
        tasks.add(() -> collectOverridingMethods(methods, psiClass));
    }
    Object lock = new Object();
    ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
    JobLauncher.getInstance().invokeConcurrentlyUnderProgress(tasks, indicator, true, computable -> {
        List<LineMarkerInfo> infos = computable.compute();
        synchronized (lock) {
            result.addAll(infos);
        }
        return true;
    });
}
Also used : MethodSignatureBackedByPsiMethod(com.intellij.psi.util.MethodSignatureBackedByPsiMethod) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) Computable(com.intellij.openapi.util.Computable)

Example 24 with Computable

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

the class StaticIconFieldsAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = LangDataKeys.PROJECT.getData(e.getDataContext());
    final UsageViewPresentation presentation = new UsageViewPresentation();
    presentation.setTabName("Statics");
    presentation.setTabText("Statitcs");
    final UsageView view = UsageViewManager.getInstance(project).showUsages(UsageTarget.EMPTY_ARRAY, Usage.EMPTY_ARRAY, presentation);
    ProgressManager.getInstance().run(new Task.Backgroundable(project, "Searching icons usages") {

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
            final GlobalSearchScope all = GlobalSearchScope.allScope(project);
            PsiClass allIcons = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {

                @Override
                public PsiClass compute() {
                    return facade.findClass("com.intellij.icons.AllIcons", all);
                }
            });
            searchFields(allIcons, view, indicator);
            PsiClass[] classes = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass[]>() {

                @Override
                public PsiClass[] compute() {
                    return facade.findPackage("icons").getClasses(all);
                }
            });
            for (PsiClass iconsClass : classes) {
                searchFields(iconsClass, view, indicator);
            }
        }
    });
}
Also used : Project(com.intellij.openapi.project.Project) Task(com.intellij.openapi.progress.Task) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) Computable(com.intellij.openapi.util.Computable)

Example 25 with Computable

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

the class CreateClassDialog method doOKAction.

@Override
protected void doOKAction() {
    RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, myPackageComponent.getText());
    final String packageName = getPackageName();
    final String[] errorString = new String[1];
    CommandProcessor.getInstance().executeCommand(myProject, () -> {
        try {
            final PackageWrapper targetPackage = new PackageWrapper(PsiManager.getInstance(myProject), packageName);
            final MoveDestination destination = myDestinationCB.selectDirectory(targetPackage, false);
            if (destination == null)
                return;
            myTargetDirectory = ApplicationManager.getApplication().runWriteAction(new Computable<PsiDirectory>() {

                @Override
                public PsiDirectory compute() {
                    PsiDirectory baseDir = getBaseDir(packageName);
                    if (baseDir == null && destination instanceof MultipleRootsMoveDestination) {
                        errorString[0] = "Destination not found for package '" + packageName + "'";
                        return null;
                    }
                    return destination.getTargetDirectory(baseDir);
                }
            });
            if (myTargetDirectory == null) {
                return;
            }
            errorString[0] = RefactoringMessageUtil.checkCanCreateClass(myTargetDirectory, getClassName());
        } catch (IncorrectOperationException e) {
            errorString[0] = e.getMessage();
        }
    }, CodeInsightBundle.message("create.directory.command"), null);
    if (errorString[0] != null) {
        if (errorString[0].length() > 0) {
            Messages.showMessageDialog(myProject, errorString[0], CommonBundle.getErrorTitle(), Messages.getErrorIcon());
        }
        return;
    }
    super.doOKAction();
}
Also used : PsiDirectory(com.intellij.psi.PsiDirectory) MultipleRootsMoveDestination(com.intellij.refactoring.move.moveClassesOrPackages.MultipleRootsMoveDestination) MoveDestination(com.intellij.refactoring.MoveDestination) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PackageWrapper(com.intellij.refactoring.PackageWrapper) Computable(com.intellij.openapi.util.Computable) MultipleRootsMoveDestination(com.intellij.refactoring.move.moveClassesOrPackages.MultipleRootsMoveDestination)

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