下面列出了怎么用com.intellij.openapi.util.Couple的API类实例代码及写法,或者点击链接到github查看源代码。
@NotNull
@Override
public Collection<? extends Couple<TextRange>> getCommentRangesToDelete(@NotNull CharSequence text) {
Collection<Couple<TextRange>> ranges = new ArrayList<>();
// should use nearest after all pairs (* *)
int start = getNearest((String) text);
TextRange prefixRange = expandRange(text, start, start + 2);
int end = ((String) text).lastIndexOf("*)");
TextRange suffixRange = expandRange(text, end, end + 2);
ranges.add(Couple.of(prefixRange, suffixRange));
return ranges;
}
private static void collectDescriptorsRecursively(@NotNull ASTNode node,
@NotNull Document document,
@NotNull List<FoldingDescriptor> descriptors) {
final IElementType type = node.getElementType();
if (type == token(COMMENT)
&& spanMultipleLines(node, document)) {
descriptors.add(new FoldingDescriptor(node, node.getTextRange()));
}
if (type == token(LINE_COMMENT)) {
final Couple<PsiElement> commentRange = expandLineCommentsRange(node.getPsi());
final int startOffset = commentRange.getFirst().getTextRange().getStartOffset();
final int endOffset = commentRange.getSecond().getTextRange().getEndOffset();
if (document.getLineNumber(startOffset) != document.getLineNumber(endOffset)) {
descriptors.add(new FoldingDescriptor(node, new TextRange(startOffset, endOffset)));
}
}
if (PROVIDERS.keySet().contains(type)
&& spanMultipleLines(node, document)) {
descriptors.add(new FoldingDescriptor(node, node.getTextRange()));
}
for (ASTNode child : node.getChildren(null)) {
collectDescriptorsRecursively(child, document, descriptors);
}
}
/**
* @return a pair of stdout and stderr.
*/
static Couple<List<String>> executeClientAndGetOutput(
@NotNull Path clientPath,
@Nullable Path workingDirectory,
@NotNull List<String> arguments) throws IOException, InterruptedException {
ourLogger.info("Executing VS client: " + clientPath + ", args: " + StringUtils.join(arguments, ','));
List<String> command = new ArrayList<>(arguments.size() + 1);
command.add(clientPath.toString());
command.addAll(arguments);
Process client = new ProcessBuilder()
.command(command)
.directory(workingDirectory == null ? null : workingDirectory.toFile())
.start();
List<String> output = readLines(client.getInputStream(), "stdout");
List<String> errors = readLines(client.getErrorStream(), "stderr");
int exitCode = client.waitFor();
ourLogger.info("VS client exit code: " + exitCode);
return Couple.of(output, errors);
}
@Nullable
public static Object calcBinary(IElementType elementType, Object p1, Object p2)
{
Couple<Class> key = Couple.<Class>of(p1.getClass(), p2.getClass());
Map<IElementType, PairFunction<Object, Object, Object>> map = ourOperators.get(key);
if(map == null)
{
return null;
}
PairFunction<Object, Object, Object> function = map.get(elementType);
if(function == null)
{
return null;
}
return function.fun(p1, p2);
}
@Nonnull
@Override
@RequiredReadAction
protected UsageInfo[] findUsages()
{
List<UsageInfo> result = new ArrayList<>();
Set<Couple<DotNetNamedElement>> children = CSharpMoveClassesUtil.findTypesAndNamespaces(myDeclaration);
for(Couple<DotNetNamedElement> couple : children)
{
DotNetNamedElement second = couple.getSecond();
for(PsiReference reference : ReferencesSearch.search(second, CSharpClassesMoveProcessor.mapScope(second)))
{
result.add(new CSharpClassesMoveProcessor.MyUsageInfo(reference.getElement(), couple, reference));
}
}
return result.toArray(new UsageInfo[result.size()]);
}
@Override
@RequiredReadAction
public void invoke(@Nonnull Project project, @Nonnull PsiFile psiFile, @Nonnull PsiElement lambdaTemp, @Nonnull PsiElement unused)
{
CSharpLambdaExpressionImpl expression = (CSharpLambdaExpressionImpl) lambdaTemp;
Couple<PsiElement> removingInfo = getRemovingInfo(expression);
if(removingInfo == null)
{
return;
}
PsiElement newBody = removingInfo.getSecond();
PsiElement copied = newBody.copy();
removingInfo.getFirst().replace(copied);
}
@RequiredReadAction
private void notyfyNamespaces()
{
for(PsiElement psiElement : myElementsToMove)
{
if(psiElement instanceof CSharpFile)
{
Set<Couple<DotNetNamedElement>> typesAndNamespaces = CSharpMoveClassesUtil.findTypesAndNamespaces(psiElement);
for(Couple<DotNetNamedElement> couple : typesAndNamespaces)
{
DotNetNamedElement first = couple.getFirst();
if(first instanceof CSharpNamespaceDeclaration)
{
notifyNamespaceChange((CSharpNamespaceDeclaration) first);
}
}
}
}
}
@Nonnull
private static Couple<List<Range>> splitIterable2Side(@Nonnull FairDiffIterable changes, int offset) {
final List<Range> ranges1 = new ArrayList<>();
final List<Range> ranges2 = new ArrayList<>();
for (Range ch : changes.iterateUnchanged()) {
if (ch.end2 <= offset) {
ranges1.add(new Range(ch.start1, ch.end1, ch.start2, ch.end2));
}
else if (ch.start2 >= offset) {
ranges2.add(new Range(ch.start1, ch.end1, ch.start2 - offset, ch.end2 - offset));
}
else {
int len2 = offset - ch.start2;
ranges1.add(new Range(ch.start1, ch.start1 + len2, ch.start2, offset));
ranges2.add(new Range(ch.start1 + len2, ch.end1, 0, ch.end2 - offset));
}
}
return Couple.of(ranges1, ranges2);
}
@RequiredReadAction
public void updateCompileOutputInfoFile() {
Map<String, Couple<String>> map = buildOutputRootsLayout();
Element root = new Element("list");
for (Map.Entry<String, Couple<String>> entry : map.entrySet()) {
Element module = new Element("module");
root.addContent(module);
module.setAttribute("name", entry.getKey());
String first = entry.getValue().getFirst();
if (first != null) module.setAttribute("output-url", first);
String second = entry.getValue().getSecond();
if (second != null) module.setAttribute("test-output-url", second);
}
try {
JDOMUtil.writeDocument(new Document(root), getOutputUrlsFile(), "\n");
}
catch (IOException e) {
LOG.error(e);
}
}
@Nonnull
public Map<String, Couple<String>> getLastOutputRootsLayout() {
File file = getOutputUrlsFile();
Map<String, Couple<String>> map = new HashMap<>();
if (file.exists()) {
try {
Element root = JDOMUtil.load(file);
for (Element module : root.getChildren()) {
String name = module.getAttributeValue("name");
String outputUrl = module.getAttributeValue("output-url");
String testOutputUrl = module.getAttributeValue("test-output-url");
map.put(name, Couple.of(outputUrl, testOutputUrl));
}
}
catch (IOException | JDOMException e) {
LOG.error(e);
}
}
return map;
}
@RequiredReadAction
public Map<String, Couple<String>> buildOutputRootsLayout() {
Map<String, Couple<String>> map = new LinkedHashMap<>();
for (Module module : ModuleManager.getInstance(myProject).getModules()) {
ModuleCompilerPathsManager moduleCompilerPathsManager = ModuleCompilerPathsManager.getInstance(module);
final VirtualFile output = moduleCompilerPathsManager.getCompilerOutput(ProductionContentFolderTypeProvider.getInstance());
final String outputUrl = output == null ? null : output.getUrl();
final VirtualFile testsOutput = moduleCompilerPathsManager.getCompilerOutput(TestContentFolderTypeProvider.getInstance());
final String testoutUrl = testsOutput == null ? null : testsOutput.getUrl();
map.put(module.getName(), Couple.of(outputUrl, testoutUrl));
}
return map;
}
@Override
@Nonnull
@RequiredUIAccess
protected Layout buildRootLayout() {
TwoComponentSplitLayout layout = TwoComponentSplitLayout.create(SplitLayoutPosition.HORIZONTAL);
layout.setProportion(30);
Couple<Component> compoents = createComponents();
layout.setFirstComponent(compoents.getFirst());
DockLayout baseRoot = DockLayout.create();
baseRoot.center(compoents.getSecond());
baseRoot.bottom(buildButtonsLayout());
layout.setSecondComponent(baseRoot);
return layout;
}
@Nonnull
static ReparseResult reparse(@Nonnull final PsiFile file,
@Nonnull FileASTNode oldFileNode,
@Nonnull TextRange changedPsiRange,
@Nonnull final CharSequence newFileText,
@Nonnull final ProgressIndicator indicator,
@Nonnull CharSequence lastCommittedText) {
PsiFileImpl fileImpl = (PsiFileImpl)file;
final Couple<ASTNode> reparseableRoots = findReparseableRoots(fileImpl, oldFileNode, changedPsiRange, newFileText);
if (reparseableRoots == null) {
return makeFullParse(fileImpl, oldFileNode, newFileText, indicator, lastCommittedText);
}
ASTNode oldRoot = reparseableRoots.first;
ASTNode newRoot = reparseableRoots.second;
DiffLog diffLog = mergeTrees(fileImpl, oldRoot, newRoot, indicator, lastCommittedText);
return new ReparseResult(diffLog, oldRoot, newRoot);
}
public static Couple<ASTNode> findTopmostSiblingParents(ASTNode one, ASTNode two) {
if (one == two) return Couple.of(null, null);
LinkedList<ASTNode> oneParents = new LinkedList<>();
while (one != null) {
oneParents.add(one);
one = one.getTreeParent();
}
LinkedList<ASTNode> twoParents = new LinkedList<>();
while (two != null) {
twoParents.add(two);
two = two.getTreeParent();
}
do {
one = oneParents.pollLast();
two = twoParents.pollLast();
}
while (one == two && one != null);
return Couple.of(one, two);
}
@Nullable
private static Couple<Block> getBlockAtOffset(@Nullable Block parent, @Nonnull Block block, int offset) {
TextRange textRange = block.getTextRange();
int startOffset = textRange.getStartOffset();
int endOffset = textRange.getEndOffset();
if (startOffset == offset) {
return Couple.of(parent, block);
}
if (startOffset > offset || endOffset < offset || block.isLeaf()) {
return null;
}
for (Block subBlock : block.getSubBlocks()) {
Couple<Block> result = getBlockAtOffset(block, subBlock, offset);
if (result != null) {
return result;
}
}
return null;
}
public AnnotateActionGroup(@Nonnull List<AnnotationFieldGutter> gutters,
@Nonnull EditorGutterComponentEx gutterComponent,
@javax.annotation.Nullable Couple<Map<VcsRevisionNumber, Color>> bgColorMap) {
super("View", true);
final List<AnAction> actions = new ArrayList<>();
for (AnnotationFieldGutter g : gutters) {
if (g.getID() != null) {
actions.add(new ShowHideAspectAction(g, gutterComponent));
}
}
actions.add(AnSeparator.getInstance());
if (bgColorMap != null) {
actions.add(new ShowAnnotationColorsAction(gutterComponent));
}
actions.add(new ShowShortenNames(gutterComponent));
myActions = actions.toArray(new AnAction[actions.size()]);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
InplaceButton inplaceButton = new InplaceButton(
new IconButton("Click to delete", DeleteContentFolder, DeleteContentFolderRollover),
e -> {
});
Couple<Color> colors = UIUtil.getCellColors(table, isSelected, row, column);
setForeground(colors.getFirst());
setBackground(colors.getSecond());
setEnabled(true);
inplaceButton.setOpaque(false);
return inplaceButton;
}
@RequiredUIAccess
@Nonnull
@Override
public Couple<JComponent> createSplitterComponents(JPanel rootPanel) {
JTextArea area = new JTextArea();
area.setEditable(false);
area.setText(buildAboutInfo());
setOKButtonText(CommonBundle.getCloseButtonText());
JButton okButton = createJButtonForAction(getOKAction());
JPanel eastPanel = new JPanel(new VerticalFlowLayout());
eastPanel.add(okButton);
JButton copyToClipboard = new JButton("Copy to clipboard");
copyToClipboard.addActionListener(e -> {
CopyPasteManager.getInstance().setContents(new TextTransferable(area.getText(), area.getText()));
copyToClipboard.setEnabled(false);
JobScheduler.getScheduler().schedule(() -> UIUtil.invokeLaterIfNeeded(() -> copyToClipboard.setEnabled(true)), 2, TimeUnit.SECONDS);
});
eastPanel.add(copyToClipboard);
return Couple.of(ScrollPaneFactory.createScrollPane(area, true), eastPanel);
}
private static SpacingImpl getSpacingBeforeBlockAtOffset(FormattingModel model, int offset) {
Couple<Block> blockWithParent = getBlockAtOffset(null, model.getRootBlock(), offset);
if (blockWithParent != null) {
Block parentBlock = blockWithParent.first;
Block targetBlock = blockWithParent.second;
if (parentBlock != null && targetBlock != null) {
Block prevBlock = findPreviousSibling(parentBlock, targetBlock);
if (prevBlock != null) return (SpacingImpl)parentBlock.getSpacing(prevBlock, targetBlock);
}
}
return null;
}
@SuppressWarnings("unchecked")
private static <P1, P2> void register(Class<P1> p1Class, Class<P2> p2Class, IElementType elementType, PairFunction<P1, P2, Object> function)
{
Couple<Class> key = Couple.<Class>of(p1Class, p2Class);
Map<IElementType, PairFunction<Object, Object, Object>> map = ourOperators.get(key);
if(map == null)
{
ourOperators.put(key, map = new HashMap<IElementType, PairFunction<Object, Object, Object>>());
}
map.put(elementType, (PairFunction<Object, Object, Object>) function);
}
@RequiredReadAction
private static void pushTypeArgumentsDeep(@Nonnull List<Couple<DotNetTypeResolveResult>> levels,
@Nonnull DotNetGenericParameter[] expressionGenericParameters,
@Nonnull DotNetGenericExtractor expressionExtractor,
@Nonnull DotNetGenericExtractor parameterExtractor)
{
for(DotNetGenericParameter expressionGenericParameter : expressionGenericParameters)
{
ProgressManager.checkCanceled();
DotNetTypeRef expressionTypeRefFromGenericParameter = expressionExtractor.extract(expressionGenericParameter);
DotNetTypeRef parameterTypeRefFromGenericParameter = parameterExtractor.extract(expressionGenericParameter);
if(expressionTypeRefFromGenericParameter == null || parameterTypeRefFromGenericParameter == null)
{
continue;
}
DotNetTypeResolveResult exprTypeResult = expressionTypeRefFromGenericParameter.resolve();
DotNetTypeResolveResult paramTypeResult = parameterTypeRefFromGenericParameter.resolve();
// check is type equal 'Genre<System.String>' to 'Genre<T>'
if(exprTypeResult.getElement() instanceof DotNetTypeDeclaration && exprTypeResult.getElement().isEquivalentTo(paramTypeResult.getElement()))
{
levels.add(Couple.of(exprTypeResult, paramTypeResult));
DotNetGenericParameter[] genericParameters = ((DotNetTypeDeclaration) exprTypeResult.getElement()).getGenericParameters();
pushTypeArgumentsDeep(levels, genericParameters, exprTypeResult.getGenericExtractor(), paramTypeResult.getGenericExtractor());
}
}
}
@RequiredReadAction
@Nullable
private Couple<PsiElement> getRemovingInfo(CSharpLambdaExpressionImpl expression)
{
CSharpCodeBodyProxy codeBlock = expression.getCodeBlock();
PsiElement element = codeBlock.getElement();
if(element instanceof CSharpBlockStatementImpl)
{
DotNetStatement[] statements = ((CSharpBlockStatementImpl) element).getStatements();
if(statements.length == 1)
{
DotNetStatement statement = statements[0];
if(statement instanceof CSharpReturnStatementImpl)
{
DotNetExpression returnExpression = ((CSharpReturnStatementImpl) statement).getExpression();
if(returnExpression == null)
{
return null;
}
return Couple.of(element, returnExpression);
}
else if(statement instanceof CSharpExpressionStatementImpl)
{
DotNetExpression innerExpression = ((CSharpExpressionStatementImpl) statement).getExpression();
return Couple.of(element, innerExpression);
}
}
}
return null;
}
@Override
@Nonnull
@RequiredReadAction
protected UsageInfo[] findUsages()
{
List<UsageInfo> result = new ArrayList<>();
List<Couple<DotNetNamedElement>> children = new ArrayList<>();
for(PsiElement psiElement : myElementsToMove)
{
if(psiElement instanceof CSharpFile)
{
children.addAll(CSharpMoveClassesUtil.findTypesAndNamespaces((CSharpFile) psiElement));
}
}
for(Couple<DotNetNamedElement> couple : children)
{
DotNetNamedElement second = couple.getSecond();
for(PsiReference reference : ReferencesSearch.search(second, mapScope(second)))
{
result.add(new MyUsageInfo(reference.getElement(), couple, reference));
}
}
return result.toArray(new UsageInfo[result.size()]);
}
@Nonnull
private static Couple<FairDiffIterable> comparePunctuation2Side(@Nonnull CharSequence text1,
@Nonnull CharSequence text21,
@Nonnull CharSequence text22,
@Nonnull ProgressIndicator indicator) {
CharSequence text2 = new MergingCharSequence(text21, text22);
FairDiffIterable changes = ByChar.comparePunctuation(text1, text2, indicator);
Couple<List<Range>> ranges = splitIterable2Side(changes, text21.length());
FairDiffIterable iterable1 = fair(createUnchanged(ranges.first, text1.length(), text21.length()));
FairDiffIterable iterable2 = fair(createUnchanged(ranges.second, text1.length(), text22.length()));
return Couple.of(iterable1, iterable2);
}
public static boolean showExitWithoutApplyingChangesDialog(@Nonnull JComponent component,
@Nonnull MergeRequest request,
@Nonnull MergeContext context) {
String message = DiffBundle.message("merge.dialog.exit.without.applying.changes.confirmation.message");
String title = DiffBundle.message("cancel.visual.merge.dialog.title");
Couple<String> customMessage = DiffUtil.getUserData(request, context, DiffUserDataKeysEx.MERGE_CANCEL_MESSAGE);
if (customMessage != null) {
title = customMessage.first;
message = customMessage.second;
}
return Messages.showYesNoDialog(component.getRootPane(), message, title, Messages.getQuestionIcon()) == Messages.YES;
}
private void markOldOutputRoots(final ProjectRef projRef, final Map<String, Couple<String>> currentLayout) {
final int projectId = getProjectId(projRef.get());
Set<VirtualFile> rootsToMark = new HashSet<>();
Map<String, Couple<String>> lastOutputRootsLayout = TranslationCompilerProjectMonitor.getInstance(projRef.get()).getLastOutputRootsLayout();
for (Map.Entry<String, Couple<String>> last : lastOutputRootsLayout.entrySet()) {
Couple<String> current = currentLayout.get(last.getKey());
// module was removed, renamed, etc - remove old source info
if(current == null) {
addIfDirectoryExists(last.getValue().getFirst(), rootsToMark);
addIfDirectoryExists(last.getValue().getSecond(), rootsToMark);
}
else {
String lastOutput = last.getValue().getFirst();
if(lastOutput != null && !lastOutput.equals(current.getFirst())) {
addIfDirectoryExists(lastOutput, rootsToMark);
}
String lastTestOutput = last.getValue().getSecond();
if (lastTestOutput != null && !lastTestOutput.equals(current.getSecond())) {
addIfDirectoryExists(lastTestOutput, rootsToMark);
}
}
}
for (VirtualFile outputRoot : rootsToMark) {
processOldOutputRoot(projectId, outputRoot);
}
}
@javax.annotation.Nullable
public static Couple<String> getBlockPrefixSuffixPair(PsiElement comment) {
final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(comment.getLanguage());
if (commenter != null) {
final String prefix = commenter.getBlockCommentPrefix();
final String suffix = commenter.getBlockCommentSuffix();
if (prefix != null || suffix != null) {
return Couple.of(StringUtil.notNullize(prefix), StringUtil.notNullize(suffix));
}
}
return null;
}
public static boolean isSuppressionComment(@Nonnull PsiElement comment) {
final String prefix = getLineCommentPrefix(comment);
final String commentText = comment.getText();
if (prefix != null) {
return commentText.startsWith(prefix + SUPPRESS_INSPECTIONS_TAG_NAME);
}
final Couple<String> prefixSuffixPair = getBlockPrefixSuffixPair(comment);
return prefixSuffixPair != null
&& commentText.startsWith(prefixSuffixPair.first + SUPPRESS_INSPECTIONS_TAG_NAME)
&& commentText.endsWith(prefixSuffixPair.second);
}
public void viewportSet(JViewport viewport) {
viewport.addChangeListener(e -> {
AbstractTableModel model = getModel();
Couple<Integer> visibleRows = ScrollingUtil.getVisibleRows(this);
model.fireTableChanged(new TableModelEvent(model, visibleRows.first - 1, visibleRows.second, GraphTableModel.ROOT_COLUMN));
});
}
public Selection(@Nonnull VcsLogGraphTable table) {
myTable = table;
List<Integer> selectedRows = ContainerUtil.sorted(Ints.asList(myTable.getSelectedRows()));
Couple<Integer> visibleRows = ScrollingUtil.getVisibleRows(myTable);
myIsOnTop = visibleRows.first - 1 == 0;
VisibleGraph<Integer> graph = myTable.getVisibleGraph();
mySelectedCommits = new TIntHashSet();
Integer visibleSelectedCommit = null;
Integer delta = null;
for (int row : selectedRows) {
if (row < graph.getVisibleCommitCount()) {
Integer commit = graph.getRowInfo(row).getCommit();
mySelectedCommits.add(commit);
if (visibleRows.first - 1 <= row && row <= visibleRows.second && visibleSelectedCommit == null) {
visibleSelectedCommit = commit;
delta = myTable.getCellRect(row, 0, false).y - myTable.getVisibleRect().y;
}
}
}
if (visibleSelectedCommit == null && visibleRows.first - 1 >= 0) {
visibleSelectedCommit = graph.getRowInfo(visibleRows.first - 1).getCommit();
delta = myTable.getCellRect(visibleRows.first - 1, 0, false).y - myTable.getVisibleRect().y;
}
myVisibleSelectedCommit = visibleSelectedCommit;
myDelta = delta;
}