Search in sources :

Example 91 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class AndroidInferNullityAnnotationAction method checkModules.

// For Android we need to check SDK version and possibly update the gradle project file
protected boolean checkModules(@NotNull Project project, @NotNull AnalysisScope scope, @NotNull Map<Module, PsiFile> modules) {
    Set<Module> modulesWithoutAnnotations = new HashSet<>();
    Set<Module> modulesWithLowVersion = new HashSet<>();
    for (Module module : modules.keySet()) {
        AndroidModuleInfo info = AndroidModuleInfo.get(module);
        if (info != null && info.getBuildSdkVersion() != null && info.getBuildSdkVersion().getFeatureLevel() < MIN_SDK_WITH_NULLABLE) {
            modulesWithLowVersion.add(module);
        }
        GradleBuildModel buildModel = GradleBuildModel.get(module);
        if (buildModel == null) {
            LOG.warn("Unable to find Gradle build model for module " + module.getModuleFilePath());
            continue;
        }
        boolean dependencyFound = false;
        DependenciesModel dependenciesModel = buildModel.dependencies();
        if (dependenciesModel != null) {
            for (ArtifactDependencyModel dependency : dependenciesModel.artifacts(COMPILE)) {
                String notation = dependency.compactNotation().value();
                if (notation.startsWith(SdkConstants.APPCOMPAT_LIB_ARTIFACT) || notation.startsWith(SdkConstants.SUPPORT_LIB_ARTIFACT) || notation.startsWith(SdkConstants.ANNOTATIONS_LIB_ARTIFACT)) {
                    dependencyFound = true;
                    break;
                }
            }
        }
        if (!dependencyFound) {
            modulesWithoutAnnotations.add(module);
        }
    }
    if (!modulesWithLowVersion.isEmpty()) {
        Messages.showErrorDialog(project, String.format("Infer Nullity Annotations requires the project sdk level be set to %1$d or greater.", MIN_SDK_WITH_NULLABLE), "Infer Nullity Annotations");
        return false;
    }
    if (modulesWithoutAnnotations.isEmpty()) {
        return true;
    }
    String moduleNames = StringUtil.join(modulesWithoutAnnotations, Module::getName, ", ");
    int count = modulesWithoutAnnotations.size();
    String message = String.format("The %1$s %2$s %3$sn't refer to the existing '%4$s' library with Android nullity annotations. \n\n" + "Would you like to add the %5$s now?", pluralize("module", count), moduleNames, count > 1 ? "do" : "does", SupportLibrary.SUPPORT_ANNOTATIONS.getArtifactId(), pluralize("dependency", count));
    if (Messages.showOkCancelDialog(project, message, "Infer Nullity Annotations", Messages.getErrorIcon()) == Messages.OK) {
        LocalHistoryAction action = LocalHistory.getInstance().startAction(ADD_DEPENDENCY);
        try {
            new WriteCommandAction(project, ADD_DEPENDENCY) {

                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    RepositoryUrlManager manager = RepositoryUrlManager.get();
                    String annotationsLibraryCoordinate = manager.getLibraryStringCoordinate(SupportLibrary.SUPPORT_ANNOTATIONS, true);
                    for (Module module : modulesWithoutAnnotations) {
                        addDependency(module, annotationsLibraryCoordinate);
                    }
                    GradleSyncInvoker.Request request = new GradleSyncInvoker.Request().setGenerateSourcesOnSuccess(false);
                    GradleSyncInvoker.getInstance().requestProjectSync(project, request, new GradleSyncListener.Adapter() {

                        @Override
                        public void syncSucceeded(@NotNull Project project) {
                            restartAnalysis(project, scope);
                        }
                    });
                }
            }.execute();
        } finally {
            action.finish();
        }
    }
    return false;
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) RepositoryUrlManager(com.android.tools.idea.templates.RepositoryUrlManager) ArtifactDependencyModel(com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) AndroidModuleInfo(com.android.tools.idea.model.AndroidModuleInfo) Project(com.intellij.openapi.project.Project) GradleBuildModel(com.android.tools.idea.gradle.dsl.model.GradleBuildModel) LocalHistoryAction(com.intellij.history.LocalHistoryAction) DependenciesModel(com.android.tools.idea.gradle.dsl.model.dependencies.DependenciesModel) Module(com.intellij.openapi.module.Module)

Example 92 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class AndroidGradleJavaProjectModelModifier method addModuleDependency.

@Nullable
@Override
public Promise<Void> addModuleDependency(@NotNull Module from, @NotNull Module to, @NotNull DependencyScope scope) {
    Project project = from.getProject();
    VirtualFile openedFile = FileEditorManagerEx.getInstanceEx(from.getProject()).getCurrentFile();
    String gradlePath = getGradlePath(to);
    GradleBuildModel buildModel = GradleBuildModel.get(from);
    if (buildModel != null && gradlePath != null) {
        DependenciesModel dependencies = buildModel.dependencies();
        String configurationName = getConfigurationName(from, scope, openedFile);
        dependencies.addModule(configurationName, gradlePath, null);
        new WriteCommandAction(project, "Add Gradle Module Dependency") {

            @Override
            protected void run(@NotNull Result result) throws Throwable {
                buildModel.applyChanges();
                registerUndoAction(project);
            }
        }.execute();
        return requestProjectSync(project);
    }
    if ((buildModel == null) ^ (gradlePath == null)) {
        // If one of them is gradle module and one of them are not, reject since this is invalid dependency
        return Promises.rejectedPromise();
    }
    return null;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Project(com.intellij.openapi.project.Project) GradleBuildModel(com.android.tools.idea.gradle.dsl.model.GradleBuildModel) DependenciesModel(com.android.tools.idea.gradle.dsl.model.dependencies.DependenciesModel) Result(com.intellij.openapi.application.Result) Nullable(org.jetbrains.annotations.Nullable)

Example 93 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class AndroidGradleJavaProjectModelModifier method addExternalLibraryDependency.

@Nullable
private static Promise<Void> addExternalLibraryDependency(@NotNull Collection<Module> modules, @NotNull ArtifactDependencySpec dependencySpec, @NotNull DependencyScope scope) {
    Module firstModule = Iterables.getFirst(modules, null);
    if (firstModule == null) {
        return null;
    }
    Project project = firstModule.getProject();
    VirtualFile openedFile = FileEditorManagerEx.getInstanceEx(firstModule.getProject()).getCurrentFile();
    List<GradleBuildModel> buildModelsToUpdate = Lists.newArrayList();
    for (Module module : modules) {
        GradleBuildModel buildModel = GradleBuildModel.get(module);
        if (buildModel == null) {
            return null;
        }
        String configurationName = getConfigurationName(module, scope, openedFile);
        DependenciesModel dependencies = buildModel.dependencies();
        dependencies.addArtifact(configurationName, dependencySpec);
        buildModelsToUpdate.add(buildModel);
    }
    new WriteCommandAction(project, "Add Gradle Library Dependency") {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            for (GradleBuildModel buildModel : buildModelsToUpdate) {
                buildModel.applyChanges();
            }
            registerUndoAction(project);
        }
    }.execute();
    return requestProjectSync(project);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Project(com.intellij.openapi.project.Project) GradleBuildModel(com.android.tools.idea.gradle.dsl.model.GradleBuildModel) DependenciesModel(com.android.tools.idea.gradle.dsl.model.dependencies.DependenciesModel) Module(com.intellij.openapi.module.Module) Result(com.intellij.openapi.application.Result) Nullable(org.jetbrains.annotations.Nullable)

Example 94 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class AndroidGradleJavaProjectModelModifier method changeLanguageLevel.

@Nullable
@Override
public Promise<Void> changeLanguageLevel(@NotNull Module module, @NotNull LanguageLevel level) {
    Project project = module.getProject();
    if (!isBuildWithGradle(module)) {
        return null;
    }
    GradleBuildModel buildModel = GradleBuildModel.get(module);
    if (buildModel == null) {
        return null;
    }
    if (getAndroidModel(module) != null) {
        AndroidModel android = buildModel.android();
        if (android == null) {
            return null;
        }
        CompileOptionsModel compileOptions = android.compileOptions();
        compileOptions.setSourceCompatibility(level);
        compileOptions.setTargetCompatibility(level);
    } else {
        JavaFacet javaFacet = JavaFacet.getInstance(module);
        if (javaFacet == null || javaFacet.getJavaModuleModel() == null) {
            return null;
        }
        JavaModel javaModel = buildModel.java();
        javaModel.setSourceCompatibility(level);
        javaModel.setTargetCompatibility(level);
    }
    new WriteCommandAction(project, "Change Gradle Language Level") {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            buildModel.applyChanges();
            registerUndoAction(project);
        }
    }.execute();
    return requestProjectSync(project);
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) Project(com.intellij.openapi.project.Project) JavaFacet(com.android.tools.idea.gradle.project.facet.java.JavaFacet) GradleBuildModel(com.android.tools.idea.gradle.dsl.model.GradleBuildModel) Projects.getAndroidModel(com.android.tools.idea.gradle.util.Projects.getAndroidModel) AndroidModel(com.android.tools.idea.gradle.dsl.model.android.AndroidModel) JavaModel(com.android.tools.idea.gradle.dsl.model.java.JavaModel) CompileOptionsModel(com.android.tools.idea.gradle.dsl.model.android.CompileOptionsModel) Result(com.intellij.openapi.application.Result) Nullable(org.jetbrains.annotations.Nullable)

Example 95 with WriteCommandAction

use of com.intellij.openapi.command.WriteCommandAction in project android by JetBrains.

the class AndroidResourceUtil method changeValueResource.

/**
   * Sets a new value for a resource.
   * @param project the project containing the resource
   * @param resDir the res/ directory containing the resource
   * @param name the name of the resource to be modified
   * @param newValue the new resource value
   * @param fileName the resource values file name
   * @param dirNames list of values directories where the resource should be changed
   * @param useGlobalCommand if true, the undo will be registered globally. This allows the command to be undone from anywhere in the IDE
   *                         and not only the XML editor
   * @return true if the resource value was changed
   */
public static boolean changeValueResource(@NotNull final Project project, @NotNull VirtualFile resDir, @NotNull final String name, @NotNull final ResourceType resourceType, @NotNull final String newValue, @NotNull String fileName, @NotNull List<String> dirNames, final boolean useGlobalCommand) {
    if (dirNames.isEmpty()) {
        return false;
    }
    ArrayList<VirtualFile> resFiles = Lists.newArrayListWithExpectedSize(dirNames.size());
    for (String dirName : dirNames) {
        final VirtualFile resFile = findResourceFile(resDir, fileName, dirName);
        if (resFile != null) {
            resFiles.add(resFile);
        }
    }
    if (!ensureFilesWritable(project, resFiles)) {
        return false;
    }
    final Resources[] resourcesElements = new Resources[resFiles.size()];
    for (int i = 0; i < resFiles.size(); i++) {
        final Resources resources = AndroidUtils.loadDomElement(project, resFiles.get(i), Resources.class);
        if (resources == null) {
            AndroidUtils.reportError(project, AndroidBundle.message("not.resource.file.error", fileName));
            return false;
        }
        resourcesElements[i] = resources;
    }
    List<PsiFile> psiFiles = Lists.newArrayListWithExpectedSize(resFiles.size());
    PsiManager manager = PsiManager.getInstance(project);
    for (VirtualFile file : resFiles) {
        PsiFile psiFile = manager.findFile(file);
        if (psiFile != null) {
            psiFiles.add(psiFile);
        }
    }
    PsiFile[] files = psiFiles.toArray(new PsiFile[psiFiles.size()]);
    WriteCommandAction<Boolean> action = new WriteCommandAction<Boolean>(project, "Change " + resourceType.getName() + " Resource", files) {

        @Override
        protected void run(@NotNull Result<Boolean> result) throws Throwable {
            if (useGlobalCommand) {
                CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
            }
            result.setResult(false);
            for (Resources resources : resourcesElements) {
                for (ResourceElement element : getValueResourcesFromElement(resourceType, resources)) {
                    String value = element.getName().getStringValue();
                    if (name.equals(value)) {
                        element.setStringValue(newValue);
                        result.setResult(true);
                    }
                }
            }
        }
    };
    return action.execute().getResultObject();
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) ResourceElement(org.jetbrains.android.dom.resources.ResourceElement) NotNull(org.jetbrains.annotations.NotNull) Result(com.intellij.openapi.application.Result) Resources(org.jetbrains.android.dom.resources.Resources)

Aggregations

WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)176 Result (com.intellij.openapi.application.Result)175 NotNull (org.jetbrains.annotations.NotNull)62 Project (com.intellij.openapi.project.Project)45 VirtualFile (com.intellij.openapi.vfs.VirtualFile)29 XmlFile (com.intellij.psi.xml.XmlFile)28 XmlTag (com.intellij.psi.xml.XmlTag)23 Document (com.intellij.openapi.editor.Document)22 PsiFile (com.intellij.psi.PsiFile)16 Module (com.intellij.openapi.module.Module)14 Nullable (org.jetbrains.annotations.Nullable)12 NlModel (com.android.tools.idea.uibuilder.model.NlModel)11 AttributesTransaction (com.android.tools.idea.uibuilder.model.AttributesTransaction)10 Editor (com.intellij.openapi.editor.Editor)10 TextRange (com.intellij.openapi.util.TextRange)8 XmlAttribute (com.intellij.psi.xml.XmlAttribute)8 File (java.io.File)8 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8 GradleBuildModel (com.android.tools.idea.gradle.dsl.model.GradleBuildModel)7