Java 类com.intellij.openapi.util.Trinity 实例源码

项目:idea-php-class-templates    文件:PhpNewExceptionClassDialog.java   
private List<Trinity> getExceptionTypes() {
    List<Trinity> types = new ArrayList<Trinity>();

    types.add(new Trinity("Exception", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("Error", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("BadFunctionCallException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("BadMethodCallException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("DomainException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("InvalidArgumentException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("LengthException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("LogicException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("OutOfBoundsException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("OutOfRangeException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("OverflowException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("RangeException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("RuntimeException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("UnderflowException", PhpIcons.EXCEPTION, "PHP Exception"));
    types.add(new Trinity("UnexpectedValueException", PhpIcons.EXCEPTION, "PHP Exception"));

    return types;
}
项目:idea-php-class-templates    文件:PhpNewTemplateClassDialog.java   
private List<Trinity> getAvailableTemplates() {
    List<Trinity> templates = new ArrayList<Trinity>();

    FileTemplate classTemplate = FileTemplateManager.getInstance(this.myProject).getInternalTemplate("PHP Class");

    for (FileTemplate template : FileTemplateManager.getInstance(this.myProject).getAllTemplates()) {
        if (template.getExtension().equals("class.php")) {
            templates.add(new Trinity(template.getName(), PhpIcons.CLASS, template));
        }
    }

    if (templates.size() < 1) {
        templates.add(new Trinity(classTemplate.getName(), PhpIcons.CLASS, classTemplate));
    }

    return templates;
}
项目:intellij-ce-playground    文件:TextWithImportsImpl.java   
public TextWithImportsImpl(@NotNull PsiElement expression) {
  myKind = CodeFragmentKind.EXPRESSION;
  final String text = expression.getText();
  PsiFile containingFile = expression.getContainingFile();
  if(containingFile instanceof PsiExpressionCodeFragment) {
    myText = text;
    myImports = ((JavaCodeFragment)containingFile).importsToString();
    myFileType = StdFileTypes.JAVA;
  }
  else {
    Trinity<String, String, FileType> trinity = parseExternalForm(text);
    myText = trinity.first;
    myImports = trinity.second;
    myFileType = trinity.third;
  }
}
项目:intellij-ce-playground    文件:DfaVariableValue.java   
@NotNull
public DfaVariableValue createVariableValue(@NotNull PsiModifierListOwner myVariable,
                                            @Nullable PsiType varType,
                                            boolean isNegated,
                                            @Nullable DfaVariableValue qualifier) {
  Trinity<Boolean,String,DfaVariableValue> key = Trinity.create(isNegated, ((PsiNamedElement)myVariable).getName(), qualifier);
  for (DfaVariableValue aVar : myExistingVars.get(key)) {
    if (aVar.hardEquals(myVariable, varType, isNegated, qualifier)) return aVar;
  }

  DfaVariableValue result = new DfaVariableValue(myVariable, varType, isNegated, myFactory, qualifier);
  myExistingVars.putValue(key, result);
  while (qualifier != null) {
    qualifier.myDependents.add(result);
    qualifier = qualifier.getQualifier();
  }
  return result;
}
项目:intellij-ce-playground    文件:VcsContentAnnotationExceptionFilter.java   
private static List<TextRange> findMethodRange(final ExceptionWorker worker,
                                               final Document document,
                                               final Trinity<PsiClass, PsiFile, String> previousLineResult) {
  return ApplicationManager.getApplication().runReadAction(new Computable<List<TextRange>>() {
    @Override
    public List<TextRange> compute() {
      List<TextRange> ranges = getTextRangeForMethod(worker, previousLineResult);
      if (ranges == null) return null;
      final List<TextRange> result = new ArrayList<TextRange>();
      for (TextRange range : ranges) {
        result.add(new TextRange(document.getLineNumber(range.getStartOffset()),
                                     document.getLineNumber(range.getEndOffset())));
      }
      return result;
    }
  });
}
项目:intellij-ce-playground    文件:VcsContentAnnotationExceptionFilter.java   
@Nullable
private static List<PsiMethod> selectMethod(final PsiMethod[] methods, final Trinity<PsiClass, PsiFile, String> previousLineResult) {
  if (previousLineResult == null || previousLineResult.getThird() == null) return null;

  final List<PsiMethod> result = new SmartList<PsiMethod>();
  for (final PsiMethod method : methods) {
    method.accept(new JavaRecursiveElementVisitor() {
      @Override
      public void visitCallExpression(PsiCallExpression callExpression) {
        final PsiMethod resolved = callExpression.resolveMethod();
        if (resolved != null) {
          if (resolved.getName().equals(previousLineResult.getThird())) {
            result.add(method);
          }
        }
      }
    });
  }

  return result;
}
项目:intellij-ce-playground    文件:AddAnnotationFixTest.java   
private void startListening(@NotNull final List<Trinity<PsiModifierListOwner, String, Boolean>> expectedSequence) {
  myBusConnection = myProject.getMessageBus().connect();
  myBusConnection.subscribe(ExternalAnnotationsManager.TOPIC, new DefaultAnnotationsListener() {
    private int index = 0;

    @Override
    public void afterExternalAnnotationChanging(@NotNull PsiModifierListOwner owner, @NotNull String annotationFQName,
                                                boolean successful) {
      if (index < expectedSequence.size() && expectedSequence.get(index).first == owner
          && expectedSequence.get(index).second.equals(annotationFQName) && expectedSequence.get(index).third == successful) {
        index++;
        myExpectedEventWasProduced = true;
      }
      else {
        super.afterExternalAnnotationChanging(owner, annotationFQName, successful);
      }
    }
  });
}
项目:intellij-ce-playground    文件:RunConfigurableTest.java   
public void testMoveUpDown() {
  doExpand();
  checkPositionToMove(0, 1, null);
  checkPositionToMove(2, 1, Trinity.create(2, 3, BELOW));
  checkPositionToMove(2, -1, null);
  checkPositionToMove(14, 1, null);
  checkPositionToMove(14, -1, null);
  checkPositionToMove(15, -1, null);
  checkPositionToMove(16, -1, null);
  checkPositionToMove(3, -1, Trinity.create(3, 2, ABOVE));
  checkPositionToMove(6, 1, Trinity.create(6, 9, BELOW));
  checkPositionToMove(7, 1, Trinity.create(7, 8, BELOW));
  checkPositionToMove(10, -1, Trinity.create(10, 8, BELOW));
  checkPositionToMove(8, 1, Trinity.create(8, 9, BELOW));
  checkPositionToMove(21, -1, Trinity.create(21, 20, BELOW));
  checkPositionToMove(21, 1, null);
  checkPositionToMove(20, 1, Trinity.create(20, 21, ABOVE));
  checkPositionToMove(20, -1, Trinity.create(20, 19, ABOVE));
  checkPositionToMove(19, 1, Trinity.create(19, 20, BELOW));
  checkPositionToMove(19, -1, Trinity.create(19, 17, BELOW));
  checkPositionToMove(17, -1, Trinity.create(17, 16, ABOVE));
  checkPositionToMove(17, 1, Trinity.create(17, 18, BELOW));
}
项目:intellij-ce-playground    文件:LogModel.java   
public void removeNotification(Notification notification) {
  synchronized (myNotifications) {
    myNotifications.remove(notification);
  }

  Runnable handler = removeHandlers.remove(notification);
  if (handler != null) {
    UIUtil.invokeLaterIfNeeded(handler);
  }

  Trinity<Notification, String, Long> oldStatus = getStatusMessage();
  if (oldStatus != null && notification == oldStatus.first) {
    setStatusToImportant();
  }
  fireModelChanged();
}
项目:intellij-ce-playground    文件:ChangesListView.java   
public void updateModel(List<? extends ChangeList> changeLists, Trinity<List<VirtualFile>, Integer, Integer> unversionedFiles, final List<LocallyDeletedChange> locallyDeletedFiles,
                        List<VirtualFile> modifiedWithoutEditing,
                        MultiMap<String, VirtualFile> switchedFiles,
                        @Nullable Map<VirtualFile, String> switchedRoots,
                        @Nullable List<VirtualFile> ignoredFiles,
                        final List<VirtualFile> lockedFolders,
                        @Nullable final Map<VirtualFile, LogicalLock> logicallyLockedFiles) {
  TreeModelBuilder builder = new TreeModelBuilder(myProject, isShowFlatten());
  final DefaultTreeModel model = builder.buildModel(changeLists, unversionedFiles, locallyDeletedFiles, modifiedWithoutEditing,
                                                    switchedFiles, switchedRoots, ignoredFiles, lockedFolders, logicallyLockedFiles);

  TreeState state = TreeState.createOn(this, (ChangesBrowserNode)getModel().getRoot());
  state.setScrollToSelection(false);
  DefaultTreeModel oldModel = getModel();
  setModel(model);
  setCellRenderer(isShowFlatten() ? myShowFlattenNodeRenderer : myNodeRenderer);
  ChangesBrowserNode root = (ChangesBrowserNode)model.getRoot();
  expandPath(new TreePath(root.getPath()));
  state.applyTo(this, (ChangesBrowserNode)getModel().getRoot());
  expandDefaultChangeList(oldModel, root);
}
项目:intellij-ce-playground    文件:CodeStyleBlankLinesPanel.java   
@Override
public void showCustomOption(Class<? extends CustomCodeStyleSettings> settingsClass,
                             String fieldName,
                             String title,
                             String groupName,
                             @Nullable OptionAnchor anchor,
                             @Nullable String anchorFieldName,
                             Object... options) {
  if (myIsFirstUpdate) {
    myCustomOptions.putValue(groupName, (Trinity)Trinity.create(settingsClass, fieldName, title));
  }

  for (IntOption option : myOptions) {
    if (option.myTarget.getName().equals(fieldName)) {
      option.myTextField.setEnabled(true);
    }
  }
}
项目:intellij-ce-playground    文件:TemplateKindCombo.java   
public TemplateKindCombo() {
  //noinspection unchecked
  getComboBox().setRenderer(new ListCellRendererWrapper() {
    @Override
    public void customize(final JList list, final Object value, final int index, final boolean selected, final boolean cellHasFocus) {
      if (value instanceof Trinity) {
        setText((String)((Trinity)value).first);
        setIcon ((Icon)((Trinity)value).second);
      }
    }
  });

  new ComboboxSpeedSearch(getComboBox()) {
    @Override
    protected String getElementText(Object element) {
      if (element instanceof Trinity) {
        return (String)((Trinity)element).first;
      }
      return null;
    }
  }.setComparator(new SpeedSearchComparator(true));
  setButtonListener(null);
}
项目:intellij-ce-playground    文件:AntRenameProcessor.java   
public void prepareRenaming(PsiElement element, String newName, Map<PsiElement, String> allRenames) {
  final AntDomElement antElement = convertToAntDomElement(element);
  String propName = null;
  if (antElement instanceof AntDomProperty) {
    propName = ((AntDomProperty)antElement).getName().getStringValue();
  }
  else if (antElement instanceof AntDomAntCallParam) {
    propName = ((AntDomAntCallParam)antElement).getName().getStringValue();
  }
  if (propName != null) {
    final AntDomProject contextProject = antElement.getContextAntProject();
    final List<PsiElement> additional = AntCallParamsFinder.resolve(contextProject, propName);
    for (PsiElement psiElement : additional) {
      allRenames.put(psiElement, newName);
    }
    if (antElement instanceof AntDomAntCallParam) {
      final Trinity<PsiElement, Collection<String>, PropertiesProvider> result = PropertyResolver.resolve(contextProject, propName, null);
      if (result.getFirst() != null) {
        allRenames.put(result.getFirst(), newName);
      }
    }
  }
}
项目:intellij-ce-playground    文件:AntDomPropertyReference.java   
@NotNull
public ResolveResult[] resolve(@NotNull AntDomPropertyReference antDomPropertyReference, boolean incompleteCode) {
  final List<ResolveResult> result = new ArrayList<ResolveResult>();
  final AntDomProject project = antDomPropertyReference.myInvocationContextElement.getParentOfType(AntDomProject.class, true);
  if (project != null) {
    final AntDomProject contextAntProject = project.getContextAntProject();
    final String propertyName = antDomPropertyReference.getCanonicalText();
    final Trinity<PsiElement,Collection<String>,PropertiesProvider> resolved = 
      PropertyResolver.resolve(contextAntProject, propertyName, antDomPropertyReference.myInvocationContextElement);
    final PsiElement mainDeclaration = resolved.getFirst();

    if (mainDeclaration != null) {
      result.add(new MyResolveResult(mainDeclaration, resolved.getThird()));
    }

    final List<PsiElement> antCallParams = AntCallParamsFinder.resolve(project, propertyName);
    for (PsiElement param : antCallParams) {
      result.add(new MyResolveResult(param, null));
    }
  }
  return ContainerUtil.toArray(result, new ResolveResult[result.size()]);
}
项目:intellij-ce-playground    文件:MvcModuleStructureSynchronizer.java   
private Set<Trinity<Module, SyncAction, MvcFramework>> computeRawActions(Set<Pair<Object, SyncAction>> actions) {
  //get module by object and kill duplicates
  final Set<Trinity<Module, SyncAction, MvcFramework>> rawActions = new LinkedHashSet<Trinity<Module, SyncAction, MvcFramework>>();
  for (final Pair<Object, SyncAction> pair : actions) {
    for (Module module : determineModuleBySyncActionObject(pair.first)) {
      if (!module.isDisposed()) {
        final MvcFramework framework = (pair.second == SyncAction.CreateAppStructureIfNeeded)
                                       ? MvcFramework.getInstanceBySdk(module)
                                       : MvcFramework.getInstance(module);

        if (framework != null && !framework.isAuxModule(module)) {
          rawActions.add(Trinity.create(module, pair.second, framework));
        }
      }
    }
  }
  return rawActions;
}
项目:intellij-ce-playground    文件:TemporaryPlacesInjector.java   
public void getLanguagesToInject(@NotNull final MultiHostRegistrar registrar, @NotNull final PsiElement context) {
  if (!(context instanceof PsiLanguageInjectionHost) || !((PsiLanguageInjectionHost)context).isValidHost()) return;
  PsiLanguageInjectionHost host = (PsiLanguageInjectionHost)context;

  PsiFile containingFile = context.getContainingFile();
  InjectedLanguage injectedLanguage = myRegistry.getLanguageFor(host, containingFile);
  Language language = injectedLanguage != null ? injectedLanguage.getLanguage() : null;
  if (language == null) return;

  final ElementManipulator<PsiLanguageInjectionHost> manipulator = ElementManipulators.getManipulator(host);
  if (manipulator == null) return;
  List<Trinity<PsiLanguageInjectionHost, InjectedLanguage,TextRange>> trinities =
    Collections.singletonList(Trinity.create(host, injectedLanguage, manipulator.getRangeInElement(host)));
  InjectorUtils.registerInjection(language, trinities, containingFile, registrar);
  InjectorUtils.registerSupport(myRegistry.getLanguageInjectionSupport(), false, registrar);
}
项目:intellij-ce-playground    文件:XmlLanguageInjector.java   
private boolean isInIndex(XmlElement xmlElement) {
  final Trinity<Long, Pattern, Collection<String>> index = getXmlAnnotatedElementsValue();
  if (xmlElement instanceof XmlAttributeValue) xmlElement = (XmlElement)xmlElement.getParent();
  final XmlTag tag;
  if (xmlElement instanceof XmlAttribute) {
    final XmlAttribute attribute = (XmlAttribute)xmlElement;
    if (areThereInjectionsWithText(attribute.getLocalName(), index)) return true;
    if (areThereInjectionsWithText(attribute.getValue(), index)) return true;
    //if (areThereInjectionsWithText(attribute.getNamespace(), index)) return false;
    tag = attribute.getParent();
    if (tag == null) return false;
  }
  else if (xmlElement instanceof XmlTag) {
    tag = (XmlTag)xmlElement;
  }
  else {
    return false;
  }
  if (areThereInjectionsWithText(tag.getLocalName(), index)) return true;
  //if (areThereInjectionsWithText(tag.getNamespace(), index)) return false;
  return false;
}
项目:intellij-ce-playground    文件:XmlLanguageInjector.java   
private Trinity<Long, Pattern, Collection<String>> getXmlAnnotatedElementsValue() {
  Trinity<Long, Pattern, Collection<String>> index = myXmlIndex;
  if (index == null || myConfiguration.getModificationCount() != index.first.longValue()) {
    final Map<ElementPattern<?>, BaseInjection> map = new THashMap<ElementPattern<?>, BaseInjection>();
    for (BaseInjection injection : myConfiguration.getInjections(XmlLanguageInjectionSupport.XML_SUPPORT_ID)) {
      for (InjectionPlace place : injection.getInjectionPlaces()) {
        if (!place.isEnabled() || place.getElementPattern() == null) continue;
        map.put(place.getElementPattern(), injection);
      }
    }
    final Collection<String> stringSet = PatternValuesIndex.buildStringIndex(map.keySet());
    index = Trinity.create(myConfiguration.getModificationCount(), buildPattern(stringSet), stringSet);
    myXmlIndex = index;
  }
  return index;
}
项目:intellij-ce-playground    文件:GdkMethodUtil.java   
/**
 * @return (type[1] in which methods mixed, reference to type[1], type[2] to mixin)
 */
@Nullable
private static Trinity<PsiClassType, GrReferenceExpression, PsiClass> getMixinTypes(final GrStatement statement) {
  if (!(statement instanceof GrMethodCall)) return null;

  return CachedValuesManager.getCachedValue(statement, new CachedValueProvider<Trinity<PsiClassType, GrReferenceExpression, PsiClass>>() {
    @Nullable
    @Override
    public Result<Trinity<PsiClassType, GrReferenceExpression, PsiClass>> compute() {
      GrMethodCall call = (GrMethodCall)statement;

      Pair<PsiClassType, GrReferenceExpression> original = getTypeToMixIn(call);
      if (original == null) return Result.create(null, PsiModificationTracker.MODIFICATION_COUNT);

      PsiClass mix = getTypeToMix(call);
      if (mix == null) return Result.create(null, PsiModificationTracker.MODIFICATION_COUNT);

      return Result.create(new Trinity<PsiClassType, GrReferenceExpression, PsiClass>(original.first, original.second, mix),
                           PsiModificationTracker.MODIFICATION_COUNT);
    }
  });
}
项目:intellij-ce-playground    文件:GrClosureSignatureUtil.java   
@Nullable
public static GrClosureSignature createSignature(GrCall call) {
  if (call instanceof GrMethodCall) {
    final GrExpression invokedExpression = ((GrMethodCall)call).getInvokedExpression();
    final PsiType type = invokedExpression.getType();
    if (type instanceof GrClosureType) {
      final GrSignature signature = ((GrClosureType)type).getSignature();
      final Trinity<GrClosureSignature, ArgInfo<PsiType>[], ApplicabilityResult> trinity =
        getApplicableSignature(signature, PsiUtil.getArgumentTypes(invokedExpression, true), call);
      if (trinity != null) {
        return trinity.first;
      }
      return null;
    }
  }

  final GroovyResolveResult resolveResult = call.advancedResolve();
  final PsiElement element = resolveResult.getElement();
  if (element instanceof PsiMethod) {
    return createSignature((PsiMethod)element, resolveResult.getSubstitutor());
  }

  return null;
}
项目:intellij-ce-playground    文件:GrClosureSignatureUtil.java   
@Override
public Iterator<PsiType> iterator() {
  return new Iterator<PsiType>() {
    private final Iterator<Trinity<GrClosureSignature, ArgInfo<PsiType>[], ApplicabilityResult>> myIterator = results.iterator();

    @Override
    public boolean hasNext() {
      return myIterator.hasNext();
    }

    @Nullable
    @Override
    public PsiType next() {
      return myIterator.next().first.getReturnType();
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }
  };
}
项目:idea-php-class-templates    文件:PhpNewExceptionClassDialog.java   
@Override
protected void subInit() {
    super.subInit();

    this.myMessageTextField = new EditorTextField("");
    this.myKindUpDownHint      = new JLabel();
    this.myKindUpDownHint.setIcon(PlatformIcons.UP_DOWN_ARROWS);
    this.myKindUpDownHint.setToolTipText(PhpBundle.message("actions.new.php.base.arrows.kind.tooltip"));


    this.myKindComboBox = new ComboBox<String>();
    this.myKindComboBox.setMinimumAndPreferredWidth(400);
    this.myKindComboBox.setRenderer(new ListCellRendererWrapper<Trinity>() {
        public void customize(JList list, Trinity value, int index, boolean selected, boolean hasFocus) {
            this.setText((String)value.first);
            this.setIcon((Icon)value.second);
        }
    });
    ComboboxSpeedSearch var10001 = new ComboboxSpeedSearch(this.myKindComboBox) {
        protected String getElementText(Object element) {
            return (String)((Trinity)element).first;
        }
    };
    KeyboardShortcut up = new KeyboardShortcut(KeyStroke.getKeyStroke(38, 0), (KeyStroke)null);
    KeyboardShortcut down = new KeyboardShortcut(KeyStroke.getKeyStroke(40, 0), (KeyStroke)null);
    AnAction kindArrow = PhpNewFileDialog.getCbArrowAction(this.myKindComboBox);
    kindArrow.registerCustomShortcutSet(new CustomShortcutSet(new Shortcut[]{up, down}), this.myNameTextField);
    List<Trinity> exceptionTypes = this.getExceptionTypes();

    for(Trinity type : exceptionTypes) {
        this.myKindComboBox.addItem(type);
    }
}
项目:idea-php-class-templates    文件:PhpNewExceptionClassDialog.java   
@NotNull
public Properties getProperties(@NotNull PsiDirectory directory) {
    super.getProperties(directory);

    this.myProperties.setProperty("EXCEPTION", (String)((Trinity)this.myKindComboBox.getSelectedItem()).getFirst());
    String exceptionMessage = this.myMessageTextField.getText();

    if (StringUtil.isNotEmpty(exceptionMessage)) {
        this.myProperties.setProperty("EXCEPTION_MESSAGE", exceptionMessage);
    }

    return this.myProperties;
}
项目:idea-php-class-templates    文件:PhpNewTemplateClassDialog.java   
private void updateTemplateAttributes() {
    FileTemplate template = (FileTemplate) ((Trinity) this.myKindComboBox.getSelectedItem()).getThird();

    if (template.equals(this.myCurrentTemplate)) {
        return;
    }

    this.myCurrentTemplate = template;
    this.myTemplateAttributes.getPanel().removeAll();
    this.myTemplateAttributesFields.clear();

    String[] attrs = new String[0];
    try {
        attrs = template.getUnsetAttributes(this.getProperties(this.getDirectory()), this.myProject);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    List<String> ignoredAttributes = Arrays.asList("PROJECT_NAME", "FILE_NAME", "NAME", "USER", "DATE", "TIME", "YEAR", "MONTH", "DAY", "HOUR", "MINUTE", "PRODUCT_NAME", "MONTH_NAME_SHORT", "MONTH_NAME_FULL", "NAME", "NAMESPACE", "CLASS_NAME", "STATIC", "TYPE_HINT", "PARAM_DOC", "THROWS_DOC", "DS", "CARET");
    for (String attribute : attrs) {

        if (ignoredAttributes.contains(attribute)) {
            continue;
        }

        EditorTextField field = new EditorTextField();

        this.myTemplateAttributesFields.put(attribute, field);
        this.myTemplateAttributes.addLabeledComponent(attribute.concat(":"), field);
    }

    this.myTemplateAttributes.getPanel().revalidate();
    this.myTemplateAttributes.getPanel().repaint();
}
项目:intellij-ce-playground    文件:TextWithImportsImpl.java   
public TextWithImportsImpl(CodeFragmentKind kind, @NotNull String text) {
  myKind = kind;
  Trinity<String, String, FileType> trinity = parseExternalForm(text);
  myText = trinity.first;
  myImports = trinity.second;
  myFileType = trinity.third;
}
项目:intellij-ce-playground    文件:ExceptionWorker.java   
@Nullable
static Trinity<TextRange, TextRange, TextRange> parseExceptionLine(final String line) {
  int startIdx;
  if (line.startsWith(AT_PREFIX)){
    startIdx = 0;
  }
  else{
    startIdx = line.indexOf(STANDALONE_AT);
    if (startIdx < 0) {
      startIdx = line.indexOf(AT_PREFIX);
    }

    if (startIdx < 0) {
      startIdx = -1;
    }
  }

  int rParenIdx = line.lastIndexOf(')');
  while (rParenIdx > 0 && !Character.isDigit(line.charAt(rParenIdx-1))) {
    rParenIdx = line.lastIndexOf(')', rParenIdx - 1);
  }
  if (rParenIdx < 0) return null;

  final int lParenIdx = line.lastIndexOf('(', rParenIdx);
  if (lParenIdx < 0) return null;

  final int dotIdx = line.lastIndexOf('.', lParenIdx);
  if (dotIdx < 0 || dotIdx < startIdx) return null;

  // class, method, link
  return Trinity.create(new TextRange(startIdx + 1 + (startIdx >= 0 ? AT.length() : 0), handleSpaces(line, dotIdx, -1, true)),
                        new TextRange(handleSpaces(line, dotIdx + 1, 1, true), handleSpaces(line, lParenIdx + 1, -1, true)),
                        new TextRange(lParenIdx, rParenIdx));
}
项目:intellij-ce-playground    文件:VcsContentAnnotationExceptionFilter.java   
private static List<TextRange> getTextRangeForMethod(final ExceptionWorker worker, Trinity<PsiClass, PsiFile, String> previousLineResult) {
  String method = worker.getMethod();
  PsiClass psiClass = worker.getPsiClass();
  PsiMethod[] methods;
  if (method.contains("<init>")) {
    // constructor
    methods = psiClass.getConstructors();
  } else if (method.contains("$")) {
    // access$100
    return null;
  } else {
    methods = psiClass.findMethodsByName(method, false);
  }
  if (methods.length > 0) {
    if (methods.length == 1) {
      final TextRange range = methods[0].getTextRange();
      return Collections.singletonList(range);
    } else {
      List<PsiMethod> selectedMethods = selectMethod(methods, previousLineResult);
      final List<PsiMethod> toIterate = selectedMethods == null ? Arrays.asList(methods) : selectedMethods;
      final List<TextRange> result = new ArrayList<TextRange>();
      for (PsiMethod psiMethod : toIterate) {
        result.add(psiMethod.getTextRange());
      }
      return result;
    }
  }
  return null;
}
项目:intellij-ce-playground    文件:AddAnnotationFixTest.java   
public void testAnnotateLibrary() throws Throwable {

    addDefaultLibrary();
    myFixture.configureByFiles("lib/p/TestPrimitive.java", "content/anno/p/annotations.xml");
    myFixture.configureByFiles("lib/p/Test.java");
    final PsiFile file = myFixture.getFile();
    final Editor editor = myFixture.getEditor();

    final IntentionAction fix = myFixture.findSingleIntention("Annotate method 'get' as @NotNull");
    assertTrue(fix.isAvailable(myProject, editor, file));

    // expecting other @Nullable annotations to be removed, and default @NotNull to be added
    List<Trinity<PsiModifierListOwner, String, Boolean>> expectedSequence = new ArrayList<>();
    for (String notNull : NullableNotNullManager.getInstance(myProject).getNullables()) {
      expectedSequence.add(Trinity.create(getOwner(), notNull, false));
    }
    expectedSequence.add(Trinity.create(getOwner(), AnnotationUtil.NOT_NULL, true));
    startListening(expectedSequence);
    new WriteCommandAction(myProject){
      @Override
      protected void run(@NotNull final Result result) throws Throwable {
        fix.invoke(myProject, editor, file);
      }
    }.execute();

    FileDocumentManager.getInstance().saveAllDocuments();

    final PsiElement psiElement = file.findElementAt(editor.getCaretModel().getOffset());
    assertNotNull(psiElement);
    final PsiModifierListOwner listOwner = PsiTreeUtil.getParentOfType(psiElement, PsiModifierListOwner.class);
    assertNotNull(listOwner);
    assertNotNull(ExternalAnnotationsManager.getInstance(myProject).findExternalAnnotation(listOwner, AnnotationUtil.NOT_NULL));
    stopListeningAndCheckEvents();

    myFixture.checkResultByFile("content/anno/p/annotations.xml", "content/anno/p/annotationsAnnotateLibrary_after.xml", false);
  }
项目:intellij-ce-playground    文件:PackageFileWorker.java   
public static void packageFile(@NotNull VirtualFile file, @NotNull Project project, final Artifact[] artifacts,
                               final boolean packIntoArchives) throws IOException {
  LOG.debug("Start packaging file: " + file.getPath());
  final Collection<Trinity<Artifact, PackagingElementPath, String>> items = ArtifactUtil.findContainingArtifactsWithOutputPaths(file, project, artifacts);
  File ioFile = VfsUtilCore.virtualToIoFile(file);
  for (Trinity<Artifact, PackagingElementPath, String> item : items) {
    final Artifact artifact = item.getFirst();
    final String outputPath = artifact.getOutputPath();
    if (!StringUtil.isEmpty(outputPath)) {
      PackageFileWorker worker = new PackageFileWorker(ioFile, item.getThird(), packIntoArchives);
      LOG.debug(" package to " + outputPath);
      worker.packageFile(outputPath, item.getSecond().getParents());
    }
  }
}
项目:intellij-ce-playground    文件:LogModel.java   
void setStatusMessage(@Nullable Notification statusMessage, long stamp) {
  synchronized (myNotifications) {
    if (myStatusMessage != null && myStatusMessage.first == statusMessage) return;
    if (myStatusMessage == null && statusMessage == null) return;

    myStatusMessage = statusMessage == null ? null : Trinity.create(statusMessage,
                                                                    ObjectUtils.assertNotNull(myStatuses.get(statusMessage)), stamp);
  }
  StatusBar.Info.set("", myProject, EventLog.LOG_REQUESTOR);
}
项目:intellij-ce-playground    文件:LoadTextUtil.java   
@NotNull
public static Charset detectCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] content, @NotNull FileType fileType) {
  Charset charset = null;

  Trinity<Charset,CharsetToolkit.GuessedEncoding, byte[]> guessed = guessFromContent(virtualFile, content, content.length);
  if (guessed != null && guessed.first != null) {
    charset = guessed.first;
  }
  else {
    String charsetName = fileType.getCharset(virtualFile, content);

    if (charsetName == null) {
      Charset specifiedExplicitly = EncodingRegistry.getInstance().getEncoding(virtualFile, true);
      if (specifiedExplicitly != null) {
        charset = specifiedExplicitly;
      }
    }
    else {
      charset = CharsetToolkit.forName(charsetName);
    }
  }

  if (charset == null) {
    charset = EncodingRegistry.getInstance().getDefaultCharset();
  }
  if (fileType.getName().equals("Properties") && EncodingRegistry.getInstance().isNative2Ascii(virtualFile)) {
    charset = Native2AsciiCharset.wrap(charset);
  }
  virtualFile.setCharset(charset);
  return charset;
}
项目:intellij-ce-playground    文件:LoadTextUtil.java   
@Nullable("null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)")
public static Trinity<Charset, CharsetToolkit.GuessedEncoding, byte[]> guessFromContent(@NotNull VirtualFile virtualFile, @NotNull byte[] content, int length) {
  Charset defaultCharset = ObjectUtils.notNull(EncodingManager.getInstance().getEncoding(virtualFile, true), CharsetToolkit.getDefaultSystemCharset());
  CharsetToolkit toolkit = GUESS_UTF ? new CharsetToolkit(content, defaultCharset) : null;
  String detectedFromBytes = null;
  try {
    if (GUESS_UTF) {
      toolkit.setEnforce8Bit(true);
      Charset charset = toolkit.guessFromBOM();
      if (charset != null) {
        detectedFromBytes = AUTO_DETECTED_FROM_BOM;
        byte[] bom = ObjectUtils.notNull(CharsetToolkit.getMandatoryBom(charset), CharsetToolkit.UTF8_BOM);
        return Trinity.create(charset, null, bom);
      }
      CharsetToolkit.GuessedEncoding guessed = toolkit.guessFromContent(length);
      if (guessed == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
        detectedFromBytes = "auto-detected from bytes";
        return Trinity.create(CharsetToolkit.UTF8_CHARSET, guessed, null); //UTF detected, ignore all directives
      }
      if (guessed == CharsetToolkit.GuessedEncoding.SEVEN_BIT) {
        return Trinity.create(null, guessed, null);
      }
    }
    return null;
  }
  finally {
    setCharsetWasDetectedFromBytes(virtualFile, detectedFromBytes);
  }
}
项目:intellij-ce-playground    文件:VirtualFilePointerContainerImpl.java   
@NotNull
private Trinity<String[], VirtualFile[], VirtualFile[]> getOrCache() {
  assert !myDisposed;
  long timeStamp = myTimeStampOfCachedThings;
  Trinity<String[], VirtualFile[], VirtualFile[]> cached = myCachedThings;
  return timeStamp == myVirtualFilePointerManager.getModificationCount() ? cached : cacheThings();
}
项目:intellij-ce-playground    文件:VirtualFilePointerContainerImpl.java   
@NotNull
private Trinity<String[], VirtualFile[], VirtualFile[]> cacheThings() {
  Trinity<String[], VirtualFile[], VirtualFile[]> result;
  if (myList.isEmpty()) {
    result = EMPTY;
  }
  else {
    List<VirtualFile> cachedFiles = new ArrayList<VirtualFile>(myList.size());
    List<String> cachedUrls = new ArrayList<String>(myList.size());
    List<VirtualFile> cachedDirectories = new ArrayList<VirtualFile>(myList.size() / 3);
    boolean allFilesAreDirs = true;
    for (VirtualFilePointer v : myList) {
      VirtualFile file = v.getFile();
      String url = v.getUrl();
      cachedUrls.add(url);
      if (file != null) {
        cachedFiles.add(file);
        if (file.isDirectory()) {
          cachedDirectories.add(file);
        }
        else {
          allFilesAreDirs = false;
        }
      }
    }
    VirtualFile[] directories = VfsUtilCore.toVirtualFileArray(cachedDirectories);
    VirtualFile[] files = allFilesAreDirs ? directories : VfsUtilCore.toVirtualFileArray(cachedFiles);
    String[] urlsArray = ArrayUtil.toStringArray(cachedUrls);
    result = Trinity.create(urlsArray, files, directories);
  }
  myCachedThings = result;
  myTimeStampOfCachedThings = myVirtualFilePointerManager.getModificationCount();
  return result;
}
项目:intellij-ce-playground    文件:StubTreeBuilder.java   
/** Order is deterministic. First element matches {@link FileViewProvider#getStubBindingRoot()} */
@NotNull
public static List<Pair<IStubFileElementType, PsiFile>> getStubbedRoots(@NotNull FileViewProvider viewProvider) {
  final List<Trinity<Language, IStubFileElementType, PsiFile>> roots =
    new SmartList<Trinity<Language, IStubFileElementType, PsiFile>>();
  final PsiFile stubBindingRoot = viewProvider.getStubBindingRoot();
  for (Language language : viewProvider.getLanguages()) {
    final PsiFile file = viewProvider.getPsi(language);
    if (file instanceof PsiFileImpl) {
      final IElementType type = ((PsiFileImpl)file).getElementTypeForStubBuilder();
      if (type != null) {
        roots.add(Trinity.create(language, (IStubFileElementType)type, file));
      }
    }
  }

  ContainerUtil.sort(roots, new Comparator<Trinity<Language, IStubFileElementType, PsiFile>>() {
    @Override
    public int compare(Trinity<Language, IStubFileElementType, PsiFile> o1, Trinity<Language, IStubFileElementType, PsiFile> o2) {
      if (o1.third == stubBindingRoot) return o2.third == stubBindingRoot ? 0 : -1;
      else if (o2.third == stubBindingRoot) return 1;
      else return StringUtil.compare(o1.first.getID(), o2.first.getID(), false);
    }
  });

  return ContainerUtil.map(roots, new Function<Trinity<Language, IStubFileElementType, PsiFile>, Pair<IStubFileElementType, PsiFile>>() {
    @Override
    public Pair<IStubFileElementType, PsiFile> fun(Trinity<Language, IStubFileElementType, PsiFile> trinity) {
      return Pair.create(trinity.second, trinity.third);
    }
  });
}
项目:intellij-ce-playground    文件:BraceMatcherBasedSelectioner.java   
@Override
public List<TextRange> select(final PsiElement e, final CharSequence editorText, final int cursorOffset, final Editor editor) {
  final VirtualFile file = e.getContainingFile().getVirtualFile();
  final FileType fileType = file == null? null : file.getFileType();
  if (fileType == null) return super.select(e, editorText, cursorOffset, editor);
  final int textLength = editorText.length();
  final TextRange totalRange = e.getTextRange();
  final HighlighterIterator iterator = ((EditorEx)editor).getHighlighter().createIterator(totalRange.getStartOffset());
  final BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);

  final ArrayList<TextRange> result = new ArrayList<TextRange>();
  final LinkedList<Trinity<Integer, Integer, IElementType>> stack = new LinkedList<Trinity<Integer, Integer, IElementType>>();
  while (!iterator.atEnd() && iterator.getStart() < totalRange.getEndOffset()) {
    final Trinity<Integer, Integer, IElementType> last;
    if (braceMatcher.isLBraceToken(iterator, editorText, fileType)) {
      stack.addLast(Trinity.create(iterator.getStart(), iterator.getEnd(), iterator.getTokenType()));
    }
    else if (braceMatcher.isRBraceToken(iterator, editorText, fileType)
        && !stack.isEmpty() && braceMatcher.isPairBraces((last = stack.getLast()).third, iterator.getTokenType())) {
      stack.removeLast();
      result.addAll(expandToWholeLine(editorText, new TextRange(last.first, iterator.getEnd())));
      int bodyStart = last.second;
      int bodyEnd = iterator.getStart();
      while (bodyStart < textLength && Character.isWhitespace(editorText.charAt(bodyStart))) bodyStart++;
      while (bodyEnd > 0 && bodyStart < bodyEnd && Character.isWhitespace(editorText.charAt(bodyEnd - 1))) bodyEnd--;
      result.addAll(expandToWholeLine(editorText, new TextRange(bodyStart, bodyEnd)));
    }
    iterator.advance();
  }
  result.add(e.getTextRange());
  return result;
}
项目:intellij-ce-playground    文件:ExecutionManagerImpl.java   
@Override
public void dispose() {
  for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity : myRunningConfigurations) {
    Disposer.dispose(trinity.first);
  }
  myRunningConfigurations.clear();
}
项目:intellij-ce-playground    文件:ExecutionManagerImpl.java   
@NotNull
public List<RunContentDescriptor> getRunningDescriptors(@NotNull Condition<RunnerAndConfigurationSettings> condition) {
  List<RunContentDescriptor> result = new SmartList<RunContentDescriptor>();
  for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity : myRunningConfigurations) {
    if (condition.value(trinity.getSecond())) {
      ProcessHandler processHandler = trinity.getFirst().getProcessHandler();
      if (processHandler != null /*&& !processHandler.isProcessTerminating()*/ && !processHandler.isProcessTerminated()) {
        result.add(trinity.getFirst());
      }
    }
  }
  return result;
}
项目:intellij-ce-playground    文件:ExecutionManagerImpl.java   
@NotNull
public Set<Executor> getExecutors(RunContentDescriptor descriptor) {
  Set<Executor> result = new HashSet<Executor>();
  for (Trinity<RunContentDescriptor, RunnerAndConfigurationSettings, Executor> trinity : myRunningConfigurations) {
    if (descriptor == trinity.first) result.add(trinity.third);
  }
  return result;
}
项目:intellij-ce-playground    文件:PrattBuilderImpl.java   
@Nullable
private TokenParser findParser() {
  final IElementType tokenType = getTokenType();
  for (final Trinity<Integer, PathPattern, TokenParser> trinity : myRegistry.getParsers(tokenType)) {
    if (trinity.first > myPriority && trinity.second.accepts(this)) {
      return trinity.third;
    }
  }
  return null;
}