Search in sources :

Example 96 with WriteCommandAction

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

the class PsiConcurrencyStressTest method testStress.

public void testStress() throws Exception {
    DaemonProgressIndicator.setDebug(false);
    int numOfThreads = Runtime.getRuntime().availableProcessors();
    int iterations = Timings.adjustAccordingToMySpeed(20, true);
    System.out.println("iterations = " + iterations);
    final int readIterations = iterations * 3;
    synchronized (this) {
        PsiClass myClass = myJavaFacade.findClass("StressClass", GlobalSearchScope.allScope(myProject));
        assertNotNull(myClass);
        myFile = (PsiJavaFile) myClass.getContainingFile();
    }
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    final CountDownLatch reads = new CountDownLatch(numOfThreads);
    final Random random = new Random();
    List<Thread> threads = ContainerUtil.map(Collections.nCopies(numOfThreads, ""), i -> new Thread(() -> {
        for (int i1 = 0; i1 < readIterations; i1++) {
            if (myPsiManager == null)
                return;
            ProgressManager.getInstance().runProcess(() -> ApplicationManager.getApplication().runReadAction(() -> {
                assertFalse(writeActionInProgress);
                readStep(random);
            }), new DaemonProgressIndicator());
        }
        reads.countDown();
    }, "stress thread" + i));
    threads.forEach(Thread::start);
    final Document document = documentManager.getDocument(myFile);
    for (int i = 0; i < iterations; i++) {
        Thread.sleep(100);
        new WriteCommandAction(myProject, myFile) {

            @Override
            protected void run(@NotNull final Result result) throws Throwable {
                writeActionInProgress = true;
                documentManager.commitAllDocuments();
                writeStep(random);
                documentManager.commitAllDocuments();
                assertEquals(document.getText(), myFile.getText());
                writeActionInProgress = false;
            }
        }.execute();
    }
    assertTrue("Timed out", reads.await(5, TimeUnit.MINUTES));
    ConcurrencyUtil.joinAll(threads);
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) DaemonProgressIndicator(com.intellij.codeInsight.daemon.impl.DaemonProgressIndicator) CountDownLatch(java.util.concurrent.CountDownLatch) Document(com.intellij.openapi.editor.Document) Result(com.intellij.openapi.application.Result) Random(java.util.Random)

Example 97 with WriteCommandAction

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

the class ImplementMethodsFix method invoke.

@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") final Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
    final PsiElement myPsiElement = startElement;
    if (editor == null || !FileModificationService.getInstance().prepareFileForWrite(myPsiElement.getContainingFile()))
        return;
    if (myPsiElement instanceof PsiEnumConstant) {
        final boolean hasClassInitializer = ((PsiEnumConstant) myPsiElement).getInitializingClass() != null;
        final MemberChooser<PsiMethodMember> chooser = chooseMethodsToImplement(editor, startElement, ((PsiEnumConstant) myPsiElement).getContainingClass(), hasClassInitializer);
        if (chooser == null)
            return;
        final List<PsiMethodMember> selectedElements = chooser.getSelectedElements();
        if (selectedElements == null || selectedElements.isEmpty())
            return;
        new WriteCommandAction(project, file) {

            @Override
            protected void run(@NotNull final Result result) throws Throwable {
                final PsiClass psiClass = ((PsiEnumConstant) myPsiElement).getOrCreateInitializingClass();
                OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(editor, psiClass, selectedElements, chooser.isCopyJavadoc(), chooser.isInsertOverrideAnnotation());
            }
        }.execute();
    } else {
        OverrideImplementUtil.chooseAndImplementMethods(project, editor, (PsiClass) myPsiElement);
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) PsiEnumConstant(com.intellij.psi.PsiEnumConstant) PsiMethodMember(com.intellij.codeInsight.generation.PsiMethodMember) PsiClass(com.intellij.psi.PsiClass) LocalQuickFixAndIntentionActionOnPsiElement(com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement) PsiElement(com.intellij.psi.PsiElement) Result(com.intellij.openapi.application.Result)

Example 98 with WriteCommandAction

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

the class CreateClassFromNewFix method setupClassFromNewExpression.

protected void setupClassFromNewExpression(final PsiClass psiClass, final PsiNewExpression newExpression) {
    assert ApplicationManager.getApplication().isWriteAccessAllowed();
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(newExpression.getProject()).getElementFactory();
    PsiClass aClass = psiClass;
    if (aClass == null)
        return;
    final PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
    if (classReference != null) {
        classReference.bindToElement(aClass);
    }
    setupInheritance(newExpression, aClass);
    PsiExpressionList argList = newExpression.getArgumentList();
    final Project project = aClass.getProject();
    if (argList != null && argList.getExpressions().length > 0) {
        PsiMethod constructor = elementFactory.createConstructor();
        constructor = (PsiMethod) aClass.add(constructor);
        TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(aClass);
        CreateFromUsageUtils.setupMethodParameters(constructor, templateBuilder, argList, getTargetSubstitutor(newExpression));
        setupSuperCall(aClass, constructor, templateBuilder);
        getReferenceElement(newExpression).bindToElement(aClass);
        aClass = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(aClass);
        final Template template = templateBuilder.buildTemplate();
        template.setToReformat(true);
        final Editor editor = positionCursor(project, aClass.getContainingFile(), aClass);
        if (editor == null)
            return;
        final RangeMarker textRange = editor.getDocument().createRangeMarker(aClass.getTextRange());
        final Runnable runnable = () -> {
            new WriteCommandAction(project, getText(), getText()) {

                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    try {
                        editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
                    } finally {
                        textRange.dispose();
                    }
                }
            }.execute();
            startTemplate(editor, template, project, null, getText());
        };
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            runnable.run();
        } else {
            ApplicationManager.getApplication().invokeLater(runnable);
        }
    } else {
        positionCursor(project, aClass.getContainingFile(), ObjectUtils.notNull(aClass.getNameIdentifier(), aClass));
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) RangeMarker(com.intellij.openapi.editor.RangeMarker) NotNull(org.jetbrains.annotations.NotNull) Template(com.intellij.codeInsight.template.Template) Result(com.intellij.openapi.application.Result) Project(com.intellij.openapi.project.Project) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) Editor(com.intellij.openapi.editor.Editor)

Example 99 with WriteCommandAction

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

the class GenerifyFileFix method applyFix.

@Override
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    if (element == null)
        return;
    final PsiFile file = element.getContainingFile();
    if (isAvailable(project, null, file)) {
        myFileName = file.getName();
        new WriteCommandAction(project) {

            @Override
            protected void run(@NotNull Result result) throws Throwable {
                invoke(project, FileEditorManager.getInstance(project).getSelectedTextEditor(), file);
            }
        }.execute();
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) Result(com.intellij.openapi.application.Result)

Example 100 with WriteCommandAction

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

the class BaseExpressionToFieldHandler method convertExpressionToField.

private boolean convertExpressionToField(PsiExpression selectedExpr, @Nullable Editor editor, PsiFile file, final Project project, PsiType tempType) {
    if (myParentClass == null) {
        if (FileTypeUtils.isInServerPageFile(file)) {
            CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.message("error.not.supported.for.jsp", getRefactoringName()), getRefactoringName(), getHelpID());
            return true;
        } else if ("package-info.java".equals(file.getName())) {
            CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.message("error.not.supported.for.package.info", getRefactoringName()), getRefactoringName(), getHelpID());
            return true;
        } else {
            LOG.error(file);
            return true;
        }
    }
    if (!validClass(myParentClass, editor)) {
        return true;
    }
    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file))
        return true;
    final OccurrenceManager occurrenceManager = createOccurrenceManager(selectedExpr, myParentClass);
    final PsiExpression[] occurrences = occurrenceManager.getOccurrences();
    final PsiElement anchorStatementIfAll = occurrenceManager.getAnchorStatementForAll();
    List<RangeHighlighter> highlighters = null;
    if (editor != null) {
        highlighters = RefactoringUtil.highlightAllOccurrences(project, occurrences, editor);
    }
    PsiElement tempAnchorElement = RefactoringUtil.getParentExpressionAnchorElement(selectedExpr);
    if (!Comparing.strEqual(IntroduceConstantHandler.REFACTORING_NAME, getRefactoringName()) && IntroduceVariableBase.checkAnchorBeforeThisOrSuper(project, editor, tempAnchorElement, getRefactoringName(), getHelpID()))
        return true;
    final Settings settings = showRefactoringDialog(project, editor, myParentClass, selectedExpr, tempType, occurrences, tempAnchorElement, anchorStatementIfAll);
    if (settings == null)
        return true;
    if (settings.getForcedType() != null) {
        tempType = settings.getForcedType();
    }
    final PsiType type = tempType;
    if (editor != null) {
        HighlightManager highlightManager = HighlightManager.getInstance(project);
        for (RangeHighlighter highlighter : highlighters) {
            highlightManager.removeSegmentHighlighter(editor, highlighter);
        }
    }
    final Runnable runnable = new ConvertToFieldRunnable(settings.getSelectedExpr(), settings, type, settings.getOccurrences(), occurrenceManager, anchorStatementIfAll, tempAnchorElement, editor, myParentClass);
    new WriteCommandAction(project, getRefactoringName()) {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            runnable.run();
        }
    }.execute();
    return false;
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) OccurrenceManager(com.intellij.refactoring.util.occurrences.OccurrenceManager) HighlightManager(com.intellij.codeInsight.highlighting.HighlightManager) Result(com.intellij.openapi.application.Result) RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter)

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