Java Code Examples for com.intellij.openapi.util.text.StringUtil

The following examples show how to use com.intellij.openapi.util.text.StringUtil. These examples are extracted from open source projects.
Example 1
Project: consulo   File: BrowserLauncherImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doShowError(@Nullable final String error, @Nullable final WebBrowser browser, @Nullable final Project project, final String title, @Nullable final Runnable launchTask) {
  AppUIUtil.invokeOnEdt(new Runnable() {
    @Override
    public void run() {
      if (Messages.showYesNoDialog(project, StringUtil.notNullize(error, "Unknown error"), title == null ? IdeBundle.message("browser" + ".error") : title, Messages.OK_BUTTON,
                                   IdeBundle.message("button.fix"), null) == Messages.NO) {
        final BrowserSettings browserSettings = new BrowserSettings();

        AsyncResult<Void> result = ShowSettingsUtil.getInstance().editConfigurable(project, browserSettings, browser == null ? null : (Runnable)() -> browserSettings.selectBrowser(browser));
        result.doWhenDone(() -> {
          if (launchTask != null) {
            launchTask.run();
          }
        });
      }
    }
  }, project == null ? null : project.getDisposed());
}
 
Example 2
Project: intellij   File: SwitchToHeaderOrSourceSearch.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static OCFile correlateTestToHeader(OCFile file) {
  // Quickly check foo_test.cc -> foo.h as well. "getAssociatedFileWithSameName" only does
  // foo.cc <-> foo.h. However, if you do goto-related-symbol again, it will go from
  // foo.h -> foo.cc instead of back to foo_test.cc.
  PsiManager psiManager = PsiManager.getInstance(file.getProject());
  String pathWithoutExtension = FileUtil.getNameWithoutExtension(file.getVirtualFile().getPath());
  for (String testSuffix : PartnerFilePatterns.DEFAULT_PARTNER_SUFFIXES) {
    if (pathWithoutExtension.endsWith(testSuffix)) {
      String possibleHeaderName = StringUtil.trimEnd(pathWithoutExtension, testSuffix) + ".h";
      VirtualFile virtualFile = VfsUtil.findFileByIoFile(new File(possibleHeaderName), false);
      if (virtualFile != null) {
        PsiFile psiFile = psiManager.findFile(virtualFile);
        if (psiFile instanceof OCFile) {
          return (OCFile) psiFile;
        }
      }
    }
  }
  return null;
}
 
Example 3
Project: consulo   File: ExportTestResultsForm.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public String validate() {
  if (getExportFormat() == ExportTestResultsConfiguration.ExportFormat.UserTemplate) {
    if (StringUtil.isEmpty(myCustomTemplateField.getText())) {
      return ExecutionBundle.message("export.test.results.custom.template.path.empty");
    }
    File file = new File(myCustomTemplateField.getText());
    if (!file.isFile()) {
      return ExecutionBundle.message("export.test.results.custom.template.not.found", file.getAbsolutePath());
    }
  }

  if (StringUtil.isEmpty(myFileNameField.getText())) {
    return ExecutionBundle.message("export.test.results.output.filename.empty");
  }
  if (StringUtil.isEmpty(myFolderField.getText())) {
    return ExecutionBundle.message("export.test.results.output.path.empty");
  }

  return null;
}
 
Example 4
Project: lombok-intellij-plugin   File: LombokConfigIndex.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@NotNull
@Override
public KeyDescriptor<ConfigIndexKey> getKeyDescriptor() {
  return new KeyDescriptor<ConfigIndexKey>() {
    @Override
    public int getHashCode(ConfigIndexKey configKey) {
      return configKey.hashCode();
    }

    @Override
    public boolean isEqual(ConfigIndexKey val1, ConfigIndexKey val2) {
      return val1.equals(val2);
    }

    @Override
    public void save(@NotNull DataOutput out, ConfigIndexKey value) throws IOException {
      out.writeUTF(StringUtil.notNullize(value.getDirectoryName()));
      out.writeUTF(StringUtil.notNullize(value.getConfigKey()));
    }

    @Override
    public ConfigIndexKey read(@NotNull DataInput in) throws IOException {
      return new ConfigIndexKey(in.readUTF(), in.readUTF());
    }
  };
}
 
Example 5
Project: idea-php-symfony2-plugin   File: YamlHelper.java    License: MIT License 6 votes vote down vote up
@Nullable
public static PsiElement insertKeyIntoFile(final @NotNull YAMLFile yamlFile, final @NotNull YAMLKeyValue yamlKeyValue, @NotNull String... keys) {
    String keyText = yamlKeyValue.getKeyText();

    return insertKeyIntoFile(yamlFile, (yamlMapping, chainedKey) -> {
        String text = yamlKeyValue.getText();

        final String previousIndent = StringUtil.repeatSymbol(' ', YAMLUtil.getIndentInThisLine(yamlMapping));

        // split content of array value object;
        // drop first item as getValueText() removes our key indent
        String[] remove = (String[]) ArrayUtils.remove(text.split("\\r?\\n"), 0);

        List<String> map = ContainerUtil.map(remove, s -> previousIndent + s);

        return "\n" + StringUtils.strip(StringUtils.join(map, "\n"), "\n");
    }, (String[]) ArrayUtils.add(keys, keyText));
}
 
Example 6
Project: flutter-intellij   File: DartElementPresentationUtil.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void renderElement(@NotNull Element element, @NotNull OutlineTreeCellRenderer renderer, boolean nameInBold) {
  final SimpleTextAttributes attributes =
    nameInBold ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES;

  renderer.appendSearch(element.getName(), attributes);

  if (!StringUtil.isEmpty(element.getTypeParameters())) {
    renderer.appendSearch(element.getTypeParameters(), attributes);
  }
  if (!StringUtil.isEmpty(element.getParameters())) {
    renderer.appendSearch(element.getParameters(), attributes);
  }
  if (!StringUtil.isEmpty(element.getReturnType())) {
    renderer.append(" ");
    renderer.append(DartPresentableUtil.RIGHT_ARROW);
    renderer.append(" ");
    renderer.appendSearch(element.getReturnType(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
  }
}
 
Example 7
Project: consulo   File: PersistentMapTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test2GLimit() throws IOException {
  if (!DO_SLOW_TEST) return;
  File file = FileUtil.createTempFile("persistent", "map");
  FileUtil.createParentDirs(file);
  EnumeratorStringDescriptor stringDescriptor = new EnumeratorStringDescriptor();
  PersistentHashMap<String, String> map = new PersistentHashMap<String, String>(file, stringDescriptor, stringDescriptor);
  for (int i = 0; i < 12000; i++) {
    map.put("abc" + i, StringUtil.repeat("0123456789", 10000));
  }
  map.close();

  map = new PersistentHashMap<String, String>(file,
                                              stringDescriptor, stringDescriptor);
  long len = 0;
  for (String key : map.getAllKeysWithExistingMapping()) {
    len += map.get(key).length();
  }
  map.close();
  assertEquals(1200000000L, len);
}
 
Example 8
Project: consulo   File: ConsoleViewImpl.java    License: Apache License 2.0 6 votes vote down vote up
private static int evaluateBackspacesInTokens(@Nonnull List<? extends TokenBuffer.TokenInfo> source, int sourceStartIndex, @Nonnull List<? super TokenBuffer.TokenInfo> dest) {
  int backspacesFromNextToken = 0;
  for (int i = source.size() - 1; i >= sourceStartIndex; i--) {
    TokenBuffer.TokenInfo token = source.get(i);
    final TokenBuffer.TokenInfo newToken;
    if (StringUtil.containsChar(token.getText(), BACKSPACE) || backspacesFromNextToken > 0) {
      StringBuilder tokenTextBuilder = new StringBuilder(token.getText().length() + backspacesFromNextToken);
      tokenTextBuilder.append(token.getText());
      for (int j = 0; j < backspacesFromNextToken; j++) {
        tokenTextBuilder.append(BACKSPACE);
      }
      normalizeBackspaceCharacters(tokenTextBuilder);
      backspacesFromNextToken = getBackspacePrefixLength(tokenTextBuilder);
      String newText = tokenTextBuilder.substring(backspacesFromNextToken);
      newToken = new TokenBuffer.TokenInfo(token.contentType, newText, token.getHyperlinkInfo());
    }
    else {
      newToken = token;
    }
    dest.add(newToken);
  }
  Collections.reverse(dest);
  return backspacesFromNextToken;
}
 
Example 9
Project: consulo   File: OptionTagBinding.java    License: Apache License 2.0 6 votes vote down vote up
public OptionTagBinding(@Nonnull MutableAccessor accessor, @Nullable OptionTag optionTag) {
  super(accessor, optionTag == null ? null : optionTag.value(), optionTag == null ? null : optionTag.converter());

  if (optionTag == null) {
    myTagName = Constants.OPTION;
    myNameAttribute = Constants.NAME;
    myValueAttribute = Constants.VALUE;
  }
  else {
    myNameAttribute = optionTag.nameAttribute();
    myValueAttribute = optionTag.valueAttribute();

    String tagName = optionTag.tag();
    if (StringUtil.isEmpty(myNameAttribute) && Constants.OPTION.equals(tagName)) {
      tagName = myAccessor.getName();
    }
    myTagName = tagName;
  }
}
 
Example 10
Project: consulo   File: WSLDistribution.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to resolve symlink with a given timeout
 *
 * @param path                  path in question
 * @param timeoutInMilliseconds timeout for execution
 * @return actual file name
 */
@Nonnull
public String resolveSymlink(@Nonnull String path, int timeoutInMilliseconds) {

  try {
    final ProcessOutput output = executeOnWsl(timeoutInMilliseconds, "readlink", "-f", path);
    if (output.getExitCode() == 0) {
      String stdout = output.getStdout().trim();
      if (output.getExitCode() == 0 && StringUtil.isNotEmpty(stdout)) {
        return stdout;
      }
    }
  }
  catch (ExecutionException e) {
    LOG.debug("Error while resolving symlink: " + path, e);
  }
  return path;
}
 
Example 11
Project: consulo   File: TreeState.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static String calcId(@Nullable Object userObject) {
  if (userObject == null) return "";
  Object value = userObject instanceof NodeDescriptorProvidingKey
                 ? ((NodeDescriptorProvidingKey)userObject).getKey()
                 : userObject instanceof AbstractTreeNode ? ((AbstractTreeNode)userObject).getValue() : userObject;
  if (value instanceof NavigationItem) {
    try {
      String name = ((NavigationItem)value).getName();
      return name != null ? name : StringUtil.notNullize(value.toString());
    }
    catch (Exception ignored) {
    }
  }
  return StringUtil.notNullize(userObject.toString());
}
 
Example 12
Project: consulo   File: BeanBinding.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static Pair<String, Boolean> getPropertyData(@Nonnull String methodName) {
  String part = "";
  boolean isSetter = false;
  if (methodName.startsWith("get")) {
    part = methodName.substring(3, methodName.length());
  }
  else if (methodName.startsWith("is")) {
    part = methodName.substring(2, methodName.length());
  }
  else if (methodName.startsWith("set")) {
    part = methodName.substring(3, methodName.length());
    isSetter = true;
  }
  return part.isEmpty() ? null : Pair.create(StringUtil.decapitalize(part), isSetter);
}
 
Example 13
Project: consulo   File: XValueContainerNode.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public XDebuggerTreeNode addTemporaryEditorNode(@Nullable Image icon, @Nullable String text) {
  if (isLeaf()) {
    setLeaf(false);
  }
  myTree.expandPath(getPath());
  MessageTreeNode node = new MessageTreeNode(myTree, this, true);
  node.setIcon(icon);
  if (!StringUtil.isEmpty(text)) {
    node.getText().append(text, SimpleTextAttributes.REGULAR_ATTRIBUTES);
  }
  myTemporaryEditorNode = node;
  myCachedAllChildren = null;
  fireNodesInserted(Collections.singleton(node));
  return node;
}
 
Example 14
Project: consulo-csharp   File: CSharpTypeStubElementType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@RequiredReadAction
public void indexStub(@Nonnull CSharpTypeDeclStub stub, @Nonnull IndexSink indexSink)
{
	String name = getName(stub);
	if(!StringUtil.isEmpty(name))
	{
		indexSink.occurrence(CSharpIndexKeys.TYPE_INDEX, name);

		String parentQName = stub.getParentQName();
		if(!stub.isNested())
		{
			DotNetNamespaceStubUtil.indexStub(indexSink, CSharpIndexKeys.MEMBER_BY_NAMESPACE_QNAME_INDEX, CSharpIndexKeys.MEMBER_BY_ALL_NAMESPACE_QNAME_INDEX, parentQName, name);

			if(BitUtil.isSet(stub.getOtherModifierMask(), CSharpTypeDeclStub.HAVE_EXTENSIONS))
			{
				indexSink.occurrence(CSharpIndexKeys.TYPE_WITH_EXTENSION_METHODS_INDEX, DotNetNamespaceStubUtil.getIndexableNamespace(parentQName));
			}
		}

		indexSink.occurrence(CSharpIndexKeys.TYPE_BY_VMQNAME_INDEX, stub.getVmQName().hashCode());
	}
}
 
Example 15
Project: intellij   File: FileLookupData.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static FileLookupData nonLocalFileLookup(
    String originalLabel,
    @Nullable BuildFile containingFile,
    QuoteType quoteType,
    PathFormat pathFormat) {
  if (originalLabel.indexOf(':') != -1) {
    // it's a package-local reference
    return null;
  }
  // handle the single '/' case by calling twice.
  String relativePath = StringUtil.trimStart(StringUtil.trimStart(originalLabel, "/"), "/");
  if (relativePath.startsWith("/")) {
    return null;
  }
  boolean onlyDirectories = pathFormat != PathFormat.NonLocalWithoutInitialBackslashes;
  VirtualFileFilter filter = vf -> !onlyDirectories || vf.isDirectory();
  return new FileLookupData(
      originalLabel, containingFile, null, relativePath, pathFormat, quoteType, filter);
}
 
Example 16
Project: consulo   File: ShowUsagesAction.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static List<UsageNode> collectData(@Nonnull List<Usage> usages,
                                           @Nonnull Collection<UsageNode> visibleNodes,
                                           @Nonnull UsageViewImpl usageView,
                                           @Nonnull UsageViewPresentation presentation) {
  @Nonnull List<UsageNode> data = new ArrayList<>();
  int filtered = filtered(usages, usageView);
  if (filtered != 0) {
    data.add(createStringNode(UsageViewBundle.message("usages.were.filtered.out", filtered)));
  }
  data.addAll(visibleNodes);
  if (data.isEmpty()) {
    String progressText = StringUtil.escapeXml(UsageViewManagerImpl.getProgressTitle(presentation));
    data.add(createStringNode(progressText));
  }
  Collections.sort(data, USAGE_NODE_COMPARATOR);
  return data;
}
 
Example 17
Project: consulo   File: PatternCompilerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private StringBuilder toString(final Node node, final StringBuilder sb) {
  if (node.target == ERROR_NODE) {
    return sb.append(node.method);
  }
  if (node.target != null) {
    toString(node.target, sb);
    sb.append('.');
  }
  sb.append(node.method).append('(');
  boolean first = true;
  for (Object arg : node.args) {
    if (first) first = false;
    else sb.append(',').append(' ');
    if (arg instanceof Node) {
      toString((Node)arg, sb);
    }
    else if (arg instanceof String) {
      sb.append('\"').append(StringUtil.escapeStringCharacters((String)arg)).append('\"');
    }
    else if (arg instanceof Number) {
      sb.append(arg);
    }
  }
  sb.append(')');
  return sb;
}
 
Example 18
Project: consulo   File: TestSuiteStack.java    License: Apache License 2.0 5 votes vote down vote up
protected String getSuitePathPresentation() {
  final String[] names = getSuitePath();
  if (names.length == 0) {
    return EMPTY;
  }

  return StringUtil.join(names, new Function<String, String>() {
    @Override
    public String fun(String s) {
      return "[" + s + "]";
    }
  }, "->");
}
 
Example 19
Project: consulo   File: DocumentCommitThread.java    License: Apache License 2.0 5 votes vote down vote up
@NonNls
@Override
public String toString() {
  Document document = getDocument();
  String indicatorInfo = isCanceled() ? " (Canceled: " + ((UserDataHolder)indicator).getUserData(CANCEL_REASON) + ")" : "";
  String removedInfo = dead ? " (dead)" : "";
  String reasonInfo = " task reason: " +
                      StringUtil.first(String.valueOf(reason), 180, true) +
                      (isStillValid() ? "" : "; changed: old seq=" + modificationSequence + ", new seq=" + ((DocumentEx)document).getModificationSequence());
  String contextInfo = " Context: " + myCreationContext;
  return System.identityHashCode(this) + "; " + indicatorInfo + removedInfo + contextInfo + reasonInfo;
}
 
Example 20
Project: consulo   File: RemoteCredentialsHolder.java    License: Apache License 2.0 5 votes vote down vote up
public void setSerializedUserName(String userName) {
  if (StringUtil.isEmpty(userName)) {
    myUserName = null;
  }
  else {
    myUserName = userName;
  }
}
 
Example 21
Project: react-templates-plugin   File: AbstractCreateFormAction.java    License: MIT License 5 votes vote down vote up
protected String createFormBody(@Nullable String fqn, @NonNls String formName, String layoutManager) throws IncorrectOperationException {
        String s = "";
        try {
            s = FileUtil.loadTextAndClose(getClass().getResourceAsStream(formName));
        } catch (IOException e) {
//      throw new IncorrectOperationException(RTBundle.message("error.cannot.read", formName), (Throwable)e);
        }
        s = fqn == null ? StringUtil.replace(s, "bind-to-class=\"$CLASS$\"", "") : StringUtil.replace(s, "$CLASS$", fqn);
        s = StringUtil.replace(s, "$LAYOUT$", layoutManager);
        return StringUtil.convertLineSeparators(s);
    }
 
Example 22
Project: consulo   File: DumpLookupElementWeights.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> getLookupElementWeights(LookupImpl lookup, boolean hideSingleValued) {
  final Map<LookupElement, List<Pair<String, Object>>> weights = lookup.getRelevanceObjects(lookup.getItems(), hideSingleValued);
  return ContainerUtil.map(weights.entrySet(), new Function<Map.Entry<LookupElement, List<Pair<String, Object>>>, String>() {
    @Override
    public String fun(Map.Entry<LookupElement, List<Pair<String, Object>>> entry) {
      return entry.getKey().getLookupString() + "\t" + StringUtil.join(entry.getValue(), new Function<Pair<String, Object>, String>() {
        @Override
        public String fun(Pair<String, Object> pair) {
          return pair.first + "=" + pair.second;
        }
      }, ", ");
    }
  });
}
 
Example 23
Project: consulo   File: FSRecords.java    License: Apache License 2.0 5 votes vote down vote up
static void storeSymlinkTarget(int id, @Nullable String symlinkTarget) {
  writeAndHandleErrors(() -> {
    DbConnection.markDirty();
    try (DataOutputStream stream = writeAttribute(id, ourSymlinkTargetAttr)) {
      IOUtil.writeUTF(stream, StringUtil.notNullize(symlinkTarget));
    }
  });
}
 
Example 24
Project: consulo   File: LoadTextUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void changeLineSeparators(@Nullable Project project, @Nonnull VirtualFile file, @Nonnull String newSeparator, @Nonnull Object requestor) throws IOException {
  CharSequence currentText = getTextByBinaryPresentation(file.contentsToByteArray(), file, true, false);
  String currentSeparator = detectLineSeparator(file, false);
  if (newSeparator.equals(currentSeparator)) {
    return;
  }
  String newText = StringUtil.convertLineSeparators(currentText.toString(), newSeparator);

  file.setDetectedLineSeparator(newSeparator);
  write(project, file, requestor, newText, -1);
}
 
Example 25
Project: intellij-swagger   File: JsonReferenceInspection.java    License: MIT License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(
    @NotNull final ProblemsHolder holder,
    final boolean isOnTheFly,
    @NotNull final LocalInspectionToolSession session) {
  final PsiFile file = holder.getFile();
  final VirtualFile virtualFile = file.getVirtualFile();
  final Project project = holder.getProject();

  boolean checkRefs =
      indexFacade.isMainSpecFile(virtualFile, project)
          || indexFacade.isPartialSpecFile(virtualFile, project);

  return new JsonElementVisitor() {
    @Override
    public void visitProperty(@NotNull JsonProperty o) {
      if (!checkRefs) {
        return;
      }
      if ("$ref".equals(o.getName())) {
        JsonValue value = o.getValue();

        if (!(value instanceof JsonStringLiteral)) {
          return;
        }

        final String unquotedValue = StringUtil.unquoteString(value.getText());

        if (!unquotedValue.startsWith("http")) {
          doCheck(holder, value, new CreateJsonReferenceIntentionAction(unquotedValue));
        }
      }
      super.visitProperty(o);
    }
  };
}
 
Example 26
Project: consulo   File: ConflictsDialog.java    License: Apache License 2.0 5 votes vote down vote up
private UsagePresentation getPresentation(final UsagePresentation usagePresentation, PsiElement element) {
  final Collection<String> elementConflicts = new LinkedHashSet<String>(myElementConflictDescription.get(element));
  final String conflictDescription = " (" + Pattern.compile("<[^<>]*>").matcher(StringUtil.join(elementConflicts, "\n")).replaceAll("") + ")";
  return new UsagePresentation() {
    @Override
    @Nonnull
    public TextChunk[] getText() {
      final TextChunk[] chunks = usagePresentation.getText();
      return ArrayUtil
        .append(chunks, new TextChunk(SimpleTextAttributes.GRAY_ITALIC_ATTRIBUTES.toTextAttributes(), conflictDescription));
    }

    @Override
    @Nonnull
    public String getPlainText() {
      return usagePresentation.getPlainText() + conflictDescription;
    }

    @Override
    public Image getIcon() {
      return usagePresentation.getIcon();
    }

    @Override
    public String getTooltipText() {
      return usagePresentation.getTooltipText();
    }
  };
}
 
Example 27
Project: consulo   File: ModuleExtensionProviderEP.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
protected Image compute() {
  if (StringUtil.isEmpty(icon)) {
    return AllIcons.Toolbar.Unknown;
  }
  Image temp = IconLoader.findIcon(icon, getLoaderForClass());
  return temp == null ? AllIcons.Toolbar.Unknown : temp;
}
 
Example 28
Project: consulo   File: StubProvidedIndexExtension.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public <K> ProvidedIndexExtension<K, Void> findProvidedStubIndex(@Nonnull StubIndexExtension<K, ?> extension) {
  String name = extension.getKey().getName();
  File path = getIndexPath();

  File indexPath = new File(path, StringUtil.toLowerCase(name));
  if (!indexPath.exists()) return null;

  return new ProvidedIndexExtension<K, Void>() {
    @Nonnull
    @Override
    public File getIndexPath() {
      return myIndexFile;
    }

    @Nonnull
    @Override
    public ID<K, Void> getIndexId() {
      return (ID)extension.getKey();
    }

    @Nonnull
    @Override
    public KeyDescriptor<K> createKeyDescriptor() {
      return extension.getKeyDescriptor();
    }

    @Nonnull
    @Override
    public DataExternalizer<Void> createValueExternalizer() {
      return VoidDataExternalizer.INSTANCE;
    }
  };
}
 
Example 29
Project: consulo   File: PsiElement2UsageTargetAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public String getLongDescriptiveName() {
  SearchScope searchScope = myOptions.searchScope;
  String scopeString = searchScope.getDisplayName();
  PsiElement psiElement = getElement();

  return psiElement == null
         ? UsageViewBundle.message("node.invalid")
         : FindBundle.message("recent.find.usages.action.popup", StringUtil.capitalize(UsageViewUtil.getType(psiElement)), DescriptiveNameUtil.getDescriptiveName(psiElement), scopeString);
}
 
Example 30
Project: intellij-pants-plugin   File: ProjectInfo.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> List<Map.Entry<String, T>> getSortedEntries(Map<String, T> map) {
  return ContainerUtil.sorted(
    map.entrySet(),
    new Comparator<Map.Entry<String, T>>() {
      @Override
      public int compare(Map.Entry<String, T> o1, Map.Entry<String, T> o2) {
        return StringUtil.naturalCompare(o1.getKey(), o2.getKey());
      }
    }
  );
}
 
Example 31
Project: flutter-intellij   File: FlutterFramesMonitor.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void onVmServiceReceived(String streamId, Event event) {
  if (StringUtil.equals(streamId, VmService.EXTENSION_STREAM_ID)) {
    if (StringUtil.equals("Flutter.Frame", event.getExtensionKind())) {
      handleFlutterFrame(event);
    }
  }
}
 
Example 32
Project: lombok-intellij-plugin   File: DelombokHandler.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private PsiClass rebuildEnum(@NotNull Project project, @NotNull PsiClass fromClass) {
  final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);

  final PsiClass resultClass = elementFactory.createEnum(StringUtil.defaultIfEmpty(fromClass.getName(), "UnknownClassName"));
  copyModifiers(fromClass.getModifierList(), resultClass.getModifierList());
  rebuildTypeParameter(fromClass, resultClass);

  final List<PsiField> fields = Arrays.asList(fromClass.getFields());

  if (!fields.isEmpty()) {
    final Iterator<PsiField> iterator = fields.iterator();
    PsiElement prev = resultClass.add(rebuildField(project, iterator.next()));
    while (iterator.hasNext()) {
      PsiField curr = iterator.next();
      //guarantees order of enum constants, should match declaration order
      prev = resultClass.addAfter(rebuildField(project, curr), prev);
    }
  }

  for (PsiMethod psiMethod : fromClass.getMethods()) {
    final String psiMethodName = psiMethod.getName();
    //skip Enum virtual methods
    if ("values".equals(psiMethodName) || "valueOf".equals(psiMethodName)) {
      continue;
    }
    resultClass.add(rebuildMethod(project, psiMethod));
  }

  return (PsiClass) CodeStyleManager.getInstance(project).reformat(resultClass);
}
 
Example 33
Project: consulo   File: Task.java    License: Apache License 2.0 5 votes vote down vote up
public Backgroundable(@Nullable Project project,
                      @Nls(capitalization = Nls.Capitalization.Title) @Nonnull String title,
                      boolean canBeCancelled,
                      @Nullable PerformInBackgroundOption backgroundOption) {
  super(project, title, canBeCancelled);
  myBackgroundOption = backgroundOption;
  if (StringUtil.isEmptyOrSpaces(title)) {
    LOG.warn("Empty title for backgroundable task.", new Throwable());
  }
}
 
Example 34
Project: consulo   File: OptionsEditor.java    License: Apache License 2.0 5 votes vote down vote up
public ActionCallback select(Configurable configurable) {
  if (StringUtil.isEmpty(mySearch.getText())) {
    return select(configurable, "");
  }
  else {
    return Promises.toActionCallback(myFilter.refilterFor(mySearch.getText(), true, true));
  }
}
 
Example 35
Project: consulo   File: HighlightInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public String getToolTip() {
  String toolTip = this.toolTip;
  String description = this.description;
  if (toolTip == null || description == null || !toolTip.contains(DESCRIPTION_PLACEHOLDER)) return toolTip;
  String decoded = StringUtil.replace(toolTip, DESCRIPTION_PLACEHOLDER, XmlStringUtil.escapeString(description));
  return XmlStringUtil.wrapInHtml(decoded);
}
 
Example 36
Project: consulo   File: DirDiffTableModel.java    License: Apache License 2.0 5 votes vote down vote up
public void reloadModelSynchronously() {
  myUpdating.set(true);

  try {
    myTree = new DTree(null, "", true);
    mySrc.refresh(true);
    myTrg.refresh(true);
    scan(mySrc, myTree, true);
    scan(myTrg, myTree, false);
  }
  catch (final IOException e) {
    LOG.warn(e);
    reportException(VcsBundle.message("refresh.failed.message", StringUtil.decapitalize(e.getLocalizedMessage())));
  }
  finally {
    myTree.setSource(mySrc);
    myTree.setTarget(myTrg);
    myTree.update(mySettings);

    ArrayList<DirDiffElementImpl> elements = new ArrayList<>();
    fillElements(myTree, elements);
    myElements.clear();
    myElements.addAll(elements);

    myUpdating.set(false);
  }
}
 
Example 37
Project: consulo   File: ExcludedRootElement.java    License: Apache License 2.0 5 votes vote down vote up
public ExcludedRootElement(@Nonnull NodeDescriptor parentDescriptor, String rootUrl, @Nonnull String excludedUrl) {
  super(parentDescriptor);
  myUrl = excludedUrl;
  if (excludedUrl.startsWith(rootUrl)) {
    String relativePath = StringUtil.trimStart(excludedUrl.substring(rootUrl.length()), "/");
    myName = relativePath.isEmpty() ? "<all>" : relativePath;
  }
  else {
    myName = ItemElement.getPresentablePath(excludedUrl);
  }
  myColor = getForegroundColor(VirtualFileManager.getInstance().findFileByUrl(excludedUrl) != null);
  setIcon(AllIcons.Modules.ExcludeRoot);
}
 
Example 38
Project: consulo   File: EditorTextFieldRendererDocument.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setText(@Nonnull CharSequence text) {
  String s = StringUtil.convertLineSeparators(text.toString());
  myChars = new char[s.length()];
  s.getChars(0, s.length(), myChars, 0);
  myString = new String(myChars);
  myLineSet = LineSet.createLineSet(myString);
}
 
Example 39
Project: consulo   File: InvokeTemplateAction.java    License: Apache License 2.0 5 votes vote down vote up
public static String extractMnemonic(String caption, Set<Character> usedMnemonics) {
  if (StringUtil.isEmpty(caption)) return "";

  for (int i = 0; i < caption.length(); i++) {
    char c = caption.charAt(i);
    if (usedMnemonics.add(Character.toUpperCase(c))) {
      return caption.substring(0, i) + UIUtil.MNEMONIC + caption.substring(i);
    }
  }

  return caption + " ";
}
 
Example 40
Project: consulo   File: CompletionProgressIndicator.java    License: Apache License 2.0 5 votes vote down vote up
private void advertiseCtrlArrows() {
  if (!myEditor.isOneLineMode() && FeatureUsageTracker.getInstance().isToBeAdvertisedInLookup(CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ARROWS, getProject())) {
    String downShortcut = CompletionUtil.getActionShortcut(IdeActions.ACTION_LOOKUP_DOWN);
    String upShortcut = CompletionUtil.getActionShortcut(IdeActions.ACTION_LOOKUP_UP);
    if (StringUtil.isNotEmpty(downShortcut) && StringUtil.isNotEmpty(upShortcut)) {
      addAdvertisement(downShortcut + " and " + upShortcut + " will move caret down and up in the editor", null);
    }
  }
}