static void logPlugins() {
    List<String> loadedBundled = new ArrayList<String>();
    List<String> disabled = new ArrayList<String>();
    List<String> loadedCustom = new ArrayList<String>();

    for (IdeaPluginDescriptor descriptor : ourPlugins) {
      final String version = descriptor.getVersion();
      String s = descriptor.getName() + (version != null ? " (" + version + ")" : "");
      if (descriptor.isEnabled()) {
        if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName()))
          loadedBundled.add(s);
        else loadedCustom.add(s);
      } else {
        disabled.add(s);
      }
    }

    Collections.sort(loadedBundled);
    Collections.sort(loadedCustom);
    Collections.sort(disabled);

    getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", "));
    if (!loadedCustom.isEmpty()) {
      getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", "));
    }
    if (!disabled.isEmpty()) {
      getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", "));
    }
  }
  public Element getState() {
    final Element element = new Element(COMPONENT_NAME);

    JDOMExternalizerUtil.writeField(
        element, INSTRUMENTATION_TYPE_NAME, myInstrumentationType.toString());
    JDOMExternalizerUtil.writeField(element, LANGUAGE_ANNOTATION_NAME, myLanguageAnnotation);
    JDOMExternalizerUtil.writeField(element, PATTERN_ANNOTATION_NAME, myPatternAnnotation);
    JDOMExternalizerUtil.writeField(element, SUBST_ANNOTATION_NAME, mySubstAnnotation);
    JDOMExternalizerUtil.writeField(
        element, RESOLVE_REFERENCES, String.valueOf(myResolveReferences));

    final List<String> injectorIds = new ArrayList<String>(myInjections.keySet());
    Collections.sort(injectorIds);
    for (String key : injectorIds) {
      final List<BaseInjection> injections = new ArrayList<BaseInjection>(myInjections.get(key));
      if (myDefaultInjections != null) {
        injections.removeAll(myDefaultInjections);
      }
      Collections.sort(
          injections,
          new Comparator<BaseInjection>() {
            public int compare(final BaseInjection o1, final BaseInjection o2) {
              return Comparing.compare(o1.getDisplayName(), o2.getDisplayName());
            }
          });
      for (BaseInjection injection : injections) {
        element.addContent(injection.getState());
      }
    }
    return element;
  }
 private Map<Module, List<VirtualFile>> buildModuleToFilesMap(
     final List<VirtualFile> filesToCompile) {
   if (myChunk.getNodes().size() == 1) {
     return Collections.singletonMap(
         myChunk.getNodes().iterator().next(), Collections.unmodifiableList(filesToCompile));
   }
   return CompilerUtil.buildModuleToFilesMap(myCompileContext, filesToCompile);
 }
Beispiel #4
0
 public static boolean filterEquals(ClassFilter[] filters1, ClassFilter[] filters2) {
   if (filters1.length != filters2.length) {
     return false;
   }
   final Set<ClassFilter> f1 =
       new HashSet<ClassFilter>(Math.max((int) (filters1.length / .75f) + 1, 16));
   final Set<ClassFilter> f2 =
       new HashSet<ClassFilter>(Math.max((int) (filters2.length / .75f) + 1, 16));
   Collections.addAll(f1, filters1);
   Collections.addAll(f2, filters2);
   return f2.equals(f1);
 }
 public boolean replaceInjections(
     List<? extends BaseInjection> newInjections,
     List<? extends BaseInjection> originalInjections,
     boolean forceLevel) {
   if (!forceLevel && !originalInjections.isEmpty()) {
     if (myParentConfiguration.replaceInjections(
         Collections.<BaseInjection>emptyList(), originalInjections, forceLevel)) {
       myParentConfiguration.replaceInjections(
           newInjections, Collections.<BaseInjection>emptyList(), forceLevel);
       return true;
     }
   }
   return super.replaceInjections(newInjections, originalInjections, forceLevel);
 }
  @NotNull
  public List<Pair<TaskInfo, ProgressIndicator>> getBackgroundProcesses() {
    synchronized (myOriginals) {
      if (myOriginals.isEmpty()) return Collections.emptyList();

      List<Pair<TaskInfo, ProgressIndicator>> result =
          new ArrayList<Pair<TaskInfo, ProgressIndicator>>(myOriginals.size());
      for (int i = 0; i < myOriginals.size(); i++) {
        result.add(Pair.<TaskInfo, ProgressIndicator>create(myInfos.get(i), myOriginals.get(i)));
      }

      return Collections.unmodifiableList(result);
    }
  }
  @Override
  public void after(@NotNull final List<? extends VFileEvent> events) {
    incModificationCount();

    for (FilePointerPartNode node : myPointersToUpdateUrl) {
      synchronized (this) {
        VirtualFilePointerImpl pointer = node.leaf;
        String urlBefore = pointer.getUrlNoUpdate();
        Pair<VirtualFile, String> after = node.update();
        String urlAfter = after.second;
        if (URL_COMPARATOR.compare(urlBefore, urlAfter) != 0) {
          // url has changed, reinsert
          FilePointerPartNode root = myPointers.get(pointer.getListener());
          int useCount = node.useCount;
          node.remove();
          FilePointerPartNode newNode =
              root.findPointerOrCreate(VfsUtilCore.urlToPath(urlAfter), 0, after);
          VirtualFilePointerImpl existingPointer = newNode.leaf;
          if (existingPointer != null) {
            // can happen when e.g. file renamed to the existing file
            // merge two pointers
            pointer.myNode = newNode;
          } else {
            newNode.associate(pointer, after);
          }
          newNode.incrementUsageCount(useCount);
        }
      }
    }

    VirtualFilePointer[] pointersToFireArray = toPointers(myPointersToFire);
    for (VirtualFilePointer pointer : pointersToFireArray) {
      ((VirtualFilePointerImpl) pointer).myNode.update();
    }

    for (EventDescriptor event : myEvents) {
      event.fireAfter();
    }

    if (pointersToFireArray.length != 0) {
      myBus.syncPublisher(VirtualFilePointerListener.TOPIC).validityChanged(pointersToFireArray);
    }

    myPointersToUpdateUrl = Collections.emptyList();
    myEvents = Collections.emptyList();
    myPointersToFire = Collections.emptyList();
    for (FilePointerPartNode root : myPointers.values()) {
      root.checkConsistency();
    }
  }
  public List<HighlightInfo> runMainPasses(
      @NotNull PsiFile psiFile,
      @NotNull Document document,
      @NotNull final ProgressIndicator progress) {
    final List<HighlightInfo> result = new ArrayList<HighlightInfo>();
    final VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile != null && !virtualFile.getFileType().isBinary()) {

      final List<TextEditorHighlightingPass> passes =
          TextEditorHighlightingPassRegistrarEx.getInstanceEx(myProject)
              .instantiateMainPasses(psiFile, document);

      Collections.sort(
          passes,
          new Comparator<TextEditorHighlightingPass>() {
            @Override
            public int compare(TextEditorHighlightingPass o1, TextEditorHighlightingPass o2) {
              if (o1 instanceof GeneralHighlightingPass) return -1;
              if (o2 instanceof GeneralHighlightingPass) return 1;
              return 0;
            }
          });

      for (TextEditorHighlightingPass pass : passes) {
        pass.doCollectInformation(progress);
        result.addAll(pass.getInfos());
      }
    }

    return result;
  }
  @Override
  public List<String> getInvalidRootUrls(OrderRootType type) {
    if (myDisposed) return Collections.emptyList();

    final List<VirtualFilePointer> pointers = myRoots.get(type).getList();
    List<String> invalidPaths = null;
    for (VirtualFilePointer pointer : pointers) {
      if (!pointer.isValid()) {
        if (invalidPaths == null) {
          invalidPaths = new SmartList<String>();
        }
        invalidPaths.add(pointer.getUrl());
      }
    }
    return invalidPaths == null ? Collections.<String>emptyList() : invalidPaths;
  }
 @NotNull
 private static List<PsiMethod> findMethodsBySignature(
     @NotNull PsiClass aClass,
     @NotNull PsiMethod patternMethod,
     boolean checkBases,
     boolean stopOnFirst) {
   final PsiMethod[] methodsByName = aClass.findMethodsByName(patternMethod.getName(), checkBases);
   if (methodsByName.length == 0) return Collections.emptyList();
   final List<PsiMethod> methods = new SmartList<PsiMethod>();
   final MethodSignature patternSignature = patternMethod.getSignature(PsiSubstitutor.EMPTY);
   for (final PsiMethod method : methodsByName) {
     final PsiClass superClass = method.getContainingClass();
     final PsiSubstitutor substitutor;
     if (checkBases && !aClass.equals(superClass)) {
       substitutor =
           TypeConversionUtil.getSuperClassSubstitutor(superClass, aClass, PsiSubstitutor.EMPTY);
     } else {
       substitutor = PsiSubstitutor.EMPTY;
     }
     final MethodSignature signature = method.getSignature(substitutor);
     if (signature.equals(patternSignature)) {
       methods.add(method);
       if (stopOnFirst) {
         break;
       }
     }
   }
   return methods;
 }
 public String[] knownNamespaces() {
   final PsiElement parentElement = getParent();
   BidirectionalMap<String, String> map = initNamespaceMaps(parentElement);
   Set<String> known = Collections.emptySet();
   if (map != null) {
     known = new HashSet<String>(map.values());
   }
   if (parentElement instanceof XmlTag) {
     if (known.isEmpty()) return ((XmlTag) parentElement).knownNamespaces();
     ContainerUtil.addAll(known, ((XmlTag) parentElement).knownNamespaces());
   } else {
     XmlExtension xmlExtension = XmlExtension.getExtensionByElement(this);
     if (xmlExtension != null) {
       final XmlFile xmlFile = xmlExtension.getContainingFile(this);
       if (xmlFile != null) {
         final XmlTag rootTag = xmlFile.getRootTag();
         if (rootTag != null && rootTag != this) {
           if (known.isEmpty()) return rootTag.knownNamespaces();
           ContainerUtil.addAll(known, rootTag.knownNamespaces());
         }
       }
     }
   }
   return ArrayUtil.toStringArray(known);
 }
  public PostprocessReformattingAspect(
      Project project, PsiManager psiManager, TreeAspect treeAspect) {
    myProject = project;
    myPsiManager = psiManager;
    myTreeAspect = treeAspect;
    PomManager.getModel(psiManager.getProject())
        .registerAspect(
            PostprocessReformattingAspect.class,
            this,
            Collections.singleton((PomModelAspect) treeAspect));

    ApplicationListener applicationListener =
        new ApplicationAdapter() {
          public void writeActionStarted(final Object action) {
            final CommandProcessor processor = CommandProcessor.getInstance();
            if (processor != null) {
              final Project project = processor.getCurrentCommandProject();
              if (project == myProject) {
                myPostponedCounter++;
              }
            }
          }

          public void writeActionFinished(final Object action) {
            final CommandProcessor processor = CommandProcessor.getInstance();
            if (processor != null) {
              final Project project = processor.getCurrentCommandProject();
              if (project == myProject) {
                decrementPostponedCounter();
              }
            }
          }
        };
    ApplicationManager.getApplication().addApplicationListener(applicationListener, this);
  }
 /**
  * intersection may spread over several injected fragments
  *
  * @param rangeToEdit range in encoded(raw) PSI
  * @return list of ranges in encoded (raw) PSI
  */
 @Override
 @SuppressWarnings({"ConstantConditions", "unchecked"})
 @NotNull
 public List<TextRange> intersectWithAllEditableFragments(
     @NotNull PsiFile injectedPsi, @NotNull TextRange rangeToEdit) {
   Place shreds = InjectedLanguageUtil.getShreds(injectedPsi);
   if (shreds == null) return Collections.emptyList();
   Object result = null; // optimization: TextRange or ArrayList
   int count = 0;
   int offset = 0;
   for (PsiLanguageInjectionHost.Shred shred : shreds) {
     TextRange encodedRange =
         TextRange.from(
             offset + shred.getPrefix().length(), shred.getRangeInsideHost().getLength());
     TextRange intersection = encodedRange.intersection(rangeToEdit);
     if (intersection != null) {
       count++;
       if (count == 1) {
         result = intersection;
       } else if (count == 2) {
         TextRange range = (TextRange) result;
         if (range.isEmpty()) {
           result = intersection;
           count = 1;
         } else if (intersection.isEmpty()) {
           count = 1;
         } else {
           List<TextRange> list = new ArrayList<TextRange>();
           list.add(range);
           list.add(intersection);
           result = list;
         }
       } else if (intersection.isEmpty()) {
         count--;
       } else {
         ((List<TextRange>) result).add(intersection);
       }
     }
     offset +=
         shred.getPrefix().length()
             + shred.getRangeInsideHost().getLength()
             + shred.getSuffix().length();
   }
   return count == 0
       ? Collections.<TextRange>emptyList()
       : count == 1 ? Collections.singletonList((TextRange) result) : (List<TextRange>) result;
 }
 @Nullable
 public static List<? extends PsiElement> getAllPsiElements(final LookupElement item) {
   List<PsiMethod> allMethods = getAllMethods(item);
   if (allMethods != null) return allMethods;
   if (item.getObject() instanceof PsiElement)
     return Collections.singletonList((PsiElement) item.getObject());
   return null;
 }
 public Collection<String> getAdditionalAnnotations() {
   List<String> annos = ADDITIONAL_ANNOS;
   if (annos == null) {
     annos = new ArrayList<String>();
     Collections.addAll(annos, STANDARD_ANNOS);
     final EntryPoint[] extensions =
         Extensions.getExtensions(ExtensionPoints.DEAD_CODE_TOOL, null);
     for (EntryPoint extension : extensions) {
       final String[] ignoredAnnotations = extension.getIgnoreAnnotations();
       if (ignoredAnnotations != null) {
         ContainerUtil.addAll(annos, ignoredAnnotations);
       }
     }
     ADDITIONAL_ANNOS = annos = Collections.unmodifiableList(annos);
   }
   return annos;
 }
 @Override
 public VirtualFile[] getAllVersionedRoots() {
   List<VirtualFile> vFiles = new ArrayList<VirtualFile>();
   final AbstractVcs[] vcses = myMappings.getActiveVcses();
   for (AbstractVcs vcs : vcses) {
     Collections.addAll(vFiles, getRootsUnderVcs(vcs));
   }
   return VfsUtilCore.toVirtualFileArray(vFiles);
 }
  public static String composeText(
      final Map<String, ExpectedHighlightingSet> types,
      Collection<HighlightInfo> infos,
      String text) {
    // filter highlighting data and map each highlighting to a tag name
    List<Pair<String, HighlightInfo>> list =
        ContainerUtil.mapNotNull(
            infos,
            new NullableFunction<HighlightInfo, Pair<String, HighlightInfo>>() {
              @Override
              public Pair<String, HighlightInfo> fun(HighlightInfo info) {
                for (Map.Entry<String, ExpectedHighlightingSet> entry : types.entrySet()) {
                  final ExpectedHighlightingSet set = entry.getValue();
                  if (set.enabled
                      && set.severity == info.getSeverity()
                      && set.endOfLine == info.isAfterEndOfLine()) {
                    return Pair.create(entry.getKey(), info);
                  }
                }
                return null;
              }
            });

    // sort filtered highlighting data by end offset in descending order
    Collections.sort(
        list,
        new Comparator<Pair<String, HighlightInfo>>() {
          @Override
          public int compare(Pair<String, HighlightInfo> o1, Pair<String, HighlightInfo> o2) {
            HighlightInfo i1 = o1.second;
            HighlightInfo i2 = o2.second;

            int byEnds = i2.endOffset - i1.endOffset;
            if (byEnds != 0) return byEnds;

            if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) {
              int byStarts = i1.startOffset - i2.startOffset;
              if (byStarts != 0) return byStarts;
            } else {
              int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine());
              if (byEOL != 0) return byEOL;
            }

            int bySeverity = i2.getSeverity().compareTo(i1.getSeverity());
            if (bySeverity != 0) return bySeverity;

            return Comparing.compare(i1.getDescription(), i2.getDescription());
          }
        });

    // combine highlighting data with original text
    StringBuilder sb = new StringBuilder();
    Couple<Integer> result = composeText(sb, list, 0, text, text.length(), 0);
    sb.insert(0, text.substring(0, result.second));
    return sb.toString();
  }
 @NotNull
 public static List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(
     @NotNull PsiClass psiClass, String name, boolean checkBases) {
   if (!checkBases) {
     final PsiMethod[] methodsByName = psiClass.findMethodsByName(name, false);
     final List<Pair<PsiMethod, PsiSubstitutor>> ret =
         new ArrayList<Pair<PsiMethod, PsiSubstitutor>>(methodsByName.length);
     for (final PsiMethod method : methodsByName) {
       ret.add(new Pair<PsiMethod, PsiSubstitutor>(method, PsiSubstitutor.EMPTY));
     }
     return ret;
   }
   Map<String, List<Pair<PsiMember, PsiSubstitutor>>> map = getMap(psiClass, MemberType.METHOD);
   @SuppressWarnings("unchecked")
   List<Pair<PsiMethod, PsiSubstitutor>> list = (List) map.get(name);
   return list == null
       ? Collections.<Pair<PsiMethod, PsiSubstitutor>>emptyList()
       : Collections.unmodifiableList(list);
 }
 // TODO<rv> Remove the next two methods as a temporary solution. Sort in OrderRootType.
 //
 public static List<OrderRootType> sortRootTypes(Collection<OrderRootType> rootTypes) {
   List<OrderRootType> allTypes = new ArrayList<OrderRootType>(rootTypes);
   Collections.sort(
       allTypes,
       new Comparator<OrderRootType>() {
         @Override
         public int compare(final OrderRootType o1, final OrderRootType o2) {
           return getSortKey(o1).compareTo(getSortKey(o2));
         }
       });
   return allTypes;
 }
Beispiel #20
0
  @NotNull
  public static List<Pair<Breakpoint, Event>> getEventDescriptors(
      SuspendContextImpl suspendContext) {
    DebuggerManagerThreadImpl.assertIsManagerThread();
    if (suspendContext == null) {
      return Collections.emptyList();
    }
    final EventSet events = suspendContext.getEventSet();
    if (events == null) {
      return Collections.emptyList();
    }
    final List<Pair<Breakpoint, Event>> eventDescriptors = new SmartList<Pair<Breakpoint, Event>>();

    final RequestManagerImpl requestManager = suspendContext.getDebugProcess().getRequestsManager();
    for (final Event event : events) {
      final Requestor requestor = requestManager.findRequestor(event.request());
      if (requestor instanceof Breakpoint) {
        eventDescriptors.add(Pair.create((Breakpoint) requestor, event));
      }
    }
    return eventDescriptors;
  }
  private static List<? extends LookupElement> createLookupElements(
      CompletionElement completionElement, PsiJavaReference reference) {
    Object completion = completionElement.getElement();
    assert !(completion instanceof LookupElement);

    if (reference instanceof PsiJavaCodeReferenceElement) {
      if (completion instanceof PsiMethod
          && ((PsiJavaCodeReferenceElement) reference).getParent()
              instanceof PsiImportStaticStatement) {
        return Collections.singletonList(
            JavaLookupElementBuilder.forMethod((PsiMethod) completion, PsiSubstitutor.EMPTY));
      }

      if (completion instanceof PsiClass) {
        return JavaClassNameCompletionContributor.createClassLookupItems(
            (PsiClass) completion,
            JavaClassNameCompletionContributor.AFTER_NEW.accepts(reference),
            JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER,
            Conditions.<PsiClass>alwaysTrue());
      }
    }

    if (reference instanceof PsiMethodReferenceExpression
        && completion instanceof PsiMethod
        && ((PsiMethod) completion).isConstructor()) {
      return Collections.singletonList(
          JavaLookupElementBuilder.forMethod(
              (PsiMethod) completion, "new", PsiSubstitutor.EMPTY, null));
    }

    LookupElement _ret = LookupItemUtil.objectToLookupItem(completion);
    if (_ret instanceof LookupItem) {
      final PsiSubstitutor substitutor = completionElement.getSubstitutor();
      if (substitutor != null) {
        ((LookupItem<?>) _ret).setAttribute(LookupItem.SUBSTITUTOR, substitutor);
      }
    }
    return Collections.singletonList(_ret);
  }
 ObjectWithWeight(Object element, String pattern, SpeedSearchComparator comparator) {
   this.node = element;
   final String text = getElementText(element);
   if (text != null) {
     final Iterable<TextRange> ranges = comparator.matchingFragments(pattern, text);
     if (ranges != null) {
       for (TextRange range : ranges) {
         weights.add(range);
       }
     }
   }
   Collections.sort(weights, TEXT_RANGE_COMPARATOR);
 }
  @Override
  public void writeExternal(Element element) throws WriteExternalException {
    final CodeStyleSettings parentSettings = new CodeStyleSettings();
    DefaultJDOMExternalizer.writeExternal(
        this, element, new DifferenceFilter<CodeStyleSettings>(this, parentSettings));
    List<CustomCodeStyleSettings> customSettings =
        new ArrayList<CustomCodeStyleSettings>(getCustomSettingsValues());

    Collections.sort(
        customSettings,
        new Comparator<CustomCodeStyleSettings>() {
          @Override
          public int compare(final CustomCodeStyleSettings o1, final CustomCodeStyleSettings o2) {
            return o1.getTagName().compareTo(o2.getTagName());
          }
        });

    for (final CustomCodeStyleSettings settings : customSettings) {
      final CustomCodeStyleSettings parentCustomSettings =
          parentSettings.getCustomSettings(settings.getClass());
      if (parentCustomSettings == null) {
        throw new WriteExternalException("Custom settings are null for " + settings.getClass());
      }
      settings.writeExternal(element, parentCustomSettings);
    }

    final FileType[] fileTypes =
        myAdditionalIndentOptions
            .keySet()
            .toArray(new FileType[myAdditionalIndentOptions.keySet().size()]);
    Arrays.sort(
        fileTypes,
        new Comparator<FileType>() {
          @Override
          public int compare(final FileType o1, final FileType o2) {
            return o1.getDefaultExtension().compareTo(o2.getDefaultExtension());
          }
        });

    for (FileType fileType : fileTypes) {
      final IndentOptions indentOptions = myAdditionalIndentOptions.get(fileType);
      Element additionalIndentOptions = new Element(ADDITIONAL_INDENT_OPTIONS);
      indentOptions.serialize(additionalIndentOptions, getDefaultIndentOptions(fileType));
      additionalIndentOptions.setAttribute(FILETYPE, fileType.getDefaultExtension());
      if (!additionalIndentOptions.getChildren().isEmpty()) {
        element.addContent(additionalIndentOptions);
      }
    }

    myCommonSettingsManager.writeExternal(element);
  }
  @NotNull
  private static List<PsiMember> findByMap(
      @NotNull PsiClass aClass, String name, boolean checkBases, @NotNull MemberType type) {
    if (name == null) return Collections.emptyList();

    if (checkBases) {
      Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allMethodsMap = getMap(aClass, type);
      List<Pair<PsiMember, PsiSubstitutor>> list = allMethodsMap.get(name);
      if (list == null) return Collections.emptyList();
      List<PsiMember> ret = new ArrayList<PsiMember>(list.size());
      for (final Pair<PsiMember, PsiSubstitutor> info : list) {
        ret.add(info.getFirst());
      }

      return ret;
    } else {
      PsiMember[] members = null;
      switch (type) {
        case METHOD:
          members = aClass.getMethods();
          break;
        case CLASS:
          members = aClass.getInnerClasses();
          break;
        case FIELD:
          members = aClass.getFields();
          break;
      }

      List<PsiMember> list = new ArrayList<PsiMember>();
      for (PsiMember member : members) {
        if (name.equals(member.getName())) {
          list.add(member);
        }
      }
      return list;
    }
  }
 private static void sortInjections(final List<BaseInjection> injections) {
   Collections.sort(
       injections,
       new Comparator<BaseInjection>() {
         public int compare(final BaseInjection o1, final BaseInjection o2) {
           final int support = Comparing.compare(o1.getSupportId(), o2.getSupportId());
           if (support != 0) return support;
           final int lang =
               Comparing.compare(o1.getInjectedLanguageId(), o2.getInjectedLanguageId());
           if (lang != 0) return lang;
           return Comparing.compare(o1.getDisplayName(), o2.getDisplayName());
         }
       });
 }
    @Nullable
    private Object findClosestTo(PsiElement path, ArrayList<ObjectWithWeight> paths) {
      if (path == null || myInitialPsiElement == null) {
        return paths.get(0).node;
      }
      final Set<PsiElement> parents = getAllParents(myInitialPsiElement);
      ArrayList<ObjectWithWeight> cur = new ArrayList<ObjectWithWeight>();
      int max = -1;
      for (ObjectWithWeight p : paths) {
        final Object last = ((TreePath) p.node).getLastPathComponent();
        final List<PsiElement> elements = new ArrayList<PsiElement>();
        final Object object = ((DefaultMutableTreeNode) last).getUserObject();
        if (object instanceof FilteringTreeStructure.FilteringNode) {
          FilteringTreeStructure.FilteringNode node = (FilteringTreeStructure.FilteringNode) object;
          FilteringTreeStructure.FilteringNode candidate = node;

          while (node != null) {
            elements.add(getPsi(node));
            node = node.getParentNode();
          }
          final int size = ContainerUtil.intersection(parents, elements).size();
          if (size == elements.size() - 1
              && size == parents.size() - (myInitialNodeIsLeaf ? 1 : 0)
              && candidate.children().isEmpty()) {
            return p.node;
          }
          if (size > max) {
            max = size;
            cur.clear();
            cur.add(p);
          } else if (size == max) {
            cur.add(p);
          }
        }
      }

      Collections.sort(
          cur,
          new Comparator<ObjectWithWeight>() {
            @Override
            public int compare(ObjectWithWeight o1, ObjectWithWeight o2) {
              final int i = o1.compareWith(o2);
              return i != 0
                  ? i
                  : ((TreePath) o2.node).getPathCount() - ((TreePath) o1.node).getPathCount();
            }
          });
      return cur.isEmpty() ? null : cur.get(0).node;
    }
  @Nullable
  @SuppressWarnings({"HardCodedStringLiteral"})
  private JPanel readExternalPanel(
      final Element element, @Nullable JPanel panel, Ref<EditorWindow> currentWindow) {
    final Element splitterElement = element.getChild("splitter");
    if (splitterElement != null) {
      return readSplitter(panel, splitterElement, currentWindow);
    }

    final Element leaf = element.getChild("leaf");
    if (leaf == null) {
      return null;
    }

    EditorWindow window = (panel == null) ? new EditorWindow(this) : findWindowWith(panel);
    LOG.assertTrue(window != null);

    @SuppressWarnings("unchecked")
    final List<Element> children = ContainerUtil.newArrayList(leaf.getChildren("file"));
    if (UISettings.getInstance().ACTIVATE_RIGHT_EDITOR_ON_CLOSE) {
      Collections.reverse(children);
    }

    VirtualFile currentFile = null;
    for (final Element file : children) {
      try {
        final HistoryEntry entry =
            new HistoryEntry(getManager().getProject(), file.getChild(HistoryEntry.TAG), true);
        boolean isCurrent = Boolean.valueOf(file.getAttributeValue("current")).booleanValue();
        getManager().openFileImpl3(window, entry.myFile, false, entry, isCurrent);
        if (getManager().isFileOpen(entry.myFile)) {
          window.setFilePinned(
              entry.myFile, Boolean.valueOf(file.getAttributeValue("pinned")).booleanValue());
          if (Boolean.valueOf(file.getAttributeValue("current-in-tab")).booleanValue()) {
            currentFile = entry.myFile;
          }
        }
      } catch (InvalidDataException e) {
        // OK
      }
    }
    if (currentFile != null) {
      final EditorComposite editor = window.findFileComposite(currentFile);
      if (editor != null) {
        window.setSelectedEditor(editor, true);
      }
    }
    return window.myPanel;
  }
 public void replaceInjections(
     final List<? extends BaseInjection> newInjections,
     final List<? extends BaseInjection> originalInjections) {
   for (BaseInjection injection : originalInjections) {
     myInjections.get(injection.getSupportId()).remove(injection);
   }
   for (BaseInjection injection : newInjections) {
     injection.initializePlaces(true);
     myInjections.get(injection.getSupportId()).add(injection);
   }
   configurationModified();
   for (Project project : ProjectManager.getInstance().getOpenProjects()) {
     FileContentUtil.reparseFiles(project, Collections.<VirtualFile>emptyList(), true);
   }
 }
Beispiel #29
0
  public static List<PsiLambdaExpression> collectLambdas(
      @NotNull SourcePosition position, final boolean onlyOnTheLine) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    PsiFile file = position.getFile();
    final int line = position.getLine();
    final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
    if (document == null || line >= document.getLineCount()) {
      return Collections.emptyList();
    }
    PsiElement element = position.getElementAt();
    final TextRange lineRange = DocumentUtil.getLineTextRange(document, line);
    do {
      PsiElement parent = element.getParent();
      if (parent == null || (parent.getTextOffset() < lineRange.getStartOffset())) {
        break;
      }
      element = parent;
    } while (true);

    final List<PsiLambdaExpression> lambdas = new ArrayList<PsiLambdaExpression>(3);
    final PsiElementVisitor lambdaCollector =
        new JavaRecursiveElementVisitor() {
          @Override
          public void visitLambdaExpression(PsiLambdaExpression expression) {
            super.visitLambdaExpression(expression);
            if (!onlyOnTheLine || getFirstElementOnTheLine(expression, document, line) != null) {
              lambdas.add(expression);
            }
          }
        };
    element.accept(lambdaCollector);
    // add initial lambda if we're inside already
    PsiElement method = getContainingMethod(element);
    if (method instanceof PsiLambdaExpression) {
      lambdas.add((PsiLambdaExpression) method);
    }
    for (PsiElement sibling = getNextElement(element);
        sibling != null;
        sibling = getNextElement(sibling)) {
      if (!intersects(lineRange, sibling)) {
        break;
      }
      sibling.accept(lambdaCollector);
    }
    return lambdas;
  }
  static Collection<URL> getClassLoaderUrls() {
    final ClassLoader classLoader = PluginManagerCore.class.getClassLoader();
    final Class<? extends ClassLoader> aClass = classLoader.getClass();
    try {
      @SuppressWarnings("unchecked")
      List<URL> urls = (List<URL>) aClass.getMethod("getUrls").invoke(classLoader);
      return urls;
    } catch (IllegalAccessException ignored) {
    } catch (InvocationTargetException ignored) {
    } catch (NoSuchMethodException ignored) {
    }

    if (classLoader instanceof URLClassLoader) {
      return Arrays.asList(((URLClassLoader) classLoader).getURLs());
    }

    return Collections.emptyList();
  }