Search in sources :

Example 16 with LocalHistoryAction

use of com.intellij.history.LocalHistoryAction 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 17 with LocalHistoryAction

use of com.intellij.history.LocalHistoryAction in project intellij-community by JetBrains.

the class BaseRefactoringProcessor method doRefactoring.

private void doRefactoring(@NotNull final Collection<UsageInfo> usageInfoSet) {
    for (Iterator<UsageInfo> iterator = usageInfoSet.iterator(); iterator.hasNext(); ) {
        UsageInfo usageInfo = iterator.next();
        final PsiElement element = usageInfo.getElement();
        if (element == null || !isToBeChanged(usageInfo)) {
            iterator.remove();
        }
    }
    LocalHistoryAction action = LocalHistory.getInstance().startAction(getCommandName());
    final UsageInfo[] writableUsageInfos = usageInfoSet.toArray(new UsageInfo[usageInfoSet.size()]);
    try {
        PsiDocumentManager.getInstance(myProject).commitAllDocuments();
        RefactoringListenerManagerImpl listenerManager = (RefactoringListenerManagerImpl) RefactoringListenerManager.getInstance(myProject);
        myTransaction = listenerManager.startTransaction();
        final Map<RefactoringHelper, Object> preparedData = new LinkedHashMap<>();
        final Runnable prepareHelpersRunnable = new Runnable() {

            @Override
            public void run() {
                for (final RefactoringHelper helper : Extensions.getExtensions(RefactoringHelper.EP_NAME)) {
                    Object operation = ApplicationManager.getApplication().runReadAction(new Computable<Object>() {

                        @Override
                        public Object compute() {
                            return helper.prepareOperation(writableUsageInfos);
                        }
                    });
                    preparedData.put(helper, operation);
                }
            }
        };
        ProgressManager.getInstance().runProcessWithProgressSynchronously(prepareHelpersRunnable, "Prepare ...", false, myProject);
        Runnable performRefactoringRunnable = () -> {
            final String refactoringId = getRefactoringId();
            if (refactoringId != null) {
                RefactoringEventData data = getBeforeData();
                if (data != null) {
                    data.addUsages(usageInfoSet);
                }
                myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, data);
            }
            try {
                if (refactoringId != null) {
                    UndoableAction action1 = new UndoRefactoringAction(myProject, refactoringId);
                    UndoManager.getInstance(myProject).undoableActionPerformed(action1);
                }
                performRefactoring(writableUsageInfos);
            } finally {
                if (refactoringId != null) {
                    myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, getAfterData(writableUsageInfos));
                }
            }
        };
        ApplicationImpl app = (ApplicationImpl) ApplicationManagerEx.getApplicationEx();
        if (Registry.is("run.refactorings.under.progress")) {
            app.runWriteActionWithProgressInDispatchThread(getCommandName(), myProject, null, null, indicator -> performRefactoringRunnable.run());
        } else {
            app.runWriteAction(performRefactoringRunnable);
        }
        DumbService.getInstance(myProject).completeJustSubmittedTasks();
        for (Map.Entry<RefactoringHelper, Object> e : preparedData.entrySet()) {
            //noinspection unchecked
            e.getKey().performOperation(myProject, e.getValue());
        }
        myTransaction.commit();
        app.runWriteAction(() -> performPsiSpoilingRefactoring());
    } finally {
        action.finish();
    }
    int count = writableUsageInfos.length;
    if (count > 0) {
        StatusBarUtil.setStatusBarInfo(myProject, RefactoringBundle.message("statusBar.refactoring.result", count));
    } else {
        if (!isPreviewUsages(writableUsageInfos)) {
            StatusBarUtil.setStatusBarInfo(myProject, RefactoringBundle.message("statusBar.noUsages"));
        }
    }
}
Also used : ApplicationImpl(com.intellij.openapi.application.impl.ApplicationImpl) RefactoringListenerManagerImpl(com.intellij.refactoring.listeners.impl.RefactoringListenerManagerImpl) ThrowableRunnable(com.intellij.util.ThrowableRunnable) EmptyRunnable(com.intellij.openapi.util.EmptyRunnable) RefactoringEventData(com.intellij.refactoring.listeners.RefactoringEventData) LocalHistoryAction(com.intellij.history.LocalHistoryAction) BasicUndoableAction(com.intellij.openapi.command.undo.BasicUndoableAction) UndoableAction(com.intellij.openapi.command.undo.UndoableAction) MultiMap(com.intellij.util.containers.MultiMap) MoveRenameUsageInfo(com.intellij.refactoring.util.MoveRenameUsageInfo) UsageInfo(com.intellij.usageView.UsageInfo) PsiElement(com.intellij.psi.PsiElement)

Example 18 with LocalHistoryAction

use of com.intellij.history.LocalHistoryAction in project intellij-community by JetBrains.

the class UndoableGroup method undoOrRedo.

private void undoOrRedo(boolean isUndo) {
    LocalHistoryAction action;
    if (myProject != null && isGlobal()) {
        String actionName = CommonBundle.message(isUndo ? "local.vcs.action.name.undo.command" : "local.vcs.action.name.redo.command", myCommandName);
        action = LocalHistory.getInstance().startAction(actionName);
    } else {
        action = LocalHistoryAction.NULL;
    }
    try {
        doUndoOrRedo(isUndo);
    } finally {
        action.finish();
    }
}
Also used : LocalHistoryAction(com.intellij.history.LocalHistoryAction)

Example 19 with LocalHistoryAction

use of com.intellij.history.LocalHistoryAction in project intellij-community by JetBrains.

the class InlineMethodProcessor method performRefactoring.

protected void performRefactoring(@NotNull UsageInfo[] usages) {
    RangeMarker position = null;
    if (myEditor != null) {
        final int offset = myEditor.getCaretModel().getOffset();
        position = myEditor.getDocument().createRangeMarker(offset, offset + 1);
    }
    LocalHistoryAction a = LocalHistory.getInstance().startAction(getCommandName());
    try {
        doRefactoring(usages);
    } finally {
        a.finish();
    }
    if (position != null) {
        if (position.isValid()) {
            myEditor.getCaretModel().moveToOffset(position.getStartOffset());
        }
        position.dispose();
    }
}
Also used : LocalHistoryAction(com.intellij.history.LocalHistoryAction) RangeMarker(com.intellij.openapi.editor.RangeMarker)

Example 20 with LocalHistoryAction

use of com.intellij.history.LocalHistoryAction in project intellij-community by JetBrains.

the class MoveClassesOrPackagesImpl method doRearrangePackage.

public static void doRearrangePackage(final Project project, final PsiDirectory[] directories) {
    if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(directories), true)) {
        return;
    }
    List<PsiDirectory> sourceRootDirectories = buildRearrangeTargetsList(project, directories);
    DirectoryChooser chooser = new DirectoryChooser(project);
    chooser.setTitle(RefactoringBundle.message("select.source.root.chooser.title"));
    chooser.fillList(sourceRootDirectories.toArray(new PsiDirectory[sourceRootDirectories.size()]), null, project, "");
    if (!chooser.showAndGet()) {
        return;
    }
    final PsiDirectory selectedTarget = chooser.getSelectedDirectory();
    if (selectedTarget == null)
        return;
    final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    final Runnable analyzeConflicts = () -> ApplicationManager.getApplication().runReadAction(() -> RefactoringConflictsUtil.analyzeModuleConflicts(project, Arrays.asList(directories), UsageInfo.EMPTY_ARRAY, selectedTarget, conflicts));
    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(analyzeConflicts, "Analyze Module Conflicts...", true, project)) {
        return;
    }
    if (!conflicts.isEmpty()) {
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            throw new BaseRefactoringProcessor.ConflictsInTestsException(conflicts.values());
        } else {
            final ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts);
            if (!conflictsDialog.showAndGet()) {
                return;
            }
        }
    }
    final Ref<IncorrectOperationException> ex = Ref.create(null);
    final String commandDescription = RefactoringBundle.message("moving.directories.command");
    Runnable runnable = () -> ApplicationManager.getApplication().runWriteAction(() -> {
        LocalHistoryAction a = LocalHistory.getInstance().startAction(commandDescription);
        try {
            rearrangeDirectoriesToTarget(directories, selectedTarget);
        } catch (IncorrectOperationException e) {
            ex.set(e);
        } finally {
            a.finish();
        }
    });
    CommandProcessor.getInstance().executeCommand(project, runnable, commandDescription, null);
    if (ex.get() != null) {
        RefactoringUIUtil.processIncorrectOperation(project, ex.get());
    }
}
Also used : MultiMap(com.intellij.util.containers.MultiMap) ConflictsDialog(com.intellij.refactoring.ui.ConflictsDialog) LocalHistoryAction(com.intellij.history.LocalHistoryAction) IncorrectOperationException(com.intellij.util.IncorrectOperationException) DirectoryChooser(com.intellij.ide.util.DirectoryChooser)

Aggregations

LocalHistoryAction (com.intellij.history.LocalHistoryAction)24 VirtualFile (com.intellij.openapi.vfs.VirtualFile)8 Result (com.intellij.openapi.application.Result)7 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)7 NotNull (org.jetbrains.annotations.NotNull)7 UsageInfo (com.intellij.usageView.UsageInfo)4 Revision (com.intellij.history.core.revisions.Revision)3 Project (com.intellij.openapi.project.Project)3 PsiElement (com.intellij.psi.PsiElement)3 IncorrectOperationException (com.intellij.util.IncorrectOperationException)3 SequentialModalProgressTask (com.intellij.util.SequentialModalProgressTask)3 GradleBuildModel (com.android.tools.idea.gradle.dsl.model.GradleBuildModel)2 ArtifactDependencyModel (com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencyModel)2 DependenciesModel (com.android.tools.idea.gradle.dsl.model.dependencies.DependenciesModel)2 AndroidModuleInfo (com.android.tools.idea.model.AndroidModuleInfo)2 RepositoryUrlManager (com.android.tools.idea.templates.RepositoryUrlManager)2 BuildFileModifier (com.google.idea.blaze.base.buildmodifier.BuildFileModifier)2 WorkspaceRoot (com.google.idea.blaze.base.model.primitives.WorkspaceRoot)2 LocalHistory (com.intellij.history.LocalHistory)2 Module (com.intellij.openapi.module.Module)2