コード例 #1
0
  protected static IntentionAction findIntentionAction(
      @NotNull Collection<HighlightInfo> infos,
      @NotNull String intentionActionName,
      @NotNull Editor editor,
      @NotNull PsiFile file) {
    List<IntentionAction> actions = LightQuickFixTestCase.getAvailableActions(editor, file);
    IntentionAction intentionAction =
        LightQuickFixTestCase.findActionWithText(actions, intentionActionName);

    if (intentionAction == null) {
      final List<IntentionAction> availableActions = new ArrayList<IntentionAction>();

      for (HighlightInfo info : infos) {
        if (info.quickFixActionRanges != null) {
          for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair :
              info.quickFixActionRanges) {
            IntentionAction action = pair.first.getAction();
            if (action.isAvailable(file.getProject(), editor, file)) availableActions.add(action);
          }
        }
      }

      intentionAction =
          LightQuickFixTestCase.findActionWithText(availableActions, intentionActionName);
    }
    return intentionAction;
  }
コード例 #2
0
  private void doTestFor(
      Map<String, PsiFile> pathToFile, final IntentionAction intentionAction, String fileText)
      throws Exception {
    String isApplicableString =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// IS_APPLICABLE: ");
    boolean isApplicableExpected = isApplicableString == null || isApplicableString.equals("true");

    Assert.assertTrue(
        "isAvailable() for "
            + intentionAction.getClass()
            + " should return "
            + isApplicableExpected,
        isApplicableExpected == intentionAction.isAvailable(getProject(), getEditor(), getFile()));

    String intentionTextString =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// INTENTION_TEXT: ");

    if (intentionTextString != null) {
      assertEquals("Intention text mismatch.", intentionTextString, intentionAction.getText());
    }

    String shouldFailString =
        InTextDirectivesUtils.findStringWithPrefixes(fileText, "// SHOULD_FAIL_WITH: ");

    try {
      if (isApplicableExpected) {
        ApplicationPackage.executeWriteCommand(
            getProject(),
            intentionAction.getText(),
            new Function0<Object>() {
              @Override
              public Object invoke() {
                intentionAction.invoke(getProject(), getEditor(), getFile());
                return null;
              }
            });
        // Don't bother checking if it should have failed.
        if (shouldFailString == null) {
          for (Map.Entry<String, PsiFile> entry : pathToFile.entrySet()) {
            //noinspection AssignmentToStaticFieldFromInstanceMethod
            myFile = entry.getValue();
            String canonicalPathToExpectedFile =
                PathUtil.getCanonicalPath(entry.getKey() + ".after");

            checkResultByFile(canonicalPathToExpectedFile);
          }
        }
      }
      assertNull("Expected test to fail.", shouldFailString);
    } catch (IntentionTestException e) {
      assertEquals("Failure message mismatch.", shouldFailString, e.getMessage());
    } catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
      assertEquals(
          "Failure message mismatch.", shouldFailString, StringUtil.join(e.getMessages(), ", "));
    }
  }
コード例 #3
0
  @Nullable
  private IntentionAction doTestHighlightingAndGetQuickfix(
      @NotNull String message, @NotNull String filePath) throws IOException {
    doTestHighlighting(filePath);

    IntentionAction action = null;

    for (IntentionAction a : myFixture.getAvailableIntentions()) {
      if (message.equals(a.getText())) {
        action = a;
      }
    }
    return action;
  }
コード例 #4
0
  private void doTestWithFix(@NotNull String message, @NotNull String filePath) throws IOException {
    final IntentionAction action = doTestHighlightingAndGetQuickfix(message, filePath);
    assertNotNull(action);
    assertTrue(
        action.isAvailable(myFixture.getProject(), myFixture.getEditor(), myFixture.getFile()));

    new WriteCommandAction(myFixture.getProject(), "") {
      @Override
      protected void run(Result result) throws Throwable {
        action.invoke(myFixture.getProject(), myFixture.getEditor(), myFixture.getFile());
      }
    }.execute();
    checkAfter();
  }
コード例 #5
0
 public void testComments() {
   final String testName = getTestName(false);
   myFixture.configureByFile(getRelativePath() + "/" + testName + ".java");
   final String message =
       InspectionGadgetsBundle.message("constant.conditional.expression.simplify.quickfix");
   final List<IntentionAction> actions = myFixture.filterAvailableIntentions(message);
   assertFalse("No actions available", actions.isEmpty());
   for (IntentionAction action : actions) {
     if (action.getText().equals(message)) {
       myFixture.launchAction(action);
       myFixture.checkResultByFile(getRelativePath() + "/" + testName + ".after.java");
       break;
     }
   }
 }
コード例 #6
0
  private boolean showAddImportHint(HighlightInfo info) {
    if (!DaemonCodeAnalyzerSettings.getInstance().isImportHintEnabled()) return false;
    if (!DaemonCodeAnalyzer.getInstance(myProject).isImportHintsEnabled(myFile)) return false;
    PsiElement element = myFile.findElementAt(info.startOffset);
    if (element == null || !element.isValid()) return false;

    final List<Pair<HighlightInfo.IntentionActionDescriptor, TextRange>> list =
        info.quickFixActionRanges;
    for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : list) {
      final IntentionAction action = pair.getFirst().getAction();
      if (action instanceof HintAction && action.isAvailable(myProject, myEditor, myFile)) {
        return ((HintAction) action).showHint(myEditor);
      }
    }
    return false;
  }
コード例 #7
0
  public void testAnnotateLibrary() throws Throwable {

    addDefaultLibrary();
    myFixture.configureByFiles("lib/p/TestPrimitive.java", "content/anno/p/annotations.xml");
    myFixture.configureByFiles("lib/p/Test.java");
    final PsiFile file = myFixture.getFile();
    final Editor editor = myFixture.getEditor();

    final IntentionAction fix = myFixture.findSingleIntention("Annotate method 'get' as @NotNull");
    assertTrue(fix.isAvailable(myProject, editor, file));

    // expecting other @Nullable annotations to be removed, and default @NotNull to be added
    List<Trinity<PsiModifierListOwner, String, Boolean>> expectedSequence =
        new ArrayList<Trinity<PsiModifierListOwner, String, Boolean>>();
    for (String notNull : NullableNotNullManager.getInstance(myProject).getNullables()) {
      expectedSequence.add(Trinity.create(getOwner(), notNull, false));
    }
    expectedSequence.add(Trinity.create(getOwner(), AnnotationUtil.NOT_NULL, true));
    startListening(expectedSequence);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        fix.invoke(myProject, editor, file);
      }
    }.execute();

    FileDocumentManager.getInstance().saveAllDocuments();

    final PsiElement psiElement = file.findElementAt(editor.getCaretModel().getOffset());
    assertNotNull(psiElement);
    final PsiModifierListOwner listOwner =
        PsiTreeUtil.getParentOfType(psiElement, PsiModifierListOwner.class);
    assertNotNull(listOwner);
    assertNotNull(
        ExternalAnnotationsManager.getInstance(myProject)
            .findExternalAnnotation(listOwner, AnnotationUtil.NOT_NULL));
    stopListeningAndCheckEvents();

    myFixture.checkResultByFile(
        "content/anno/p/annotations.xml",
        "content/anno/p/annotationsAnnotateLibrary_after.xml",
        false);
  }
コード例 #8
0
  public static boolean chooseActionAndInvoke(
      PsiFile hostFile, final Editor hostEditor, final IntentionAction action, final String text) {
    final Project project = hostFile.getProject();
    FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.quickFix");
    ((FeatureUsageTrackerImpl) FeatureUsageTracker.getInstance())
        .getFixesStats()
        .registerInvocation();

    Pair<PsiFile, Editor> pair =
        chooseBetweenHostAndInjected(
            hostFile,
            hostEditor,
            new PairProcessor<PsiFile, Editor>() {
              @Override
              public boolean process(PsiFile psiFile, Editor editor) {
                return availableFor(psiFile, editor, action);
              }
            });
    if (pair == null) return false;
    final Editor editorToApply = pair.second;
    final PsiFile fileToApply = pair.first;

    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            try {
              action.invoke(project, editorToApply, fileToApply);
            } catch (IncorrectOperationException e) {
              LOG.error(e);
            }
            DaemonCodeAnalyzer.getInstance(project).updateVisibleHighlighters(hostEditor);
          }
        };

    if (action.startInWriteAction()) {
      final Runnable _runnable = runnable;
      runnable =
          new Runnable() {
            @Override
            public void run() {
              ApplicationManager.getApplication().runWriteAction(_runnable);
            }
          };
    }

    CommandProcessor.getInstance().executeCommand(project, runnable, text, null);
    return true;
  }
コード例 #9
0
 private static boolean isAvailableHere(
     Editor editor,
     PsiFile psiFile,
     PsiElement psiElement,
     boolean inProject,
     IntentionAction action) {
   try {
     Project project = psiFile.getProject();
     if (action instanceof PsiElementBaseIntentionAction) {
       if (!inProject
           || psiElement == null
           || !((PsiElementBaseIntentionAction) action).isAvailable(project, editor, psiElement))
         return false;
     } else if (!action.isAvailable(project, editor, psiFile)) {
       return false;
     }
   } catch (IndexNotReadyException e) {
     return false;
   }
   return true;
 }
コード例 #10
0
 public SpellCheckerIntentionAction(IntentionAction intention) {
   super(intention.getText());
   this.intention = intention;
 }
コード例 #11
0
 @Override
 public boolean equals(Object obj) {
   return obj instanceof IntentionActionDescriptor
       && myAction.equals(((IntentionActionDescriptor) obj).myAction);
 }
コード例 #12
0
    @Nullable
    public List<IntentionAction> getOptions(@NotNull PsiElement element, @Nullable Editor editor) {
      if (editor != null
          && Boolean.FALSE.equals(
              editor.getUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY))) {
        return null;
      }
      List<IntentionAction> options = myOptions;
      HighlightDisplayKey key = myKey;
      if (options != null || key == null) {
        return options;
      }
      List<IntentionAction> newOptions =
          IntentionManager.getInstance().getStandardIntentionOptions(key, element);
      InspectionProfile profile =
          InspectionProjectProfileManager.getInstance(element.getProject()).getInspectionProfile();
      InspectionProfileEntry tool = profile.getInspectionTool(key.toString(), element);
      if (!(tool instanceof LocalInspectionToolWrapper)) {
        HighlightDisplayKey idkey = HighlightDisplayKey.findById(key.toString());
        if (idkey != null) {
          tool = profile.getInspectionTool(idkey.toString(), element);
        }
      }
      InspectionProfileEntry wrappedTool = tool;
      if (tool instanceof LocalInspectionToolWrapper) {
        wrappedTool = ((LocalInspectionToolWrapper) tool).getTool();
        Class aClass = myAction.getClass();
        if (myAction instanceof QuickFixWrapper) {
          aClass = ((QuickFixWrapper) myAction).getFix().getClass();
        }
        newOptions.add(new CleanupInspectionIntention((LocalInspectionToolWrapper) tool, aClass));
      } else if (tool instanceof GlobalInspectionToolWrapper) {
        wrappedTool = ((GlobalInspectionToolWrapper) tool).getTool();
        if (wrappedTool instanceof GlobalSimpleInspectionTool
            && (myAction instanceof LocalQuickFix || myAction instanceof QuickFixWrapper)) {
          Class aClass = myAction.getClass();
          if (myAction instanceof QuickFixWrapper) {
            aClass = ((QuickFixWrapper) myAction).getFix().getClass();
          }
          newOptions.add(
              new CleanupInspectionIntention((GlobalInspectionToolWrapper) tool, aClass));
        }
      }

      if (wrappedTool instanceof CustomSuppressableInspectionTool) {
        final IntentionAction[] suppressActions =
            ((CustomSuppressableInspectionTool) wrappedTool).getSuppressActions(element);
        if (suppressActions != null) {
          ContainerUtil.addAll(newOptions, suppressActions);
        }
      }
      if (wrappedTool instanceof BatchSuppressableTool) {
        final SuppressQuickFix[] suppressActions =
            ((BatchSuppressableTool) wrappedTool).getBatchSuppressActions(element);
        ContainerUtil.addAll(
            newOptions,
            ContainerUtil.map(
                suppressActions,
                new Function<SuppressQuickFix, IntentionAction>() {
                  @Override
                  public IntentionAction fun(SuppressQuickFix fix) {
                    return InspectionManagerEx.convertBatchToSuppressIntentionAction(fix);
                  }
                }));
      }

      synchronized (this) {
        options = myOptions;
        if (options == null) {
          myOptions = options = newOptions;
        }
        myKey = null;
      }
      return options;
    }
コード例 #13
0
 @Override
 public String toString() {
   return quickFix.toString();
 }