示例#1
0
  @Nullable
  private String[] suggestVariableNameFromLiterals(
      PsiExpression expr, VariableKind variableKind, boolean correctKeywords) {
    final PsiElement[] literals =
        PsiTreeUtil.collectElements(
            expr,
            new PsiElementFilter() {
              @Override
              public boolean isAccepted(PsiElement element) {
                if (isStringPsiLiteral(element)
                    && StringUtil.isJavaIdentifier(StringUtil.unquoteString(element.getText()))) {
                  final PsiElement exprList = element.getParent();
                  if (exprList instanceof PsiExpressionList) {
                    final PsiElement call = exprList.getParent();
                    if (call instanceof PsiNewExpression) {
                      return true;
                    } else if (call instanceof PsiMethodCallExpression) {
                      // TODO: exclude or not getA().getB("name").getC(); or
                      // getA(getB("name").getC()); It works fine for now in the most cases
                      return true;
                    }
                  }
                }
                return false;
              }
            });

    if (literals.length == 1) {
      final String text = StringUtil.unquoteString(literals[0].getText());
      return getSuggestionsByName(
          text, variableKind, expr.getType() instanceof PsiArrayType, correctKeywords);
    }
    return null;
  }
    @NotNull
    @Override
    public PsiReference[] getReferencesByElement(
        @NotNull final PsiElement element, @NotNull final ProcessingContext context) {
      if (!(element instanceof YAMLKeyValue) || !isPathPackageDefinition((YAMLKeyValue) element)) {
        return PsiReference.EMPTY_ARRAY;
      }

      final PsiElement value = ((YAMLKeyValue) element).getValue();
      if (value == null) {
        return PsiReference.EMPTY_ARRAY;
      }

      final String text =
          StringUtil.trimTrailing(FileUtil.toSystemIndependentName(value.getText()));
      final boolean quoted = StringUtil.isQuotedString(text);
      final int startInElement = value.getStartOffsetInParent() + (quoted ? 1 : 0);

      final FileReferenceSet fileReferenceSet =
          new FileReferenceSet(
              StringUtil.unquoteString(text),
              element,
              startInElement,
              this,
              SystemInfo.isFileSystemCaseSensitive,
              false) {
            @NotNull
            @Override
            public Collection<PsiFileSystemItem> computeDefaultContexts() {
              if (isAbsolutePathReference()) {
                final VirtualFile[] roots = ManagingFS.getInstance().getLocalRoots();
                final Collection<PsiFileSystemItem> result = new SmartList<PsiFileSystemItem>();
                for (VirtualFile root : roots) {
                  ContainerUtil.addIfNotNull(result, element.getManager().findDirectory(root));
                }
                return result;
              }

              return super.computeDefaultContexts();
            }

            @Override
            public boolean isAbsolutePathReference() {
              final String path = getPathString();
              return SystemInfo.isWindows
                  ? path.length() >= 3
                      && Character.isLetter(path.charAt(0))
                      && ':' == path.charAt(1)
                      && '/' == path.charAt(2)
                  : path.startsWith("/");
            }

            @Override
            protected Condition<PsiFileSystemItem> getReferenceCompletionFilter() {
              return DIRECTORY_FILTER;
            }
          };

      return fileReferenceSet.getAllReferences();
    }
示例#3
0
 public static String prepareValueText(String text, Project project) {
   text = StringUtil.unquoteString(text);
   text = StringUtil.unescapeStringCharacters(text);
   int tabSize = CodeStyleSettingsManager.getSettings(project).getTabSize(StdFileTypes.JAVA);
   if (tabSize < 0) {
     tabSize = 0;
   }
   return text.replace("\t", StringUtil.repeat(" ", tabSize));
 }
示例#4
0
  protected static String getTypeTextFromFile() {
    String text = getEditor().getDocument().getText();

    String[] directives = InTextDirectivesUtils.findArrayWithPrefixes(text, TYPE_DIRECTIVE_PREFIX);
    assertEquals(
        "One directive with \"" + TYPE_DIRECTIVE_PREFIX + "\" expected", 1, directives.length);

    return StringUtil.unquoteString(directives[0]);
  }
 @Nullable
 public static String getTestLabel(@NotNull final DartCallExpression testCallExpression) {
   final DartArguments arguments = testCallExpression.getArguments();
   final DartArgumentList argumentList = arguments == null ? null : arguments.getArgumentList();
   final List<DartExpression> argExpressions =
       argumentList == null ? null : argumentList.getExpressionList();
   return argExpressions != null
           && !argExpressions.isEmpty()
           && argExpressions.get(0) instanceof DartStringLiteralExpression
       ? StringUtil.unquoteString(argExpressions.get(0).getText())
       : null;
 }
 @NotNull
 public static Collection<String> generateNames(@NotNull String name) {
   name =
       StringUtil.decapitalize(
           deleteNonLetterFromString(StringUtil.unquoteString(name.replace('.', '_'))));
   if (name.startsWith("get")) {
     name = name.substring(3);
   } else if (name.startsWith("is")) {
     name = name.substring(2);
   }
   while (name.startsWith("_")) {
     name = name.substring(1);
   }
   while (name.endsWith("_")) {
     name = name.substring(0, name.length() - 1);
   }
   final int length = name.length();
   final Collection<String> possibleNames = new LinkedHashSet<String>();
   for (int i = 0; i < length; i++) {
     if (Character.isLetter(name.charAt(i))
         && (i == 0
             || name.charAt(i - 1) == '_'
             || (Character.isLowerCase(name.charAt(i - 1))
                 && Character.isUpperCase(name.charAt(i))))) {
       final String candidate = StringUtil.decapitalize(name.substring(i));
       if (candidate.length() < 25) {
         possibleNames.add(candidate);
       }
     }
   }
   // prefer shorter names
   ArrayList<String> reversed = new ArrayList<String>(possibleNames);
   Collections.reverse(reversed);
   return ContainerUtil.map(
       reversed,
       name1 -> {
         if (name1.indexOf('_') == -1) {
           return name1;
         }
         name1 = StringUtil.capitalizeWords(name1, "_", true, true);
         return StringUtil.decapitalize(name1.replaceAll("_", ""));
       });
 }
  public static void chooseColor(
      JComponent editorComponent, PsiElement element, String caption, boolean startInWriteAction) {
    final XmlAttributeValue literal =
        PsiTreeUtil.getParentOfType(element, XmlAttributeValue.class, false);
    if (literal == null) return;
    final String text = StringUtil.unquoteString(literal.getValue());

    Color oldColor;
    try {
      oldColor = Color.decode(text);
    } catch (NumberFormatException e) {
      oldColor = JBColor.GRAY;
    }
    Color color = ColorChooser.chooseColor(editorComponent, caption, oldColor, true);
    if (color == null) return;
    if (!Comparing.equal(color, oldColor)) {
      if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return;
      final String newText = "#" + ColorUtil.toHex(color);
      final PsiManager manager = literal.getManager();
      final XmlAttribute newAttribute =
          XmlElementFactory.getInstance(manager.getProject()).createXmlAttribute("name", newText);
      final Runnable replaceRunnable =
          new Runnable() {
            @Override
            public void run() {
              final XmlAttributeValue valueElement = newAttribute.getValueElement();
              assert valueElement != null;
              literal.replace(valueElement);
            }
          };
      if (startInWriteAction) {
        new WriteCommandAction(element.getProject(), caption) {
          @Override
          protected void run(@NotNull Result result) throws Throwable {
            replaceRunnable.run();
          }
        }.execute();
      } else {
        replaceRunnable.run();
      }
    }
  }
        @NotNull
        @Override
        protected Map<String, String> compute() {
          if (isUnix && !isMac) {
            try {
              List<String> lines = FileUtil.loadLines("/etc/os-release");
              Map<String, String> info = ContainerUtil.newHashMap();
              for (String line : lines) {
                int p = line.indexOf('=');
                if (p > 0) {
                  String name = line.substring(0, p);
                  String value = StringUtil.unquoteString(line.substring(p + 1));
                  if (!StringUtil.isEmptyOrSpaces(name) && !StringUtil.isEmptyOrSpaces(value)) {
                    info.put(name, value);
                  }
                }
              }
              return info;
            } catch (IOException ignored) {
            }
          }

          return Collections.emptyMap();
        }
 @Override
 public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
   final PsiFile containingFile = element.getContainingFile();
   if (!JavaFxFileTypeFactory.isFxml(containingFile)) return;
   if (element instanceof XmlAttributeValue) {
     final String value = ((XmlAttributeValue) element).getValue();
     if (!JavaFxPsiUtil.isExpressionBinding(value)
         && !JavaFxPsiUtil.isIncorrectExpressionBinding(value)) {
       final PsiReference[] references = element.getReferences();
       for (PsiReference reference : references) {
         if (reference instanceof JavaFxColorReference) {
           attachColorIcon(element, holder, StringUtil.unquoteString(element.getText()));
           continue;
         }
         final PsiElement resolve = reference.resolve();
         if (resolve instanceof PsiMember) {
           if (!JavaFxPsiUtil.isVisibleInFxml((PsiMember) resolve)) {
             final String symbolPresentation =
                 "'" + SymbolPresentationUtil.getSymbolPresentableText(resolve) + "'";
             final Annotation annotation =
                 holder.createErrorAnnotation(
                     element,
                     symbolPresentation
                         + (resolve instanceof PsiClass
                             ? " should be public"
                             : " should be public or annotated with @FXML"));
             if (!(resolve instanceof PsiClass)) {
               annotation.registerUniversalFix(
                   new AddAnnotationFix(
                       JavaFxCommonNames.JAVAFX_FXML_ANNOTATION,
                       (PsiMember) resolve,
                       ArrayUtil.EMPTY_STRING_ARRAY),
                   null,
                   null);
             }
           }
         }
       }
     }
   } else if (element instanceof XmlAttribute) {
     final XmlAttribute attribute = (XmlAttribute) element;
     final String attributeName = attribute.getName();
     if (!FxmlConstants.FX_BUILT_IN_ATTRIBUTES.contains(attributeName)
         && !attribute.isNamespaceDeclaration()
         && JavaFxPsiUtil.isReadOnly(attributeName, attribute.getParent())) {
       holder.createErrorAnnotation(
           element.getNavigationElement(), "Property '" + attributeName + "' is read-only");
     }
     if (FxmlConstants.SOURCE.equals(attributeName)) {
       final XmlAttributeValue valueElement = attribute.getValueElement();
       if (valueElement != null) {
         final XmlTag xmlTag = attribute.getParent();
         if (xmlTag != null) {
           final XmlTag referencedTag = JavaFxBuiltInTagDescriptor.getReferencedTag(xmlTag);
           if (referencedTag != null) {
             if (referencedTag.getTextOffset() > xmlTag.getTextOffset()) {
               holder.createErrorAnnotation(
                   valueElement.getValueTextRange(), valueElement.getValue() + " not found");
             } else if (xmlTag.getParentTag() == referencedTag.getParentTag()) {
               final Annotation annotation =
                   holder.createErrorAnnotation(
                       valueElement.getValueTextRange(), "Duplicate child added");
               annotation.registerFix(
                   new JavaFxWrapWithDefineIntention(referencedTag, valueElement.getValue()));
             }
           }
         }
       }
     }
   } else if (element instanceof XmlTag) {
     if (FxmlConstants.FX_SCRIPT.equals(((XmlTag) element).getName())) {
       final XmlTagValue tagValue = ((XmlTag) element).getValue();
       if (!StringUtil.isEmptyOrSpaces(tagValue.getText())) {
         final List<String> langs =
             JavaFxPsiUtil.parseInjectedLanguages((XmlFile) element.getContainingFile());
         if (langs.isEmpty()) {
           final ASTNode openTag = element.getNode().findChildByType(XmlTokenType.XML_NAME);
           final Annotation annotation =
               holder.createErrorAnnotation(
                   openTag != null ? openTag.getPsi() : element, "Page language not specified.");
           annotation.registerFix(new JavaFxInjectPageLanguageIntention());
         }
       }
     }
   }
 }
  @Override
  public JComponent getPreviewComponent(@NotNull PsiElement element) {
    final PsiNewExpression psiNewExpression =
        PsiTreeUtil.getParentOfType(element, PsiNewExpression.class);

    if (psiNewExpression != null) {
      final PsiJavaCodeReferenceElement referenceElement =
          PsiTreeUtil.getChildOfType(psiNewExpression, PsiJavaCodeReferenceElement.class);

      if (referenceElement != null) {
        final PsiReference reference = referenceElement.getReference();

        if (reference != null) {
          final PsiElement psiElement = reference.resolve();

          if (psiElement instanceof PsiClass
              && "java.awt.Color".equals(((PsiClass) psiElement).getQualifiedName())) {
            final PsiExpressionList argumentList = psiNewExpression.getArgumentList();

            if (argumentList != null) {
              final PsiExpression[] expressions = argumentList.getExpressions();
              int[] values = ArrayUtil.newIntArray(expressions.length);
              float[] values2 = new float[expressions.length];
              int i = 0;
              int j = 0;

              final PsiConstantEvaluationHelper helper =
                  JavaPsiFacade.getInstance(element.getProject()).getConstantEvaluationHelper();
              for (final PsiExpression each : expressions) {
                final Object o = helper.computeConstantExpression(each);
                if (o instanceof Integer) {
                  values[i] = ((Integer) o).intValue();
                  if (expressions.length != 1) {
                    values[i] = values[i] > 255 ? 255 : values[i] < 0 ? 0 : values[i];
                  }

                  i++;
                } else if (o instanceof Float) {
                  values2[j] = ((Float) o).floatValue();
                  values2[j] = values2[j] > 1 ? 1 : values2[j] < 0 ? 0 : values2[j];
                  j++;
                }
              }

              Color c = null;
              if (i == expressions.length) {
                if (i == 1 && values[0] > 255) {
                  c = new Color(values[0]);
                } else {
                  switch (values.length) {
                    case 1:
                      c = new Color(values[0]);
                      break;
                    case 3:
                      c = new Color(values[0], values[1], values[2]);
                      break;
                    case 4:
                      c = new Color(values[0], values[1], values[2], values[3]);
                      break;
                    default:
                      break;
                  }
                }
              } else if (j == expressions.length) {
                switch (values2.length) {
                  case 3:
                    c = new Color(values2[0], values2[1], values2[2]);
                    break;
                  case 4:
                    c = new Color(values2[0], values2[1], values2[2], values2[3]);
                    break;
                  default:
                    break;
                }
              }

              if (c != null) {
                return new ColorPreviewComponent(c);
              }
            }
          }
        }
      }
    }

    if (ColorChooserIntentionAction.isInsideDecodeOrGetColorMethod(element)) {
      final String color = StringUtil.unquoteString(element.getText());
      try {
        return new ColorPreviewComponent(Color.decode(color));
      } catch (NumberFormatException ignore) {
      }
    }

    if (PlatformPatterns.psiElement(PsiIdentifier.class)
        .withParent(PlatformPatterns.psiElement(PsiReferenceExpression.class))
        .accepts(element)) {
      final PsiReference reference = element.getParent().getReference();

      if (reference != null) {
        final PsiElement psiElement = reference.resolve();

        if (psiElement instanceof PsiField) {
          if ("java.awt.Color"
              .equals(((PsiField) psiElement).getContainingClass().getQualifiedName())) {
            final String colorName =
                ((PsiField) psiElement).getName().toLowerCase().replace("_", "");
            final String hex = ColorSampleLookupValue.getHexCodeForColorName(colorName);
            return new ColorPreviewComponent(Color.decode("0x" + hex.substring(1)));
          }
        }
      }
    }

    if (PlatformPatterns.psiElement()
        .withParent(PlatformPatterns.psiElement(PsiLiteralExpression.class))
        .accepts(element)) {
      final PsiLiteralExpression psiLiteralExpression = (PsiLiteralExpression) element.getParent();
      if (psiLiteralExpression != null) {
        return ImagePreviewComponent.getPreviewComponent(psiLiteralExpression);
      }
    }

    return null;
  }