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();
  }
  @NotNull
  private int[] fixRanges(@NotNull DocumentEvent e, int line1, int line2) {
    CharSequence document = myDocument.getCharsSequence();
    int offset = e.getOffset();

    if (e.getOldLength() == 0 && e.getNewLength() != 0) {
      if (StringUtil.endsWithChar(e.getNewFragment(), '\n') && isNewline(offset - 1, document)) {
        return new int[] {line1, line2 - 1};
      }
      if (StringUtil.startsWithChar(e.getNewFragment(), '\n')
          && isNewline(offset + e.getNewLength(), document)) {
        return new int[] {line1 + 1, line2};
      }
    }
    if (e.getOldLength() != 0 && e.getNewLength() == 0) {
      if (StringUtil.endsWithChar(e.getOldFragment(), '\n') && isNewline(offset - 1, document)) {
        return new int[] {line1, line2 - 1};
      }
      if (StringUtil.startsWithChar(e.getOldFragment(), '\n')
          && isNewline(offset + e.getNewLength(), document)) {
        return new int[] {line1 + 1, line2};
      }
    }

    return new int[] {line1, line2};
  }
 private static String trimTrailingSeparators(@NotNull String path, boolean isJar) {
   while (StringUtil.endsWithChar(path, '/')
       && !(isJar && path.endsWith(JarFileSystem.JAR_SEPARATOR))) {
     path = StringUtil.trimEnd(path, "/");
   }
   return path;
 }
 public TestDataReferenceCollector(@Nullable String testDataPath, String testName) {
   if (StringUtil.isNotEmpty(testDataPath)
       && StringUtil.endsWithChar(testDataPath, File.separatorChar)) {
     testDataPath += File.separatorChar;
   }
   myTestDataPath = testDataPath;
   myTestName = testName;
 }
 public static String fixDirName(String dir, boolean replaceUserHome) {
   if (StringUtil.startsWithChar(dir, '\"') && StringUtil.endsWithChar(dir, '\"')) {
     dir = dir.substring(1, dir.length() - 1);
   }
   if (replaceUserHome) {
     dir = FileUtil.expandUserHome(dir);
   }
   return dir;
 }
 @NotNull
 public static String createTooltipText(@Nullable String name, @NotNull AnAction action) {
   String toolTipText = name == null ? "" : name;
   while (StringUtil.endsWithChar(toolTipText, '.')) {
     toolTipText = toolTipText.substring(0, toolTipText.length() - 1);
   }
   String shortcutsText = getFirstKeyboardShortcutText(action);
   if (!shortcutsText.isEmpty()) {
     toolTipText += " (" + shortcutsText + ")";
   }
   return toolTipText;
 }
 @NotNull
 public String getNewCompileOutput() {
   final String projectFilePath = myWizardContext.getProjectFileDirectory();
   @NonNls String path = myWizardContext.getCompilerOutputDirectory();
   if (path == null) {
     path =
         StringUtil.endsWithChar(projectFilePath, '/')
             ? projectFilePath + "out"
             : projectFilePath + "/out";
   }
   return path;
 }
  protected void doComplete(
      final int offset1,
      final int offset2,
      final CompletionContext context,
      final FileCopyPatcher dummyIdentifier,
      final Editor editor,
      final int invocationCount) {
    PsiFile file = context.file;
    int offset = context.getStartOffset();

    PsiElement lastElement = file.findElementAt(offset - 1);
    if (lastElement == null || !StringUtil.endsWithChar(lastElement.getText(), '@')) return;

    super.doComplete(offset1, offset2, context, dummyIdentifier, editor, invocationCount);
  }
  @NotNull
  private EntryInfo getOrCreate(
      @NotNull ZipEntry entry, @NotNull Map<String, EntryInfo> map, @NotNull ZipFile zip) {
    boolean isDirectory = entry.isDirectory();
    String entryName = entry.getName();
    if (StringUtil.endsWithChar(entryName, '/')) {
      entryName = entryName.substring(0, entryName.length() - 1);
      isDirectory = true;
    }

    EntryInfo info = map.get(entryName);
    if (info != null) return info;

    Pair<String, String> path = splitPath(entryName);
    EntryInfo parentInfo = getOrCreate(path.first, map, zip);
    if (".".equals(path.second)) {
      return parentInfo;
    }
    info =
        store(map, parentInfo, path.second, isDirectory, entry.getSize(), myFileStamp, entryName);
    return info;
  }
Beispiel #10
0
  @Override
  public String propertyNameToVariableName(String propertyName, VariableKind variableKind) {
    if (variableKind == VariableKind.STATIC_FINAL_FIELD) {
      String[] words = NameUtil.nameToWords(propertyName);
      StringBuilder buffer = new StringBuilder();
      for (int i = 0; i < words.length; i++) {
        String word = words[i];
        if (i > 0) {
          buffer.append("_");
        }
        buffer.append(StringUtil.toUpperCase(word));
      }
      return buffer.toString();
    }

    String prefix = getPrefixByVariableKind(variableKind);
    String name = propertyName;
    if (!name.isEmpty() && !prefix.isEmpty() && !StringUtil.endsWithChar(prefix, '_')) {
      name = Character.toUpperCase(name.charAt(0)) + name.substring(1);
    }
    name = prefix + name + getSuffixByVariableKind(variableKind);
    name = changeIfNotIdentifier(name);
    return name;
  }
  public final void move(Editor editor, final PsiFile file) {
    myMover.beforeMove(editor, myInfo, myIsDown);
    final Document document = editor.getDocument();
    final int start =
        StatementUpDownMover.getLineStartSafeOffset(document, myInfo.toMove.startLine);
    final int end = StatementUpDownMover.getLineStartSafeOffset(document, myInfo.toMove.endLine);
    myInfo.range1 = document.createRangeMarker(start, end);

    String textToInsert = document.getCharsSequence().subSequence(start, end).toString();
    if (!StringUtil.endsWithChar(textToInsert, '\n')) textToInsert += '\n';

    final int start2 = document.getLineStartOffset(myInfo.toMove2.startLine);
    final int end2 = StatementUpDownMover.getLineStartSafeOffset(document, myInfo.toMove2.endLine);
    String textToInsert2 = document.getCharsSequence().subSequence(start2, end2).toString();
    if (!StringUtil.endsWithChar(textToInsert2, '\n')) textToInsert2 += '\n';
    myInfo.range2 = document.createRangeMarker(start2, end2);
    if (myInfo.range1.getStartOffset() < myInfo.range2.getStartOffset()) {
      myInfo.range1.setGreedyToLeft(true);
      myInfo.range1.setGreedyToRight(false);
      myInfo.range2.setGreedyToLeft(true);
      myInfo.range2.setGreedyToRight(true);
    } else {
      myInfo.range1.setGreedyToLeft(true);
      myInfo.range1.setGreedyToRight(true);
      myInfo.range2.setGreedyToLeft(true);
      myInfo.range2.setGreedyToRight(false);
    }

    final CaretModel caretModel = editor.getCaretModel();
    final int caretRelativePos = caretModel.getOffset() - start;
    final SelectionModel selectionModel = editor.getSelectionModel();
    final int selectionStart = selectionModel.getSelectionStart();
    final int selectionEnd = selectionModel.getSelectionEnd();
    final boolean hasSelection = selectionModel.hasSelection();

    // to prevent flicker
    caretModel.moveToOffset(0);

    // There is a possible case that the user performs, say, method move. It's also possible that
    // one (or both) of moved methods
    // are folded. We want to preserve their states then. The problem is that folding processing is
    // based on PSI element pointers
    // and the pointers behave as following during move up/down:
    //     method1() {}
    //     method2() {}
    // Pointer for the fold region from method1 points to 'method2()' now and vice versa (check
    // range markers processing on
    // document change for further information). I.e. information about fold regions statuses holds
    // the data swapped for
    // 'method1' and 'method2'. Hence, we want to apply correct 'collapsed' status.
    FoldRegion topRegion = null;
    FoldRegion bottomRegion = null;
    for (FoldRegion foldRegion : editor.getFoldingModel().getAllFoldRegions()) {
      if (!foldRegion.isValid()
          || (!contains(myInfo.range1, foldRegion) && !contains(myInfo.range2, foldRegion))) {
        continue;
      }
      if (contains(myInfo.range1, foldRegion) && !contains(topRegion, foldRegion)) {
        topRegion = foldRegion;
      } else if (contains(myInfo.range2, foldRegion) && !contains(bottomRegion, foldRegion)) {
        bottomRegion = foldRegion;
      }
    }

    document.insertString(myInfo.range1.getStartOffset(), textToInsert2);
    document.deleteString(
        myInfo.range1.getStartOffset() + textToInsert2.length(), myInfo.range1.getEndOffset());

    document.insertString(myInfo.range2.getStartOffset(), textToInsert);
    int s = myInfo.range2.getStartOffset() + textToInsert.length();
    int e = myInfo.range2.getEndOffset();
    if (e > s) {
      document.deleteString(s, e);
    }

    final Project project = file.getProject();
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    // Swap fold regions status if necessary.
    if (topRegion != null && bottomRegion != null) {
      final FoldRegion finalTopRegion = topRegion;
      final FoldRegion finalBottomRegion = bottomRegion;
      editor
          .getFoldingModel()
          .runBatchFoldingOperation(
              new Runnable() {
                @Override
                public void run() {
                  boolean topExpanded = finalTopRegion.isExpanded();
                  finalTopRegion.setExpanded(finalBottomRegion.isExpanded());
                  finalBottomRegion.setExpanded(topExpanded);
                }
              });
    }
    CodeFoldingManager.getInstance(project).allowFoldingOnCaretLine(editor);

    if (hasSelection) {
      restoreSelection(editor, selectionStart, selectionEnd, start, myInfo.range2.getStartOffset());
    }

    caretModel.moveToOffset(myInfo.range2.getStartOffset() + caretRelativePos);
    if (myInfo.indentTarget) {
      indentLinesIn(editor, file, document, project, myInfo.range2);
    }
    if (myInfo.indentSource) {
      indentLinesIn(editor, file, document, project, myInfo.range1);
    }

    myMover.afterMove(editor, file, myInfo, myIsDown);
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
  }
  public boolean processUsage(
      @NotNull EncapsulateFieldUsageInfo usage,
      @NotNull EncapsulateFieldsDescriptor descriptor,
      PsiMethod setter,
      PsiMethod getter) {
    final PsiElement element = usage.getElement();
    if (!(element instanceof PsiReferenceExpression)) return false;

    final FieldDescriptor fieldDescriptor = usage.getFieldDescriptor();
    PsiField field = fieldDescriptor.getField();
    boolean processGet = descriptor.isToEncapsulateGet();
    boolean processSet =
        descriptor.isToEncapsulateSet() && !field.hasModifierProperty(PsiModifier.FINAL);
    if (!processGet && !processSet) return true;
    PsiElementFactory factory =
        JavaPsiFacade.getInstance(descriptor.getTargetClass().getProject()).getElementFactory();

    try {
      final PsiReferenceExpression expr = (PsiReferenceExpression) element;
      final PsiElement parent = expr.getParent();
      if (parent instanceof PsiAssignmentExpression
          && expr.equals(((PsiAssignmentExpression) parent).getLExpression())) {
        PsiAssignmentExpression assignment = (PsiAssignmentExpression) parent;
        if (assignment.getRExpression() == null) return true;
        PsiJavaToken opSign = assignment.getOperationSign();
        IElementType opType = opSign.getTokenType();
        if (opType == JavaTokenType.EQ) {
          {
            if (!processSet) return true;
            final PsiExpression setterArgument = assignment.getRExpression();

            PsiMethodCallExpression methodCall =
                createSetterCall(
                    fieldDescriptor, setterArgument, expr, descriptor.getTargetClass(), setter);

            if (methodCall != null) {
              assignment.replace(methodCall);
            }
            // TODO: check if value is used!!!
          }
        } else if (opType == JavaTokenType.ASTERISKEQ
            || opType == JavaTokenType.DIVEQ
            || opType == JavaTokenType.PERCEQ
            || opType == JavaTokenType.PLUSEQ
            || opType == JavaTokenType.MINUSEQ
            || opType == JavaTokenType.LTLTEQ
            || opType == JavaTokenType.GTGTEQ
            || opType == JavaTokenType.GTGTGTEQ
            || opType == JavaTokenType.ANDEQ
            || opType == JavaTokenType.OREQ
            || opType == JavaTokenType.XOREQ) {
          {
            // Q: side effects of qualifier??!

            String opName = opSign.getText();
            LOG.assertTrue(StringUtil.endsWithChar(opName, '='));
            opName = opName.substring(0, opName.length() - 1);

            PsiExpression getExpr = expr;
            if (processGet) {
              final PsiMethodCallExpression getterCall =
                  createGetterCall(fieldDescriptor, expr, descriptor.getTargetClass(), getter);
              if (getterCall != null) {
                getExpr = getterCall;
              }
            }

            @NonNls String text = "a" + opName + "b";
            PsiBinaryExpression binExpr =
                (PsiBinaryExpression) factory.createExpressionFromText(text, expr);
            binExpr.getLOperand().replace(getExpr);
            binExpr.getROperand().replace(assignment.getRExpression());

            PsiExpression setExpr;
            if (processSet) {
              setExpr =
                  createSetterCall(
                      fieldDescriptor, binExpr, expr, descriptor.getTargetClass(), setter);
            } else {
              text = "a = b";
              PsiAssignmentExpression assignment1 =
                  (PsiAssignmentExpression) factory.createExpressionFromText(text, null);
              assignment1.getLExpression().replace(expr);
              assignment1.getRExpression().replace(binExpr);
              setExpr = assignment1;
            }

            assignment.replace(setExpr);
            // TODO: check if value is used!!!
          }
        }
      } else if (RefactoringUtil.isPlusPlusOrMinusMinus(parent)) {
        IElementType sign;
        if (parent instanceof PsiPrefixExpression) {
          sign = ((PsiPrefixExpression) parent).getOperationTokenType();
        } else {
          sign = ((PsiPostfixExpression) parent).getOperationTokenType();
        }

        PsiExpression getExpr = expr;
        if (processGet) {
          final PsiMethodCallExpression getterCall =
              createGetterCall(fieldDescriptor, expr, descriptor.getTargetClass(), getter);
          if (getterCall != null) {
            getExpr = getterCall;
          }
        }

        @NonNls String text;
        if (sign == JavaTokenType.PLUSPLUS) {
          text = "a+1";
        } else {
          text = "a-1";
        }
        PsiBinaryExpression binExpr =
            (PsiBinaryExpression) factory.createExpressionFromText(text, null);
        binExpr.getLOperand().replace(getExpr);

        PsiExpression setExpr;
        if (processSet) {
          setExpr =
              createSetterCall(fieldDescriptor, binExpr, expr, descriptor.getTargetClass(), setter);
        } else {
          text = "a = b";
          PsiAssignmentExpression assignment =
              (PsiAssignmentExpression) factory.createExpressionFromText(text, null);
          assignment.getLExpression().replace(expr);
          assignment.getRExpression().replace(binExpr);
          setExpr = assignment;
        }
        parent.replace(setExpr);
      } else {
        if (!processGet) return true;
        PsiMethodCallExpression methodCall =
            createGetterCall(fieldDescriptor, expr, descriptor.getTargetClass(), getter);

        if (methodCall != null) {
          expr.replace(methodCall);
        }
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    return true;
  }