Exemplo n.º 1
1
  @Override
  protected void updateTitle(@Nullable final PsiVariable variable, final String value) {
    final PsiElement declarationScope =
        variable != null ? ((PsiParameter) variable).getDeclarationScope() : null;
    if (declarationScope instanceof PsiMethod) {
      final PsiMethod psiMethod = (PsiMethod) declarationScope;
      final StringBuilder buf = new StringBuilder();
      buf.append(psiMethod.getName()).append(" (");
      boolean frst = true;
      final List<TextRange> ranges2Remove = new ArrayList<>();
      TextRange addedRange = null;
      for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) {
        if (frst) {
          frst = false;
        } else {
          buf.append(", ");
        }
        int startOffset = buf.length();
        if (myMustBeFinal || myPanel.isGenerateFinal()) {
          buf.append("final ");
        }
        buf.append(parameter.getType().getPresentableText())
            .append(" ")
            .append(variable == parameter ? value : parameter.getName());
        int endOffset = buf.length();
        if (variable == parameter) {
          addedRange = new TextRange(startOffset, endOffset);
        } else if (myPanel.isParamToRemove(parameter)) {
          ranges2Remove.add(new TextRange(startOffset, endOffset));
        }
      }

      buf.append(")");
      setPreviewText(buf.toString());
      final MarkupModel markupModel =
          DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true);
      markupModel.removeAllHighlighters();
      for (TextRange textRange : ranges2Remove) {
        markupModel.addRangeHighlighter(
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            0,
            getTestAttributesForRemoval(),
            HighlighterTargetArea.EXACT_RANGE);
      }
      markupModel.addRangeHighlighter(
          addedRange.getStartOffset(),
          addedRange.getEndOffset(),
          0,
          getTextAttributesForAdd(),
          HighlighterTargetArea.EXACT_RANGE);
      revalidate();
    }
  }
  protected String doCalculateSignature(PsiMethod method) {
    final StringBuilder buffer = new StringBuilder();
    final PsiModifierList modifierList = method.getModifierList();
    String modifiers = modifierList.getText();
    final String oldModifier = VisibilityUtil.getVisibilityModifier(modifierList);
    final String newModifier = getVisibility();
    String newModifierStr = VisibilityUtil.getVisibilityString(newModifier);
    if (!newModifier.equals(oldModifier)) {
      int index = modifiers.indexOf(oldModifier);
      if (index >= 0) {
        final StringBuilder buf = new StringBuilder(modifiers);
        buf.replace(
            index,
            index + oldModifier.length() + ("".equals(newModifierStr) ? 1 : 0),
            newModifierStr);
        modifiers = buf.toString();
      } else {
        if (!StringUtil.isEmpty(newModifierStr)) {
          newModifierStr += " ";
        }
        modifiers = newModifierStr + modifiers;
      }
    }

    buffer.append(modifiers);
    if (modifiers.length() > 0
        && !StringUtil.endsWithChar(modifiers, '\n')
        && !StringUtil.endsWithChar(modifiers, '\r')
        && !StringUtil.endsWithChar(modifiers, ' ')) {
      buffer.append(" ");
    }

    if (!method.isConstructor()) {
      final CanonicalTypes.Type type = getReturnType();
      if (type != null) {
        buffer.append(type.getTypeText());
      }
      buffer.append(" ");
    }
    buffer.append(getMethodName());
    buffer.append("(");

    final int lineBreakIdx = buffer.lastIndexOf("\n");
    String indent =
        StringUtil.repeatSymbol(
            ' ', lineBreakIdx >= 0 ? buffer.length() - lineBreakIdx - 1 : buffer.length());
    List<ParameterTableModelItemBase<ParameterInfoImpl>> items = myParametersTableModel.getItems();
    int curIndent = indent.length();
    for (int i = 0; i < items.size(); i++) {
      final ParameterTableModelItemBase<ParameterInfoImpl> item = items.get(i);
      if (i > 0) {
        buffer.append(",");
        buffer.append("\n");
        buffer.append(indent);
      }
      final String text = item.typeCodeFragment.getText();
      buffer.append(text).append(" ");
      final String name = item.parameter.getName();
      buffer.append(name);
      curIndent = indent.length() + text.length() + 1 + name.length();
    }
    // if (!items.isEmpty()) {
    //  buffer.append("\n");
    // }
    buffer.append(")");
    PsiTypeCodeFragment[] thrownExceptionsFragments = myExceptionsModel.getTypeCodeFragments();
    if (thrownExceptionsFragments.length > 0) {
      // buffer.append("\n");
      buffer.append(" throws ");
      curIndent += 9; // ") throws ".length()
      indent = StringUtil.repeatSymbol(' ', curIndent);
      for (int i = 0; i < thrownExceptionsFragments.length; i++) {
        String text = thrownExceptionsFragments[i].getText();
        if (i != 0) buffer.append(indent);
        buffer.append(text);
        if (i < thrownExceptionsFragments.length - 1) {
          buffer.append(",");
        }
        buffer.append("\n");
      }
    }

    return buffer.toString();
  }
Exemplo n.º 3
0
 @Nullable
 private PsiParameter getParameter() {
   if (!myMethod.isValid()) return null;
   final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
   return parameters.length > myParameterIndex && myParameterIndex >= 0
       ? parameters[myParameterIndex]
       : null;
 }
 private void doImport(final PsiMethod toImport) {
   CommandProcessor.getInstance()
       .executeCommand(
           toImport.getProject(),
           new Runnable() {
             @Override
             public void run() {
               ApplicationManager.getApplication()
                   .runWriteAction(
                       new Runnable() {
                         @Override
                         public void run() {
                           try {
                             PsiMethodCallExpression element = myMethodCall.getElement();
                             if (element != null) {
                               element
                                   .getMethodExpression()
                                   .bindToElementViaStaticImport(toImport.getContainingClass());
                             }
                           } catch (IncorrectOperationException e) {
                             LOG.error(e);
                           }
                         }
                       });
             }
           },
           getText(),
           this);
 }
Exemplo n.º 5
0
 @Override
 protected PsiVariable createFieldToStartTemplateOn(
     final String[] names, final PsiType defaultType) {
   final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myMethod.getProject());
   return ApplicationManager.getApplication()
       .runWriteAction(
           new Computable<PsiParameter>() {
             @Override
             public PsiParameter compute() {
               final PsiParameter anchor =
                   JavaIntroduceParameterMethodUsagesProcessor.getAnchorParameter(myMethod);
               final PsiParameter psiParameter =
                   (PsiParameter)
                       myMethod
                           .getParameterList()
                           .addAfter(
                               elementFactory.createParameter(
                                   chooseName(names, myMethod.getLanguage()), defaultType),
                               anchor);
               PsiUtil.setModifierProperty(
                   psiParameter, PsiModifier.FINAL, myPanel.hasFinalModifier());
               myParameterIndex = myMethod.getParameterList().getParameterIndex(psiParameter);
               return psiParameter;
             }
           });
 }
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!FileModificationService.getInstance()
          .preparePsiElementForWrite(descriptor.getPsiElement())) return;
      final PsiModifierListOwner element =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiModifierListOwner.class);
      if (element != null) {
        RefElement refElement = null;
        if (myManager != null) {
          refElement = myManager.getReference(element);
        }
        try {
          if (element instanceof PsiVariable) {
            ((PsiVariable) element).normalizeDeclaration();
          }

          PsiModifierList list = element.getModifierList();

          LOG.assertTrue(list != null);

          if (element instanceof PsiMethod) {
            PsiMethod psiMethod = (PsiMethod) element;
            PsiClass containingClass = psiMethod.getContainingClass();
            if (containingClass != null
                && containingClass.getParent() instanceof PsiFile
                && myHint == PsiModifier.PRIVATE
                && list.hasModifierProperty(PsiModifier.FINAL)) {
              list.setModifierProperty(PsiModifier.FINAL, false);
            }
          }

          list.setModifierProperty(myHint, true);
          if (refElement instanceof RefJavaElement) {
            RefJavaUtil.getInstance().setAccessModifier((RefJavaElement) refElement, myHint);
          }
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }
    }
 @NotNull
 private List<PsiMethod> getMethodsToImport() {
   PsiShortNamesCache cache = PsiShortNamesCache.getInstance(myMethodCall.getProject());
   PsiMethodCallExpression element = myMethodCall.getElement();
   PsiReferenceExpression reference = element.getMethodExpression();
   PsiExpressionList argumentList = element.getArgumentList();
   String name = reference.getReferenceName();
   List<PsiMethod> list = new ArrayList<PsiMethod>();
   if (name == null) return list;
   GlobalSearchScope scope = element.getResolveScope();
   PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(name, scope, 20);
   List<PsiMethod> applicableList = new ArrayList<PsiMethod>();
   final PsiResolveHelper resolveHelper =
       JavaPsiFacade.getInstance(element.getProject()).getResolveHelper();
   for (PsiMethod method : methods) {
     ProgressManager.checkCanceled();
     if (JavaCompletionUtil.isInExcludedPackage(method)) continue;
     if (!method.hasModifierProperty(PsiModifier.STATIC)) continue;
     PsiFile file = method.getContainingFile();
     if (file instanceof PsiJavaFile
         // do not show methods from default package
         && ((PsiJavaFile) file).getPackageName().length() != 0
         && PsiUtil.isAccessible(method, element, method.getContainingClass())) {
       list.add(method);
       PsiSubstitutor substitutorForMethod =
           resolveHelper.inferTypeArguments(
               method.getTypeParameters(),
               method.getParameterList().getParameters(),
               argumentList.getExpressions(),
               PsiSubstitutor.EMPTY,
               element.getParent(),
               DefaultParameterTypeInferencePolicy.INSTANCE);
       if (PsiUtil.isApplicable(method, substitutorForMethod, argumentList)) {
         applicableList.add(method);
       }
     }
   }
   List<PsiMethod> result = applicableList.isEmpty() ? list : applicableList;
   for (int i = result.size() - 1; i >= 0; i--) {
     ProgressManager.checkCanceled();
     PsiMethod method = result.get(i);
     PsiClass containingClass = method.getContainingClass();
     for (int j = i + 1; j < result.size(); j++) {
       PsiMethod exMethod = result.get(j);
       if (!Comparing.strEqual(exMethod.getName(), method.getName())) continue;
       PsiClass exContainingClass = exMethod.getContainingClass();
       if (containingClass != null
           && exContainingClass != null
           && !Comparing.equal(
               containingClass.getQualifiedName(), exContainingClass.getQualifiedName())) continue;
       // same named methods, drop one
       result.remove(i);
       break;
     }
     // check for manually excluded
     if (isExcluded(method)) {
       result.remove(i);
     }
   }
   Collections.sort(result, new PsiProximityComparator(argumentList));
   return result;
 }
  @Override
  public void customizeCellRendererFor(@NotNull SliceUsage sliceUsage) {
    boolean isForcedLeaf = sliceUsage instanceof JavaSliceDereferenceUsage;
    // might come SliceTooComplexDFAUsage
    JavaSliceUsage javaSliceUsage =
        sliceUsage instanceof JavaSliceUsage ? (JavaSliceUsage) sliceUsage : null;

    TextChunk[] text = sliceUsage.getText();
    final List<TextRange> usageRanges = new SmartList<TextRange>();
    sliceUsage.processRangeMarkers(
        new Processor<Segment>() {
          @Override
          public boolean process(Segment segment) {
            usageRanges.add(TextRange.create(segment));
            return true;
          }
        });
    boolean isInsideContainer = javaSliceUsage != null && javaSliceUsage.indexNesting != 0;
    for (int i = 0, length = text.length; i < length; i++) {
      TextChunk textChunk = text[i];
      SimpleTextAttributes attributes = textChunk.getSimpleAttributesIgnoreBackground();
      if (isForcedLeaf) {
        attributes =
            attributes.derive(
                attributes.getStyle(),
                JBColor.LIGHT_GRAY,
                attributes.getBgColor(),
                attributes.getWaveColor());
      }
      boolean inUsage = (attributes.getFontStyle() & Font.BOLD) != 0;
      if (isInsideContainer && inUsage) {
        // Color darker = Color.BLACK;//attributes.getBgColor() == null ? Color.BLACK :
        // attributes.getBgColor().darker();
        // attributes = attributes.derive(SimpleTextAttributes.STYLE_OPAQUE,
        // attributes.getFgColor(), UIUtil.getTreeBackground().brighter(),
        // attributes.getWaveColor());
        // setMyBorder(IdeBorderFactory.createRoundedBorder(10, 3));
        // setPaintFocusBorder(true);
      }
      append(textChunk.getText(), attributes);
      if (i == 0) {
        append(FontUtil.spaceAndThinSpace());
      }
    }

    if (javaSliceUsage != null) {
      for (int i = 0; i < javaSliceUsage.indexNesting; i++) {
        append(
            " (Tracking container contents"
                + (javaSliceUsage.syntheticField.isEmpty()
                    ? ""
                    : " '" + javaSliceUsage.syntheticField + "'")
                + ")",
            SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
      }
    }

    PsiElement element = sliceUsage.getElement();
    PsiMethod method;
    PsiClass aClass;
    while (true) {
      method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
      aClass =
          method == null
              ? PsiTreeUtil.getParentOfType(element, PsiClass.class)
              : method.getContainingClass();
      if (aClass instanceof PsiAnonymousClass) {
        element = aClass;
      } else {
        break;
      }
    }
    int methodOptions =
        PsiFormatUtilBase.SHOW_NAME
            | PsiFormatUtilBase.SHOW_PARAMETERS
            | PsiFormatUtilBase.SHOW_CONTAINING_CLASS;
    String location =
        method != null
            ? PsiFormatUtil.formatMethod(
                method, PsiSubstitutor.EMPTY, methodOptions, PsiFormatUtilBase.SHOW_TYPE, 2)
            : aClass != null
                ? PsiFormatUtil.formatClass(aClass, PsiFormatUtilBase.SHOW_NAME)
                : null;
    if (location != null) {
      SimpleTextAttributes attributes = SimpleTextAttributes.GRAY_ATTRIBUTES;
      append(" in " + location, attributes);
    }
  }