@Override @NotNull public LogData readAllHashes( @NotNull VirtualFile root, @NotNull final Consumer<TimedVcsCommit> commitConsumer) throws VcsException { if (!isRepositoryReady(root)) { return LogDataImpl.empty(); } List<String> parameters = new ArrayList<String>(GitHistoryUtils.LOG_ALL); parameters.add("--sparse"); final GitBekParentFixer parentFixer = GitBekParentFixer.prepare(root, this); Set<VcsUser> userRegistry = ContainerUtil.newHashSet(); Set<VcsRef> refs = ContainerUtil.newHashSet(); GitHistoryUtils.readCommits( myProject, root, parameters, new CollectConsumer<VcsUser>(userRegistry), new CollectConsumer<VcsRef>(refs), new Consumer<TimedVcsCommit>() { @Override public void consume(TimedVcsCommit commit) { commitConsumer.consume(parentFixer.fixCommit(commit)); } }); return new LogDataImpl(refs, userRegistry); }
private ClassMapCachingNulls<MultiHostInjector> getInjectorMap() { ClassMapCachingNulls<MultiHostInjector> cached = cachedInjectors; if (cached != null) { return cached; } Map<Class, MultiHostInjector[]> injectors = ContainerUtil.newHashMap(); List<MultiHostInjector> allInjectors = ContainerUtil.newArrayList(); allInjectors.addAll(myManualInjectors); Collections.addAll( allInjectors, MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME.getExtensions(myProject)); if (LanguageInjector.EXTENSION_POINT_NAME.getExtensions().length > 0) { allInjectors.add(PsiManagerRegisteredInjectorsAdapter.INSTANCE); } for (MultiHostInjector injector : allInjectors) { for (Class<? extends PsiElement> place : injector.elementsToInjectIn()) { LOG.assertTrue(place != null, injector); MultiHostInjector[] existing = injectors.get(place); injectors.put( place, existing == null ? new MultiHostInjector[] {injector} : ArrayUtil.append(existing, injector)); } } ClassMapCachingNulls<MultiHostInjector> result = new ClassMapCachingNulls<>(injectors, new MultiHostInjector[0], allInjectors); cachedInjectors = result; return result; }
@NotNull private static MutableCollectionComboBoxModel<String> createModel( @NotNull Collection<String> values, @NotNull String defaultValue) { List<String> items = ContainerUtil.newArrayList(defaultValue); items.addAll(ContainerUtil.sorted(values)); return new MutableCollectionComboBoxModel<String>(items, defaultValue); }
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); }
private static Groups prepareGroups( @NotNull VcsLogDataPack dataPack, @Nullable Collection<VirtualFile> visibleRoots, @Nullable List<List<String>> recentItems) { Groups filteredGroups = new Groups(); Collection<VcsRef> allRefs = dataPack.getRefs().getBranches(); for (Map.Entry<VirtualFile, Set<VcsRef>> entry : VcsLogUtil.groupRefsByRoot(allRefs).entrySet()) { VirtualFile root = entry.getKey(); if (visibleRoots != null && !visibleRoots.contains(root)) continue; Collection<VcsRef> refs = entry.getValue(); VcsLogProvider provider = dataPack.getLogProviders().get(root); VcsLogRefManager refManager = provider.getReferenceManager(); List<RefGroup> refGroups = refManager.group(refs); putActionsForReferences(refGroups, filteredGroups); } if (recentItems != null) { for (List<String> recentItem : recentItems) { if (recentItem.size() == 1) { final String item = ContainerUtil.getFirstItem(recentItem); if (filteredGroups.singletonGroups.contains(item) || ContainerUtil.find( filteredGroups.expandedGroups.values(), strings -> strings.contains(item)) != null) { continue; } } filteredGroups.recentGroups.add(recentItem); } } return filteredGroups; }
public GrInplaceConstantIntroducer( GrIntroduceContext context, OccurrencesChooser.ReplaceChoice choice) { super(IntroduceConstantHandler.REFACTORING_NAME, choice, context); myContext = context; myPanel = new GrInplaceIntroduceConstantPanel(); GrVariable localVar = GrIntroduceHandlerBase.resolveLocalVar(context); if (localVar != null) { ArrayList<String> result = ContainerUtil.newArrayList(localVar.getName()); GrExpression initializer = localVar.getInitializerGroovy(); if (initializer != null) { ContainerUtil.addAll( result, GroovyNameSuggestionUtil.suggestVariableNames( initializer, new GroovyInplaceFieldValidator(context), true)); } mySuggestedNames = ArrayUtil.toStringArray(result); } else { GrExpression expression = context.getExpression(); assert expression != null; mySuggestedNames = GroovyNameSuggestionUtil.suggestVariableNames( expression, new GroovyInplaceFieldValidator(context), true); } }
protected DfaMemoryStateImpl(DfaMemoryStateImpl toCopy) { myFactory = toCopy.myFactory; myEphemeral = toCopy.myEphemeral; myDefaultVariableStates = toCopy.myDefaultVariableStates; // shared between all states myStack = new Stack<>(toCopy.myStack); myDistinctClasses = new TLongHashSet(toCopy.myDistinctClasses.toArray()); myUnknownVariables = ContainerUtil.newLinkedHashSet(toCopy.myUnknownVariables); myEqClasses = ContainerUtil.newArrayList(toCopy.myEqClasses); myIdToEqClassesIndices = new MyIdMap(toCopy.myIdToEqClassesIndices.size()); toCopy.myIdToEqClassesIndices.forEachEntry( new TIntObjectProcedure<int[]>() { @Override public boolean execute(int id, int[] set) { myIdToEqClassesIndices.put(id, set); return true; } }); myVariableStates = ContainerUtil.newLinkedHashMap(toCopy.myVariableStates); myCachedDistinctClassPairs = toCopy.myCachedDistinctClassPairs; myCachedNonTrivialEqClasses = toCopy.myCachedNonTrivialEqClasses; myCachedHash = toCopy.myCachedHash; }
public void annotate( @NotNull final VirtualFile contentRoot, @NotNull final CoverageSuitesBundle suite, final @NotNull CoverageDataManager dataManager, @NotNull final ProjectData data, final Project project, final Annotator annotator) { if (!contentRoot.isValid()) { return; } // TODO: check name filter!!!!! final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); @SuppressWarnings("unchecked") final Set<String> files = data.getClasses().keySet(); final Map<String, String> normalizedFiles2Files = ContainerUtil.newHashMap(); for (final String file : files) { normalizedFiles2Files.put(normalizeFilePath(file), file); } collectFolderCoverage( contentRoot, dataManager, annotator, data, suite.isTrackTestFolders(), index, suite.getCoverageEngine(), ContainerUtil.newHashSet(), Collections.unmodifiableMap(normalizedFiles2Files)); }
@NotNull private static List<AndroidModuleExtension> getAllAndroidDependencies( @NotNull Module module, boolean androidLibrariesOnly, Ref<List<WeakReference<AndroidModuleExtension>>> listRef) { List<WeakReference<AndroidModuleExtension>> refs = listRef.get(); if (refs == null) { final List<AndroidModuleExtension> facets = new ArrayList<AndroidModuleExtension>(); collectAllAndroidDependencies( module, androidLibrariesOnly, facets, new HashSet<AndroidModuleExtension>()); refs = ContainerUtil.map( ContainerUtil.reverse(facets), new Function<AndroidModuleExtension, WeakReference<AndroidModuleExtension>>() { @Override public WeakReference<AndroidModuleExtension> fun(AndroidModuleExtension facet) { return new WeakReference<AndroidModuleExtension>(facet); } }); listRef.set(refs); } return dereference(refs); }
public NextOccurrenceAction( EditorSearchComponent editorSearchComponent, Getter<JTextComponent> editorTextField) { super(editorSearchComponent); myTextField = editorTextField; copyFrom(ActionManager.getInstance().getAction(IdeActions.ACTION_NEXT_OCCURENCE)); ArrayList<Shortcut> shortcuts = new ArrayList<Shortcut>(); ContainerUtil.addAll( shortcuts, ActionManager.getInstance() .getAction(IdeActions.ACTION_FIND_NEXT) .getShortcutSet() .getShortcuts()); if (!editorSearchComponent.getFindModel().isMultiline()) { ContainerUtil.addAll( shortcuts, ActionManager.getInstance() .getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN) .getShortcutSet() .getShortcuts()); shortcuts.add(new KeyboardShortcut(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), null)); } registerShortcutsForComponent(shortcuts, editorTextField.get()); }
@Override @Nullable public Collection<PsiImportStatementBase> findRedundantImports(final PsiJavaFile file) { final PsiImportList importList = file.getImportList(); if (importList == null) return null; final PsiImportStatementBase[] imports = importList.getAllImportStatements(); if (imports.length == 0) return null; Set<PsiImportStatementBase> allImports = new THashSet<PsiImportStatementBase>(Arrays.asList(imports)); final Collection<PsiImportStatementBase> redundant; if (FileTypeUtils.isInServerPageFile(file)) { // remove only duplicate imports redundant = ContainerUtil.newIdentityTroveSet(); ContainerUtil.addAll(redundant, imports); redundant.removeAll(allImports); for (PsiImportStatementBase importStatement : imports) { if (importStatement instanceof JspxImportStatement && importStatement.isForeignFileImport()) { redundant.remove(importStatement); } } } else { redundant = allImports; final List<PsiFile> roots = file.getViewProvider().getAllFiles(); for (PsiElement root : roots) { root.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { if (!reference.isQualified()) { final JavaResolveResult resolveResult = reference.advancedResolve(false); if (!inTheSamePackage(file, resolveResult.getElement())) { final PsiElement resolveScope = resolveResult.getCurrentFileResolveScope(); if (resolveScope instanceof PsiImportStatementBase) { final PsiImportStatementBase importStatementBase = (PsiImportStatementBase) resolveScope; redundant.remove(importStatementBase); } } } super.visitReferenceElement(reference); } private boolean inTheSamePackage(PsiJavaFile file, PsiElement element) { if (element instanceof PsiClass && ((PsiClass) element).getContainingClass() == null) { final PsiFile containingFile = element.getContainingFile(); if (containingFile instanceof PsiJavaFile) { return Comparing.strEqual( file.getPackageName(), ((PsiJavaFile) containingFile).getPackageName()); } } return false; } }); } } return redundant; }
private void doInstallActionHighlighters() { ContainerUtil.addIfNotNull(myOperations, createOperation(ThreeSide.LEFT, OperationType.APPLY)); ContainerUtil.addIfNotNull(myOperations, createOperation(ThreeSide.LEFT, OperationType.IGNORE)); ContainerUtil.addIfNotNull(myOperations, createOperation(ThreeSide.RIGHT, OperationType.APPLY)); ContainerUtil.addIfNotNull( myOperations, createOperation(ThreeSide.RIGHT, OperationType.IGNORE)); }
private List<MethodContract> visitEqualityComparison( List<ValueConstraint[]> states, PsiExpression op1, PsiExpression op2, boolean equality) { int parameter = resolveParameter(op1); ValueConstraint constraint = getLiteralConstraint(op2); if (parameter < 0 || constraint == null) { parameter = resolveParameter(op2); constraint = getLiteralConstraint(op1); } if (parameter >= 0 && constraint != null) { List<MethodContract> result = ContainerUtil.newArrayList(); for (ValueConstraint[] state : states) { ContainerUtil.addIfNotNull( result, contractWithConstraint( state, parameter, constraint, equality ? TRUE_VALUE : FALSE_VALUE)); ContainerUtil.addIfNotNull( result, contractWithConstraint( state, parameter, negateConstraint(constraint), equality ? FALSE_VALUE : TRUE_VALUE)); } return result; } return Collections.emptyList(); }
public void test_support_equally_named_branch_and_tag() throws Exception { prepareSomeHistory(); git("branch build"); git("tag build"); VcsLogProvider.DetailedLogData data = myLogProvider.readFirstBlock( myProjectRoot, new RequirementsImpl(1000, true, Collections.<VcsRef>emptySet())); List<VcsCommitMetadata> expectedLog = log(); assertOrderedEquals(data.getCommits(), expectedLog); assertTrue( ContainerUtil.exists( data.getRefs(), new Condition<VcsRef>() { @Override public boolean value(VcsRef ref) { return ref.getName().equals("build") && ref.getType() == GitRefManager.LOCAL_BRANCH; } })); assertTrue( ContainerUtil.exists( data.getRefs(), new Condition<VcsRef>() { @Override public boolean value(VcsRef ref) { return ref.getName().equals("build") && ref.getType() == GitRefManager.TAG; } })); }
private static OrderEntry[] calcOrderEntries( @NotNull RootInfo info, @NotNull MultiMap<VirtualFile, OrderEntry> depEntries, @NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries, @NotNull MultiMap<VirtualFile, OrderEntry> libSourceRootEntries, @NotNull List<VirtualFile> hierarchy) { @Nullable VirtualFile libraryClassRoot = info.findLibraryRootInfo(hierarchy, false); @Nullable VirtualFile librarySourceRoot = info.findLibraryRootInfo(hierarchy, true); Set<OrderEntry> orderEntries = ContainerUtil.newLinkedHashSet(); orderEntries.addAll( info.getLibraryOrderEntries( hierarchy, libraryClassRoot, librarySourceRoot, libClassRootEntries, libSourceRootEntries)); for (VirtualFile root : hierarchy) { orderEntries.addAll(depEntries.get(root)); } VirtualFile moduleContentRoot = info.findModuleRootInfo(hierarchy); if (moduleContentRoot != null) { ContainerUtil.addIfNotNull( orderEntries, info.getModuleSourceEntry(hierarchy, moduleContentRoot, libClassRootEntries)); } if (orderEntries.isEmpty()) { return null; } OrderEntry[] array = orderEntries.toArray(new OrderEntry[orderEntries.size()]); Arrays.sort(array, BY_OWNER_MODULE); return array; }
private void doUpdateRanges( int beforeChangedLine1, int beforeChangedLine2, int linesShift, int beforeTotalLines) { List<Range> rangesBeforeChange = new ArrayList<Range>(); List<Range> rangesAfterChange = new ArrayList<Range>(); List<Range> changedRanges = new ArrayList<Range>(); sortRanges( beforeChangedLine1, beforeChangedLine2, linesShift, rangesBeforeChange, changedRanges, rangesAfterChange); Range firstChangedRange = ContainerUtil.getFirstItem(changedRanges); Range lastChangedRange = ContainerUtil.getLastItem(changedRanges); if (firstChangedRange != null && firstChangedRange.getLine1() < beforeChangedLine1) { beforeChangedLine1 = firstChangedRange.getLine1(); } if (lastChangedRange != null && lastChangedRange.getLine2() > beforeChangedLine2) { beforeChangedLine2 = lastChangedRange.getLine2(); } doUpdateRanges( beforeChangedLine1, beforeChangedLine2, linesShift, beforeTotalLines, rangesBeforeChange, changedRanges, rangesAfterChange); }
private void createEditors(@Nullable Module module) { if (module == null) return; ModuleConfigurationState state = createModuleConfigurationState(); for (ModuleConfigurationEditorProvider provider : collectProviders(module)) { ModuleConfigurationEditor[] editors = provider.createEditors(state); if (editors.length > 0 && provider instanceof ModuleConfigurationEditorProviderEx && ((ModuleConfigurationEditorProviderEx) provider).isCompleteEditorSet()) { myEditors.clear(); ContainerUtil.addAll(myEditors, editors); break; } else { ContainerUtil.addAll(myEditors, editors); } } for (Configurable moduleConfigurable : ServiceKt.getComponents(module, Configurable.class)) { reportDeprecatedModuleEditor(moduleConfigurable.getClass()); myEditors.add(new ModuleConfigurableWrapper(moduleConfigurable)); } for (ModuleConfigurableEP extension : module.getExtensions(MODULE_CONFIGURABLES)) { if (extension.canCreateConfigurable()) { Configurable configurable = extension.createConfigurable(); if (configurable != null) { reportDeprecatedModuleEditor(configurable.getClass()); myEditors.add(new ModuleConfigurableWrapper(configurable)); } } } }
public void moveMembersToBase() throws IncorrectOperationException { myMovedMembers = ContainerUtil.newHashSet(); myMembersAfterMove = ContainerUtil.newHashSet(); // build aux sets for (MemberInfo info : myMembersToMove) { myMovedMembers.add(info.getMember()); } final PsiSubstitutor substitutor = upDownSuperClassSubstitutor(); for (MemberInfo info : myMembersToMove) { PullUpHelper<MemberInfo> processor = getProcessor(info); LOG.assertTrue(processor != null, info.getMember()); if (!(info.getMember() instanceof PsiClass) || info.getOverrides() == null) { processor.setCorrectVisibility(info); processor.encodeContextInfo(info); } processor.move(info, substitutor); } for (PsiMember member : myMembersAfterMove) { PullUpHelper<MemberInfo> processor = getProcessor(member); LOG.assertTrue(processor != null, member); processor.postProcessMember(member); final JavaRefactoringListenerManager listenerManager = JavaRefactoringListenerManager.getInstance(myProject); ((JavaRefactoringListenerManagerImpl) listenerManager).fireMemberMoved(mySourceClass, member); } }
private static PsiElement fixCatchBlock(GrTryCatchStatement tryCatch, PsiClassType[] exceptions) { if (exceptions.length == 0) return tryCatch; final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(tryCatch.getProject()); final GrCatchClause[] clauses = tryCatch.getCatchClauses(); List<String> restricted = ContainerUtil.map( clauses, new Function<GrCatchClause, String>() { @Override @Nullable public String fun(GrCatchClause grCatchClause) { final GrParameter grParameter = grCatchClause.getParameter(); return grParameter != null ? grParameter.getName() : null; } }); restricted = ContainerUtil.skipNulls(restricted); final DefaultGroovyVariableNameValidator nameValidator = new DefaultGroovyVariableNameValidator(tryCatch, restricted); GrCatchClause anchor = clauses.length == 0 ? null : clauses[clauses.length - 1]; for (PsiClassType type : exceptions) { final String[] names = GroovyNameSuggestionUtil.suggestVariableNameByType(type, nameValidator); final GrCatchClause catchClause = factory.createCatchClause(type, names[0]); final GrStatement printStackTrace = factory.createStatementFromText(names[0] + ".printStackTrace()"); catchClause.getBody().addStatementBefore(printStackTrace, null); anchor = tryCatch.addCatchClause(catchClause, anchor); JavaCodeStyleManager.getInstance(anchor.getProject()).shortenClassReferences(anchor); } return tryCatch; }
public void testDelayedTasksThatFiredAtTheSameTimeAreExecutedConcurrently() throws InterruptedException, ExecutionException { final AppScheduledExecutorService service = new AppScheduledExecutorService(getName()); final List<LogInfo> log = Collections.synchronizedList(new ArrayList<>()); int delay = 500; int N = 20; List<? extends Future<?>> futures = ContainerUtil.map( Collections.nCopies(N, ""), __ -> service.schedule( () -> { log.add(new LogInfo(0)); TimeoutUtil.sleep(10 * 1000); }, delay, TimeUnit.MILLISECONDS)); for (Future<?> future : futures) { future.get(); } assertEquals(N, log.size()); Set<Thread> usedThreads = ContainerUtil.map2Set(log, logInfo -> logInfo.currentThread); assertEquals(N, usedThreads.size()); service.shutdownAppScheduledExecutorService(); assertTrue(service.awaitTermination(10, TimeUnit.SECONDS)); }
@Nullable private List<GithubFullPath> getAvailableForks(@NotNull ProgressIndicator indicator) { try { List<GithubFullPath> forks = ContainerUtil.map( GithubUtil.runTask( myProject, myAuthHolder, indicator, new ThrowableConvertor<GithubConnection, List<GithubRepo>, IOException>() { @NotNull @Override public List<GithubRepo> convert(@NotNull GithubConnection connection) throws IOException { return GithubApiUtil.getForks( connection, mySource.getUser(), mySource.getRepository()); } }), new Function<GithubRepo, GithubFullPath>() { @Override public GithubFullPath fun(GithubRepo repo) { return repo.getFullPath(); } }); if (!forks.contains(mySource)) return ContainerUtil.append(forks, mySource); return forks; } catch (IOException e) { GithubNotifications.showWarning(myProject, "Can't load available forks", e); return null; } }
private UnionScope(@NotNull GlobalSearchScope[] scopes) { super( ContainerUtil.getFirstItem( ContainerUtil.mapNotNull( scopes, new Function<GlobalSearchScope, Project>() { @Override public Project fun(GlobalSearchScope scope) { return scope.getProject(); } }), null)); if (scopes.length <= 1) throw new IllegalArgumentException("Too few scopes: " + Arrays.asList(scopes)); myScopes = scopes; final int[] nested = {0}; ContainerUtil.process( scopes, new Processor<GlobalSearchScope>() { @Override public boolean process(GlobalSearchScope scope) { nested[0] = Math.max( nested[0], scope instanceof UnionScope ? ((UnionScope) scope).myNestingLevel : 0); return true; } }); myNestingLevel = 1 + nested[0]; if (myNestingLevel > 1000) { throw new IllegalStateException( "Too many scopes combined: " + myNestingLevel + StringUtil.last(toString(), 500, true)); } }
private NamesByExprInfo suggestVariableNameByExpression( PsiExpression expr, VariableKind variableKind, boolean correctKeywords) { final LinkedHashSet<String> names = new LinkedHashSet<String>(); final String[] fromLiterals = suggestVariableNameFromLiterals(expr, variableKind, correctKeywords); if (fromLiterals != null) { ContainerUtil.addAll(names, fromLiterals); } ContainerUtil.addAll( names, suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, false).names); ContainerUtil.addAll( names, suggestVariableNameByExpressionPlace(expr, variableKind, correctKeywords).names); PsiType type = expr.getType(); if (type != null) { ContainerUtil.addAll(names, suggestVariableNameByType(type, variableKind, correctKeywords)); } ContainerUtil.addAll( names, suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, true).names); String[] namesArray = ArrayUtil.toStringArray(names); String propertyName = suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, false).propertyName != null ? suggestVariableNameByExpressionOnly(expr, variableKind, correctKeywords, false) .propertyName : suggestVariableNameByExpressionPlace(expr, variableKind, correctKeywords) .propertyName; return new NamesByExprInfo(propertyName, namesArray); }
@NotNull static List<HighlightInfo> checkDuplicateRequires(@NotNull PsiJavaModule module) { List<HighlightInfo> results = ContainerUtil.newSmartList(); Map<String, PsiElement> map = ContainerUtil.newHashMap(); for (PsiElement child = module.getFirstChild(); child != null; child = child.getNextSibling()) { if (child instanceof PsiRequiresStatement) { PsiJavaModuleReferenceElement ref = ((PsiRequiresStatement) child).getReferenceElement(); if (ref != null) { String text = ref.getReferenceText(); if (!map.containsKey(text)) { map.put(text, child); } else { String message = JavaErrorMessages.message("module.duplicate.requires", text); HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) .range(child) .description(message) .create(); QuickFixAction.registerQuickFixAction(info, new DeleteElementFix(child)); results.add(info); } } } } return results; }
private List<HighlightInfo> getHighlights() { if (myReadAccessRanges.isEmpty() && myWriteAccessRanges.isEmpty()) { return Collections.emptyList(); } Set<Pair<Object, TextRange>> existingMarkupTooltips = new HashSet<Pair<Object, TextRange>>(); for (RangeHighlighter highlighter : myEditor.getMarkupModel().getAllHighlighters()) { existingMarkupTooltips.add( Pair.create( highlighter.getErrorStripeTooltip(), new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset()))); } List<HighlightInfo> result = new ArrayList<HighlightInfo>(myReadAccessRanges.size() + myWriteAccessRanges.size()); for (TextRange range : myReadAccessRanges) { ContainerUtil.addIfNotNull( createHighlightInfo( range, HighlightInfoType.ELEMENT_UNDER_CARET_READ, existingMarkupTooltips), result); } for (TextRange range : myWriteAccessRanges) { ContainerUtil.addIfNotNull( createHighlightInfo( range, HighlightInfoType.ELEMENT_UNDER_CARET_WRITE, existingMarkupTooltips), result); } return result; }
@NotNull private static List<VirtualFile> findClasses(File file, boolean isJre) { List<VirtualFile> result = ContainerUtil.newArrayList(); VirtualFileManager fileManager = VirtualFileManager.getInstance(); String path = file.getPath(); if (JrtFileSystem.isModularJdk(path)) { String url = VirtualFileManager.constructUrl( JrtFileSystem.PROTOCOL, FileUtil.toSystemIndependentName(path) + JrtFileSystem.SEPARATOR); for (String module : JrtFileSystem.listModules(path)) { ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url + module)); } } for (File root : JavaSdkUtil.getJdkClassesRoots(file, isJre)) { String url = VfsUtil.getUrlForLibraryRoot(root); ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url)); } Collections.sort(result, (o1, o2) -> o1.getPath().compareTo(o2.getPath())); return result; }
@Override public void customizePainter( @NotNull JComponent component, @NotNull Collection<VcsRef> references, @Nullable VcsLogRefManager manager, @NotNull Color background, @NotNull Color foreground) { FontMetrics metrics = component.getFontMetrics(getReferenceFont()); myHeight = metrics.getHeight() + RectanglePainter.TOP_TEXT_PADDING + RectanglePainter.BOTTOM_TEXT_PADDING; myWidth = 2 * PaintParameters.LABEL_PADDING; myLabels = ContainerUtil.newArrayList(); if (manager == null) return; List<VcsRef> sorted = ContainerUtil.sorted(references, manager.getLabelsOrderComparator()); for (Map.Entry<VcsRefType, Collection<VcsRef>> entry : ContainerUtil.groupBy(sorted, VcsRef::getType).entrySet()) { VcsRef ref = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(entry.getValue())); String text = ref.getName() + (entry.getValue().size() > 1 ? " +" : ""); myLabels.add(Pair.create(text, entry.getKey().getBackgroundColor())); myWidth += myLabelPainter.calculateSize(text, metrics).getWidth() + PaintParameters.LABEL_PADDING; } }
private void calculateAlignments(List<ASTNode> children, boolean classLevel) { List<GrStatement> currentGroup = null; boolean spock = true; for (ASTNode child : children) { PsiElement psi = child.getPsi(); if (psi instanceof GrLabeledStatement) { alignGroup(currentGroup, spock, classLevel); currentGroup = ContainerUtil.newArrayList((GrStatement) psi); spock = true; } else if (currentGroup != null && spock && isTablePart(psi)) { currentGroup.add((GrStatement) psi); } else if (psi instanceof GrVariableDeclaration) { GrVariable[] variables = ((GrVariableDeclaration) psi).getVariables(); if (variables.length > 0) { if (!classLevel || currentGroup == null || fieldGroupEnded(psi) || spock) { alignGroup(currentGroup, spock, classLevel); currentGroup = ContainerUtil.newArrayList(); spock = false; } currentGroup.add((GrStatement) psi); } } else { if (psi instanceof PsiComment) { PsiElement prev = psi.getPrevSibling(); if (prev != null && prev.getNode().getElementType() != mNLS || classLevel && !fieldGroupEnded(psi)) { continue; } } alignGroup(currentGroup, spock, classLevel); currentGroup = null; } } }
private class ExplicitSuperDeleter extends GroovyRecursiveElementVisitor { private final ArrayList<GrExpression> mySupersToDelete = ContainerUtil.newArrayList(); private final ArrayList<GrReferenceExpression> mySupersToChangeToThis = ContainerUtil.newArrayList(); @Override public void visitReferenceExpression(GrReferenceExpression expression) { super.visitReferenceExpression(expression); if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isSuperReference( expression.getQualifierExpression())) { PsiElement resolved = expression.resolve(); if (resolved == null || resolved instanceof PsiMethod && shouldFixSuper((PsiMethod) resolved)) { mySupersToDelete.add(expression.getQualifierExpression()); } } else if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isSuperReference(expression)) { mySupersToChangeToThis.add(expression); } } @Override public void visitTypeDefinition(GrTypeDefinition typeDefinition) { // do nothing } private boolean shouldFixSuper(PsiMethod method) { for (PsiMember element : myMembersAfterMove) { if (element instanceof PsiMethod) { PsiMethod member = (PsiMethod) element; // if there is such member among moved members, super qualifier // should not be removed final PsiManager manager = method.getManager(); if (manager.areElementsEquivalent( member.getContainingClass(), method.getContainingClass()) && MethodSignatureUtil.areSignaturesEqual(member, method)) { return false; } } } final PsiMethod methodFromSuper = myTargetSuperClass.findMethodBySignature(method, false); return methodFromSuper == null; } public void fixSupers() throws IncorrectOperationException { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject); GrReferenceExpression thisExpression = (GrReferenceExpression) factory.createExpressionFromText("this", null); for (GrExpression expression : mySupersToDelete) { if (expression.getParent() instanceof GrReferenceExpression) { ((GrReferenceExpression) expression.getParent()).setQualifier(null); } } for (GrReferenceExpression superExpression : mySupersToChangeToThis) { superExpression.replace(thisExpression); } } }
private static ModuleConfigurationEditorProvider[] collectProviders(final Module module) { List<ModuleConfigurationEditorProvider> result = new ArrayList<ModuleConfigurationEditorProvider>(); ContainerUtil.addAll(result, module.getComponents(ModuleConfigurationEditorProvider.class)); ContainerUtil.addAll( result, Extensions.getExtensions(ModuleConfigurationEditorProvider.EP_NAME, module)); return result.toArray(new ModuleConfigurationEditorProvider[result.size()]); }