Java Code Examples for com.intellij.openapi.util.Pair#getFirst()

The following examples show how to use com.intellij.openapi.util.Pair#getFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SymfonyContainerServiceBuilder.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void update(AnActionEvent event) {
    Project project = event.getData(PlatformDataKeys.PROJECT);

    if (project == null || !Symfony2ProjectComponent.isEnabled(project)) {
        this.setStatus(event, false);
        return;
    }

    Pair<PsiFile, PhpClass> pair = findPhpClass(event);
    if(pair == null) {
        return;
    }

    PsiFile psiFile = pair.getFirst();
    if(!(psiFile instanceof YAMLFile) && !(psiFile instanceof XmlFile) && !(psiFile instanceof PhpFile)) {
        this.setStatus(event, false);
    }
}
 
Example 2
Source File: BlamePopup.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
@Nullable
private Pair<? extends CommittedChangeList, FilePath> findAffectedFiles(
    @NotNull CommittedChangesProvider<?, ?> changesProvider) {
  try {
    Pair<? extends CommittedChangeList, FilePath> pair = changesProvider.getOneList(file,
        revisionInfo.getRevisionNumber());
    if (pair != null && pair.getFirst() != null) {
      if (pair.getSecond() != null) {
        pair = Pair.create(pair.getFirst(), VcsUtil.getFilePath(file));
      }
      return pair;
    }
    return null;
  } catch (VcsException e) {
    LOG.warn("Failed to find affected files for path " + file, e);
    return null;
  }
}
 
Example 3
Source File: PomModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private Pair<PomModelAspect, PomTransaction> getBlockingTransaction(final PomModelAspect aspect, PomTransaction transaction) {
  final List<PomModelAspect> allDependants = getAllDependants(aspect);
  for (final PomModelAspect pomModelAspect : allDependants) {
    Stack<Pair<PomModelAspect, PomTransaction>> blockedAspects = myBlockedAspects.get();
    ListIterator<Pair<PomModelAspect, PomTransaction>> blocksIterator = blockedAspects.listIterator(blockedAspects.size());
    while (blocksIterator.hasPrevious()) {
      final Pair<PomModelAspect, PomTransaction> pair = blocksIterator.previous();
      if (pomModelAspect == pair.getFirst() && // aspect dependence
          PsiTreeUtil.isAncestor(getContainingFileByTree(pair.getSecond().getChangeScope()), transaction.getChangeScope(), false) // same file
      ) {
        return pair;
      }
    }
  }
  return null;
}
 
Example 4
Source File: PathMacroTable.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void editMacro() {
  if (getSelectedRowCount() != 1) {
    return;
  }
  final int selectedRow = getSelectedRow();
  final Pair<String, String> pair = myMacros.get(selectedRow);
  final String title = ApplicationBundle.message("title.edit.variable");
  final String macroName = pair.getFirst();
  final PathMacroEditor macroEditor = new PathMacroEditor(title, macroName, pair.getSecond(), new EditValidator());
  macroEditor.show();
  if (macroEditor.isOK()) {
    myMacros.remove(selectedRow);
    myMacros.add(Pair.create(macroEditor.getName(), macroEditor.getValue()));
    Collections.sort(myMacros, MACRO_COMPARATOR);
    myTableModel.fireTableDataChanged();
  }
}
 
Example 5
Source File: RemoteRevisionsNumbersCache.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void plus(final Pair<String, AbstractVcs> pair) {
  // does not support
  if (pair.getSecond().getDiffProvider() == null) return;

  final String key = pair.getFirst();
  final AbstractVcs newVcs = pair.getSecond();

  final VirtualFile root = getRootForPath(key);
  if (root == null) return;

  final VcsRoot vcsRoot = new VcsRoot(newVcs, root);

  synchronized (myLock) {
    final Pair<VcsRoot, VcsRevisionNumber> value = myData.get(key);
    if (value == null) {
      final LazyRefreshingSelfQueue<String> queue = getQueue(vcsRoot);
      myData.put(key, Pair.create(vcsRoot, NOT_LOADED));
      queue.addRequest(key);
    } else if (! value.getFirst().equals(vcsRoot)) {
      switchVcs(value.getFirst(), vcsRoot, key);
    }
  }
}
 
Example 6
Source File: VcsQuickListPopupAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void fillActions(@javax.annotation.Nullable final Project project,
                           @Nonnull final DefaultActionGroup group,
                           @Nonnull final DataContext dataContext) {

  if (project == null) {
    return;
  }

  final Pair<SupportedVCS, AbstractVcs> typeAndVcs = getActiveVCS(project, dataContext);
  final AbstractVcs vcs = typeAndVcs.getSecond();
  final SupportedVCS popupType = typeAndVcs.getFirst();

  switch (popupType) {
    case VCS:
      fillVcsPopup(project, group, dataContext, vcs);
      break;

    case NOT_IN_VCS:
      fillNonInVcsActions(project, group, dataContext);
      break;
  }
}
 
Example 7
Source File: MapBasedTree.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean updateRoot(Pair<? extends N, Boolean> pair) {
  N node = Pair.getFirst(pair);
  if (root == null ? node == null : root.node == node) return false;

  if (root != null) {
    remove(root, keyFunction.apply(root.node));
    root = null;
  }
  if (!map.isEmpty()) {
    map.clear();
    LOG.warn("MapBasedTree: clear lost entries");
  }
  if (node != null) {
    root = new Entry<>(path, null, node, pair.second);
    insert(root, keyFunction.apply(node));
  }
  return true;
}
 
Example 8
Source File: TwigBlockUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Collect every block name by given file name; resolve the "extends" or "embed" scope
 */
@NotNull
public static Collection<PsiElement> getBlockOverwriteTargets(@NotNull PsiElement psiElement) {
    String blockName = psiElement.getText();

    if(StringUtils.isBlank(blockName)) {
        return Collections.emptyList();
    }

    Pair<Collection<PsiFile>, Boolean> scopedFile = TwigUtil.findScopedFile(psiElement);

    Collection<PsiElement> psiElements = new HashSet<>();
    for (PsiFile psiFile : scopedFile.getFirst()) {
        psiElements.addAll(getBlockOverwriteTargets(psiFile, blockName, scopedFile.getSecond()));
    }

    return psiElements;
}
 
Example 9
Source File: MatchPatchPaths.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
private static AbstractFilePatchInProgress processMatch(final FilePatch patch, final VirtualFile file) {
  final String beforeName = patch.getBeforeName();
  final Pair<VirtualFile, Integer> pair = compareNames(beforeName, file);
  if (pair == null) return null;
  final VirtualFile parent = pair.getFirst();
  if (parent == null) return null;
  final AbstractFilePatchInProgress result = createPatchInProgress(patch, parent);
  if (result != null) {
    processStipUp(result, pair.getSecond());
  }
  return result;
}
 
Example 10
Source File: HaxeColorAnnotator.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private static void annotateCompilationExpression(PsiElement node, AnnotationHolder holder) {
  final Set<String> definitions = HaxeProjectSettings.getInstance(node.getProject()).getUserCompilerDefinitionsAsSet();
  final String nodeText = node.getText();
  for (Pair<String, Integer> pair : HaxeStringUtil.getWordsWithOffset(nodeText)) {
    final String word = pair.getFirst();
    final int offset = pair.getSecond();
    final int absoluteOffset = node.getTextOffset() + offset;
    final TextRange range = new TextRange(absoluteOffset, absoluteOffset + word.length());
    final Annotation annotation = holder.createInfoAnnotation(range, null);
    final String attributeName = definitions.contains(word) ? HaxeSyntaxHighlighterColors.HAXE_DEFINED_VAR
                                                            : HaxeSyntaxHighlighterColors.HAXE_UNDEFINED_VAR;
    annotation.setTextAttributes(TextAttributesKey.find(attributeName));
    annotation.registerFix(new HaxeDefineIntention(word, definitions.contains(word)), range);
  }
}
 
Example 11
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
public void assertLocalInspectionContains(String filename, String content, String contains) {
    Set<String> matches = new HashSet<String>();

    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);
    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond()) && result.toString().equals(contains)) {
            return;
        }

        matches.add(result.toString());
    }

    fail(String.format("Fail matches '%s' with one of %s", contains, matches));
}
 
Example 12
Source File: StatusBarProgress.java    From consulo with Apache License 2.0 5 votes vote down vote up
private String updateRestoreText(StatusBar statusBar) {
  Pair<String, String> textsPair = myStatusBar2SavedText.get(statusBar);
  // if current status bar info doesn't match the value, that we set, use this value as a restore value
  String info = ObjectUtil.notNull(statusBar.getInfo(), "");
  if (!textsPair.getSecond().equals(info)) {
    myStatusBar2SavedText.put(statusBar, pair(info, textsPair.second));
  }
  return textsPair.getFirst();
}
 
Example 13
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
public void assertLocalInspectionContainsNotContains(String filename, String content, String contains) {
    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);

    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond()) && result.toString().equals(contains)) {
            fail(String.format("Fail inspection not contains '%s'", contains));
        }
    }
}
 
Example 14
Source File: DrupalLightCodeInsightFixtureTestCase.java    From idea-php-drupal-symfony2-bridge with MIT License 5 votes vote down vote up
public void assertLocalInspectionContains(String filename, String content, String contains) {
    Set<String> matches = new HashSet<String>();

    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);
    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond()) && result.toString().equals(contains)) {
            return;
        }

        matches.add(result.toString());
    }

    fail(String.format("Fail matches '%s' with one of %s", contains, matches));
}
 
Example 15
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-generics-plugin with MIT License 5 votes vote down vote up
public void assertLocalInspectionContainsNotContains(String filename, String content, String contains) {
    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);

    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond())) {
            fail(String.format("Fail inspection not contains '%s'", contains));
        }
    }
}
 
Example 16
Source File: PsiToDocumentSynchronizer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private DocumentChangeTransaction removeTransaction(@Nonnull Document doc) {
  Pair<DocumentChangeTransaction, Integer> pair = myTransactionsMap.get(doc);
  if (pair == null) return null;
  int nestedCount = pair.getSecond().intValue();
  if (nestedCount > 0) {
    pair = Pair.create(pair.getFirst(), nestedCount - 1);
    myTransactionsMap.put(doc, pair);
    return null;
  }
  myTransactionsMap.remove(doc);
  return pair.getFirst();
}
 
Example 17
Source File: TextEditorWithPreview.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public DoublingEventListenerDelegate removeListenerAndGetDelegate(@Nonnull PropertyChangeListener listener) {
  final Pair<Integer, DoublingEventListenerDelegate> oldPair = myMap.get(listener);
  if (oldPair == null) {
    return null;
  }

  if (oldPair.getFirst() == 1) {
    myMap.remove(listener);
  }
  else {
    myMap.put(listener, Pair.create(oldPair.getFirst() - 1, oldPair.getSecond()));
  }
  return oldPair.getSecond();
}
 
Example 18
Source File: CSharpDebuggerProvider.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
public void evaluate(@Nonnull DotNetStackFrameProxy frame,
		@Nonnull DotNetDebugContext debuggerContext,
		@Nonnull DotNetReferenceExpression referenceExpression,
		@Nonnull Set<Object> visitedVariables,
		@Nonnull Consumer<XNamedValue> consumer)
{
	try
	{
		List<Evaluator> evaluators = ApplicationManager.getApplication().runReadAction((Computable<List<Evaluator>>) () ->
		{
			PsiElement resolvedElement = referenceExpression.resolve();
			if(referenceExpression.getParent() instanceof CSharpMethodCallExpressionImpl || resolvedElement instanceof DotNetLikeMethodDeclaration)
			{
				return Collections.emptyList();
			}
			CSharpExpressionEvaluator expressionEvaluator = new CSharpExpressionEvaluator();
			referenceExpression.accept(expressionEvaluator);
			return expressionEvaluator.getEvaluators();
		});

		if(evaluators.isEmpty())
		{
			return;
		}

		CSharpEvaluateContext evaluateContext = new CSharpEvaluateContext(debuggerContext, frame, referenceExpression);
		evaluateContext.evaluate(evaluators);
		Pair<DotNetValueProxy, Object> objectPair = evaluateContext.pop();
		if(objectPair != null && objectPair.getSecond() instanceof DotNetFieldOrPropertyProxy)
		{
			DotNetFieldOrPropertyProxy fieldOrPropertyMirror = (DotNetFieldOrPropertyProxy) objectPair.getSecond();
			if(visitedVariables.contains(fieldOrPropertyMirror))
			{
				return;
			}

			visitedVariables.add(fieldOrPropertyMirror);

			DotNetTypeProxy parent = fieldOrPropertyMirror.getParentType();

			DotNetValueProxy thisObjectValue = ThisObjectEvaluator.calcThisObject(frame, frame.getThisObject());
			DotNetTypeProxy type = thisObjectValue.getType();
			if(thisObjectValue instanceof DotNetObjectValueProxy && parent.equals(type))
			{
				consumer.consume(new DotNetFieldOrPropertyValueNode(debuggerContext, fieldOrPropertyMirror, frame, (DotNetObjectValueProxy) thisObjectValue));
			}
			else if(thisObjectValue instanceof DotNetStructValueProxy && parent.equals(type))
			{
				DotNetStructValueProxy structValueMirror = (DotNetStructValueProxy) thisObjectValue;

				DotNetStructValueInfo valueInfo = new DotNetStructValueInfo(structValueMirror, null, fieldOrPropertyMirror, objectPair.getFirst());

				consumer.consume(new DotNetFieldOrPropertyValueNode(debuggerContext, fieldOrPropertyMirror, frame, null, valueInfo));
			}
			else
			{
				consumer.consume(new CSharpWatcherNode(debuggerContext, ApplicationManager.getApplication().runReadAction((Computable<String>) referenceExpression::getText), frame, objectPair
						.getFirst()));
			}
		}
	}
	catch(Exception e)
	{
		// ignored
	}
}
 
Example 19
Source File: EditorHistoryManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Makes file most recent one
 */
private void fileOpenedImpl(@Nonnull final VirtualFile file, @Nullable final FileEditor fallbackEditor, @Nullable FileEditorProvider fallbackProvider) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  // don't add files that cannot be found via VFM (light & etc.)
  if (VirtualFileManager.getInstance().findFileByUrl(file.getUrl()) == null) return;

  final FileEditorManagerEx editorManager = FileEditorManagerEx.getInstanceEx(myProject);

  final Pair<FileEditor[], FileEditorProvider[]> editorsWithProviders = editorManager.getEditorsWithProviders(file);
  FileEditor[] editors = editorsWithProviders.getFirst();
  FileEditorProvider[] oldProviders = editorsWithProviders.getSecond();
  if (editors.length <= 0 && fallbackEditor != null) {
    editors = new FileEditor[]{fallbackEditor};
  }
  if (oldProviders.length <= 0 && fallbackProvider != null) {
    oldProviders = new FileEditorProvider[]{fallbackProvider};
  }
  if (editors.length <= 0) {
    LOG.error("No editors for file " + file.getPresentableUrl());
  }
  FileEditor selectedEditor = editorManager.getSelectedEditor(file);
  if (selectedEditor == null) {
    selectedEditor = fallbackEditor;
  }
  LOG.assertTrue(selectedEditor != null);
  final int selectedProviderIndex = ArrayUtilRt.find(editors, selectedEditor);
  LOG.assertTrue(selectedProviderIndex != -1, "Can't find " + selectedEditor + " among " + Arrays.asList(editors));

  final HistoryEntry entry = getEntry(file);
  if (entry != null) {
    moveOnTop(entry);
  }
  else {
    final FileEditorState[] states = new FileEditorState[editors.length];
    final FileEditorProvider[] providers = new FileEditorProvider[editors.length];
    for (int i = states.length - 1; i >= 0; i--) {
      final FileEditorProvider provider = oldProviders[i];
      LOG.assertTrue(provider != null);
      FileEditor editor = editors[i];
      if (!editor.isValid()) continue;
      providers[i] = provider;
      states[i] = editor.getState(FileEditorStateLevel.FULL);
    }
    addEntry(HistoryEntry.createHeavy(myProject, file, providers, states, providers[selectedProviderIndex]));
    trimToSize();
  }
}
 
Example 20
Source File: AbstractHaxeNamedComponent.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Override
public ItemPresentation getPresentation() {
  return new ItemPresentation() {
    @Override
    public String getPresentableText() {
      final StringBuilder result = new StringBuilder();
      HaxeBaseMemberModel model = HaxeBaseMemberModel.fromPsi(AbstractHaxeNamedComponent.this);

      if (model == null) {
        result.append(AbstractHaxeNamedComponent.this.getName());
      } else {
        if (isFindUsageRequest()) {
          HaxeClassModel klass = model.getDeclaringClass();
          if (null != klass) {
            result.append(klass.getName());
            result.append('.');
          }
        }

        if (model instanceof HaxeEnumValueModel) {
          return model.getPresentableText(null);
        }

        result.append(model.getName());

        if (model instanceof HaxeMethodModel) {
          final String parameterList = HaxePresentableUtil.getPresentableParameterList(model.getNamedComponentPsi());
          result.append("(").append(parameterList).append(")");
        }

        final ResultHolder resultType = model.getResultType();
        if (resultType != null) {
          result.append(":");
          result.append(model.getResultType().toString());
        }
      }

      return result.toString();
    }

    @Override
    public String getLocationString() {
      HaxeClass haxeClass = AbstractHaxeNamedComponent.this instanceof HaxeClass
                            ? (HaxeClass)AbstractHaxeNamedComponent.this
                            : PsiTreeUtil.getParentOfType(AbstractHaxeNamedComponent.this, HaxeClass.class);
      String path = "";
      if (haxeClass instanceof HaxeAnonymousType) {
        HaxeAnonymousTypeField field = PsiTreeUtil.getParentOfType(haxeClass, HaxeAnonymousTypeField.class);
        while (field != null) {
          boolean addDelimiter = !path.isEmpty();
          path = field.getName() + (addDelimiter ? "." : "") + path;
          field = PsiTreeUtil.getParentOfType(field, HaxeAnonymousTypeField.class);
        }
        final HaxeTypedefDeclaration typedefDeclaration = PsiTreeUtil.getParentOfType(haxeClass, HaxeTypedefDeclaration.class);
        if (typedefDeclaration != null) {
          haxeClass = typedefDeclaration;
        }
      }
      if (haxeClass == null) {
        return "";
      }
      final Pair<String, String> qName = HaxeResolveUtil.splitQName(haxeClass.getQualifiedName());
      if (haxeClass == AbstractHaxeNamedComponent.this) {
        return qName.getFirst();
      }
      return haxeClass.getQualifiedName() + (path.isEmpty() ? "" : "." + path);
    }

    @Override
    public Icon getIcon(boolean open) {
      return AbstractHaxeNamedComponent.this.getIcon(0);
    }


    private boolean isFindUsageRequest() {
      // HACK: Checking the stack is a bad answer for this, but we don't have a good way to
      // determine whether this particular request is from findUsages because all FindUsages queries
      // run on background threads, and they could be running at the same time as another access.
      // (AND, we can't change IDEA's shipping products on which this must run...)
      return HaxeDebugUtil.appearsOnStack(PsiElement2UsageTargetAdapter.class);
    }
  };
}