public TableInfo(DasTable tableElement) { this.tableElement = tableElement; List<DasColumn> columns = new ArrayList<>(); JBIterable<? extends DasColumn> columnsIter = DasUtil.getColumns(tableElement); List<? extends DasColumn> dasColumns = columnsIter.toList(); for (DasColumn dasColumn : dasColumns) { columns.add(dasColumn); if (DasUtil.isPrimary(dasColumn)) { primaryKeys.add(dasColumn.getName()); } } this.columns = columns; }
public static ArrayList<LookupElementBuilder> getLookupItemsTables(Project project, PhpExpression position) { DbPsiFacade facade = DbPsiFacade.getInstance(project); List<DbDataSource> dataSources = facade.getDataSources(); // Code to test tests :) //dataSources.clear(); //dataSources.add(new TestDataSource(project)); ArrayList<LookupElementBuilder> list = new ArrayList<>(); for (DbDataSource source : dataSources) { JBIterable<DasTable> filtered = source.getModel().traverser().filter(DasTable.class); for (Object item : filtered) { if (item instanceof DasTable) { list.add(DatabaseUtils.buildLookup(item, true, project)); } } } return list; }
public void newColumnEditorByDb(IdeaContext ideaContext, List<DbTable> dbTables) { List<Table> tables = new ArrayList<>(); for (DbTable dbTable: dbTables) { Table table = new Table(); table.setTableName(dbTable.getName()); List<Field> fields = new ArrayList<>(); JBIterable<? extends DasColumn> columnsIter = DasUtil.getColumns(dbTable); List<? extends DasColumn> dasColumns = columnsIter.toList(); for (DasColumn dasColumn : dasColumns) { Field field = new Field(); field.setColumn(dasColumn.getName()); field.setColumnType(dasColumn.getDataType().typeName); field.setColumnSize(String.valueOf(dasColumn.getDataType().size)); field.setComment(dasColumn.getComment()); fields.add(field); } table.setFields(fields); tables.add(table); } init(ideaContext, tables); // esc this.getRootPane().registerKeyboardAction(e -> dispose(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); }
@Override public void update(AnActionEvent e) { Project project = e.getProject(); JBIterable<VirtualFile> files = JBIterable.of(e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)); if (project == null || files.isEmpty()) { e.getPresentation().setEnabledAndVisible(false); return; } Condition<VirtualFile> isScratch = fileFilter(project); if (!files.filter(not(isScratch)).isEmpty()) { e.getPresentation().setEnabledAndVisible(false); return; } Set<Language> langs = files.filter(isScratch).transform(fileLanguage(project)).filter(notNull()). addAllTo(ContainerUtil.<Language>newLinkedHashSet()); String langName = langs.size() == 1 ? langs.iterator().next().getDisplayName() : langs.size() + " different"; e.getPresentation().setText(String.format("Change %s (%s)...", getLanguageTerm(), langName)); e.getPresentation().setEnabledAndVisible(true); }
public static String getStorageRoot(String[] urls, Project project) { if (urls.length == 0) { return null; } final String localRepositoryPath = FileUtil.toSystemIndependentName(MavenProjectsManager.getInstance(project).getLocalRepository().getPath()); List<String> roots = JBIterable.of(urls).transform(new Function<String, String>() { @Override public String fun(String urlWithPrefix) { String url = StringUtil.trimStart(urlWithPrefix, JarFileSystem.PROTOCOL_PREFIX); return url.startsWith(localRepositoryPath) ? null : FileUtil.toSystemDependentName(PathUtil.getParentPath(url)); } }).toList(); Map<String, Integer> counts = new HashMap<String, Integer>(); for (String root : roots) { int count = counts.get(root) != null ? counts.get(root) : 0; counts.put(root, count + 1); } return Collections.max(counts.entrySet(), new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }).getKey(); }
private static int getSelection(String selectedVersion, List<String> versions) { VersionKind versionKind = getVersionKind(selectedVersion); int releaseIndex = JBIterable.from(versions).takeWhile(new Condition<String>() { @Override public boolean value(String version) { return version.endsWith(RepositoryUtils.SnapshotVersionSuffix); } }).size(); switch (versionKind) { case Unselected: return -1; case Release: return releaseIndex == versions.size() ? -1 : releaseIndex; case Latest: return 0; case Select: if (versions.indexOf(selectedVersion) == -1) { versions.add(0, selectedVersion); } return versions.indexOf(selectedVersion); } return -1; }
@Nonnull public static JBTreeTraverser<TreePath> treePathTraverser(@Nonnull JTree tree) { TreeModel model = tree.getModel(); JBIterable<Integer> numbers = JBIterable.generate(0, i -> i + 1); Object root = model.getRoot(); TreePath rootPath = root == null ? null : new TreePath(root); return new JBTreeTraverser<TreePath>(o -> { Object parent = o.getLastPathComponent(); int count = model.getChildCount(parent); return count == 0 ? JBIterable.empty() : numbers.take(count).map( index -> o.pathByAddingChild(model.getChild(parent, index))); }) .withRoot(rootPath); }
@Nonnull @Override public PsiDirectory[] getDirectories() { NavBarPopup nodePopup = myPanel.getNodePopup(); JBIterable<?> selection = nodePopup != null && nodePopup.isVisible() ? JBIterable.from(nodePopup.getList().getSelectedValuesList()) : myPanel.getSelection(); List<PsiDirectory> dirs = selection.flatMap(o -> { if (o instanceof PsiElement && !((PsiElement)o).isValid()) return JBIterable.empty(); if (o instanceof PsiDirectory) return JBIterable.of((PsiDirectory)o); if (o instanceof PsiDirectoryContainer) { return JBIterable.of(((PsiDirectoryContainer)o).getDirectories()); } if (o instanceof PsiElement) { PsiFile file = ((PsiElement)o).getContainingFile(); return JBIterable.of(file != null ? file.getContainingDirectory() : null); } if (o instanceof Module && !((Module)o).isDisposed()) { PsiManager psiManager = PsiManager.getInstance(myPanel.getProject()); return JBIterable.of(ModuleRootManager.getInstance((Module)o).getSourceRoots()).filterMap(file -> psiManager.findDirectory(file)); } return JBIterable.empty(); }).filter(o -> o.isValid()).toList(); return dirs.isEmpty() ? PsiDirectory.EMPTY_ARRAY : dirs.toArray(PsiDirectory.EMPTY_ARRAY); }
@RequiredReadAction private static Set<InlayInfo> createMergedHints(PsiCallExpression callExpression, ResolveResult[] results) { List<Set<InlayInfo>> resultSet = Arrays.stream(results).map(it -> it.getElement() == null ? null : createHintsForResolvedMethod(callExpression, it)).filter(Objects::nonNull).collect (Collectors.toList()); if(resultSet.isEmpty()) { return Collections.emptySet(); } for(Set<InlayInfo> inlayInfos : resultSet) { if(inlayInfos.isEmpty()) { return Collections.emptySet(); } } return JBIterable.from(resultSet).reduce(null, (left, right) -> SetUtil.intersect(left, right)); }
private static List<LookupElement> collectThisVariants(PsiType functionalInterfaceType, PsiParameter[] params, PsiElement originalPosition, PsiSubstitutor substitutor, PsiType expectedReturnType) { List<LookupElement> result = new ArrayList<>(); Iterable<PsiClass> instanceClasses = JBIterable.generate(originalPosition, PsiElement::getParent).filter(PsiMember.class).takeWhile(m -> !m.hasModifierProperty(PsiModifier.STATIC)).filter (PsiClass.class); boolean first = true; for(PsiClass psiClass : instanceClasses) { if(!first && psiClass.getName() == null) { continue; } for(PsiMethod psiMethod : psiClass.getMethods()) { if(!psiMethod.hasModifierProperty(PsiModifier.STATIC) && hasAppropriateReturnType(expectedReturnType, psiMethod) && areParameterTypesAppropriate(psiMethod, params, substitutor, 0)) { result.add(createMethodRefOnThis(functionalInterfaceType, psiMethod, first ? null : psiClass)); } } first = false; } return result; }
private static List<LookupElement> collectStaticVariants(PsiType functionalInterfaceType, PsiParameter[] params, PsiElement originalPosition, PsiSubstitutor substitutor, PsiType expectedReturnType) { List<LookupElement> result = new ArrayList<>(); for(PsiClass psiClass : JBIterable.generate(PsiTreeUtil.getParentOfType(originalPosition, PsiClass.class), PsiClass::getContainingClass)) { for(PsiMethod psiMethod : psiClass.getMethods()) { if(psiMethod.hasModifierProperty(PsiModifier.STATIC) && hasAppropriateReturnType(expectedReturnType, psiMethod) && areParameterTypesAppropriate(psiMethod, params, substitutor, 0)) { result.add(createMethodRefOnClass(functionalInterfaceType, psiMethod, psiClass)); } } } return result; }
private boolean suggestByExpectedType(Consumer<LookupElement> result, PsiElement context, PsiTypeParameterListOwner paramOwner, int index) { PsiExpression expression = PsiTreeUtil.getContextOfType(context, PsiExpression.class, true); ExpectedTypeInfo[] types = ExpectedTypesProvider.getExpectedTypes(expression, true, false, false); if(expression == null || types.length == 0) { return false; } for(ExpectedTypeInfo info : types) { PsiType type = info.getType(); if(type instanceof PsiClassType && !type.equals(expression.getType())) { JBIterable<PsiTypeParameter> remainingParams = JBIterable.of(paramOwner.getTypeParameters()).skip(index); List<PsiType> expectedArgs = getExpectedTypeArgs(context, paramOwner, remainingParams, (PsiClassType) type); createLookupItems(result, context, info, expectedArgs, paramOwner); } } return true; }
@NotNull private static List<PsiType> getExpectedTypeArgs(PsiElement context, PsiTypeParameterListOwner paramOwner, JBIterable<PsiTypeParameter> typeParams, PsiClassType expectedType) { if(paramOwner instanceof PsiClass) { PsiClassType.ClassResolveResult resolve = expectedType.resolveGenerics(); final PsiClass expectedClass = resolve.getElement(); if(!InheritanceUtil.isInheritorOrSelf((PsiClass) paramOwner, expectedClass, true)) { return typeParams.map(p -> (PsiType) null).toList(); } PsiSubstitutor substitutor = TypeConversionUtil.getClassSubstitutor(expectedClass, (PsiClass) paramOwner, PsiSubstitutor.EMPTY); assert substitutor != null; return typeParams.map(p -> getExpectedTypeArg(context, resolve, substitutor, p)).toList(); } PsiSubstitutor substitutor = SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor((PsiMethod) paramOwner, expectedType); return typeParams.map(substitutor::substitute).toList(); }
@Nullable @Override public DasNamespace getCurrentRootNamespace() { return new DasNamespace() { @NotNull @Override public ObjectKind getKind() { return null; } @NotNull @Override public String getName() { return null; } @Nullable @Override public String getComment() { return null; } @Nullable @Override public DasObject getDbParent() { return null; } @NotNull @Override public <C> JBIterable<C> getDbChildren(@NotNull Class<C> clazz, @NotNull ObjectKind kind) { return null; } }; }
@NotNull @Override public <C> JBIterable<C> getDbChildren(@NotNull Class<C> clazz, @NotNull ObjectKind kind) { if (clazz == DasColumn.class) { JBIterable<C> iter = new JBIterable<C>() { @Override public Iterator<C> iterator() { return new Iterator<C>() { int counter = 0; @Override public boolean hasNext() { if (clazz == DasColumn.class) { return columns.size() > counter; } else return false; } @Override public C next() { if (clazz == DasColumn.class) { return (C)columns.get(counter++); } else return null; } }; } }; return iter; } return null; }
@Nullable public T getRawDeepestLast() { for (T result = getRoot(), last; result != null; result = last) { JBIterable<T> children = children(result); if (children.isEmpty()) return result; //noinspection AssignmentToForLoopParameter last = children.last(); } return null; }
@NotNull public JBIterable<T> parents(@Nullable final T element) { return JBIterable.generate(element, new Function<T, T>() { @Override public T fun(T t) { return parent(t); } }); }
@NotNull @Override public JBIterable<? extends T> children(@NotNull final T node) { final T first = first(node); if (first == null) return JBIterable.empty(); return JBIterable.generate(first, new Function<T, T>() { @Override public T fun(T t) { return next(t); } }); }
@NotNull @Override public JBIterable<? extends T> children(@NotNull final T node) { return new JBIterable<T>() { @Override public Iterator<T> iterator() { FlyweightCapableTreeStructure<T> structure = getStructure(); Ref<T[]> ref = Ref.create(); int count = structure.getChildren(structure.prepareForGetChildren(node), ref); if (count == 0) return ContainerUtil.emptyIterator(); T[] array = ref.get(); LinkedList<T> list = ContainerUtil.newLinkedList(); for (int i = 0; i < count; i++) { T child = array[i]; IElementType childType = typeOf(child); // skip TokenType.* types, errors cannot be properly handled (no parents) if (childType == TokenType.ERROR_ELEMENT) { // todo remember error continue; } else if (childType == TokenType.WHITE_SPACE || childType == TokenType.BAD_CHARACTER) { continue; } array[i] = null; // do not dispose meaningful TokenNodes list.addLast(child); } structure.disposeChildren(array, count); return list.iterator(); } }; }
@NotNull public static Set<ExpressionTypeProvider> getHandlers(final Project project, Language... languages) { return JBIterable.of(languages).flatten(new Function<Language, Iterable<ExpressionTypeProvider>>() { @Override public Iterable<ExpressionTypeProvider> fun(Language language) { return DumbService.getInstance(project).filterByDumbAwareness(LanguageExpressionTypes.INSTANCE.allForLanguage(language)); } }).addAllTo(ContainerUtil.<ExpressionTypeProvider>newLinkedHashSet()); }
@Override public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); JBIterable<VirtualFile> files = JBIterable.of(e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)). filter(fileFilter(project)); if (project == null || files.isEmpty()) return; actionPerformedImpl(e, project, files); }
@Nullable public T getRawDeepestLast() { for (T result = JBIterable.from(getRoots()).last(), last; result != null; result = last) { JBIterable<T> children = children(result); if (children.isEmpty()) return result; //noinspection AssignmentToForLoopParameter last = children.last(); } return null; }
@Nonnull @Override public JBIterable<? extends T> children(@Nonnull T node) { T first = first(node); if (first == null) return JBIterable.empty(); return siblings(first); }
@Nonnull @Override public JBIterable<? extends T> children(@Nonnull final T node) { return new JBIterable<T>() { @Override public Iterator<T> iterator() { FlyweightCapableTreeStructure<T> structure = getStructure(); Ref<T[]> ref = Ref.create(); int count = structure.getChildren(node, ref); if (count == 0) return ContainerUtil.emptyIterator(); T[] array = ref.get(); LinkedList<T> list = ContainerUtil.newLinkedList(); for (int i = 0; i < count; i++) { T child = array[i]; IElementType childType = typeOf(child); // tokens and errors getParent() == null if (childType == TokenType.WHITE_SPACE || childType == TokenType.BAD_CHARACTER) { continue; } array[i] = null; // do not dispose meaningful TokenNodes list.addLast(child); } structure.disposeChildren(array, count); return list.iterator(); } }; }
private Iterable<String> chooseFirstTimeItems(String path) { if (path == null) { return Collections.emptyList(); } else { return JBIterable.from(StringUtil.tokenize(path, File.pathSeparator)).filter(element -> { element = element.trim(); return !element.isEmpty() && !myPathSet.contains(element); }); } }
private static Field processFields(@Nonnull Class clazz, @Nonnull Condition<Field> checker) { for (Class c : classTraverser(clazz)) { Field field = JBIterable.of(c.getDeclaredFields()).find(checker); if (field != null) { field.setAccessible(true); return field; } } return null; }
private boolean integrateIntoExistingChanges(CompositeElement nextParent) { for (CompositeElement eachParent : JBIterable.generate(nextParent, TreeElement::getTreeParent)) { CompositeElement superParent = eachParent.getTreeParent(); TreeChangeImpl superChange = myChangedElements.get(superParent); if (superChange != null) { superChange.markChildChanged(eachParent, 0); return true; } } return false; }
@Nonnull public static Set<ExpressionTypeProvider> getHandlers(final Project project, Language... languages) { return JBIterable.of(languages).flatten(new Function<Language, Iterable<ExpressionTypeProvider>>() { @Override public Iterable<ExpressionTypeProvider> fun(Language language) { return DumbService.getInstance(project).filterByDumbAwareness(LanguageExpressionTypes.INSTANCE.allForLanguage(language)); } }).addAllTo(ContainerUtil.<ExpressionTypeProvider>newLinkedHashSet()); }
@Nonnull @Override public Iterable<LookupElement> classify(@Nonnull Iterable<LookupElement> source, @Nonnull final ProcessingContext context) { List<LookupElement> initialList = getInitialNoStatElements(source, context); Iterable<LookupElement> rest = withoutInitial(source, initialList); Collection<List<LookupElement>> byWeight = buildMapByWeight(rest).descendingMap().values(); return JBIterable.from(initialList).append(JBIterable.from(byWeight).flatten(group -> myNext.classify(group, context))); }
private static JComponent createPopupContent(NavBarPanel panel, Object[] siblings) { class MyList<E> extends JBList<E> implements DataProvider, Queryable { @Override public void putInfo(@Nonnull Map<String, String> info) { panel.putInfo(info); } @Nullable @Override public Object getData(Key dataId) { return panel.getDataImpl(dataId, () -> JBIterable.of(getSelectedValuesList())); } } JBList<Object> list = new MyList<>(); list.setModel(new CollectionListModel<>(siblings)); HintUpdateSupply.installSimpleHintUpdateSupply(list); List<Disposable> disposables = new ArrayList<>(); list.putClientProperty(DISPOSED_OBJECTS, disposables); list.installCellRenderer(obj -> { final NavBarItem navBarItem = new NavBarItem(panel, obj, null); disposables.add(navBarItem); return navBarItem; }); list.setBorder(JBUI.Borders.empty(5)); installMoveAction(list, panel, -1, KeyEvent.VK_LEFT); installMoveAction(list, panel, 1, KeyEvent.VK_RIGHT); installEnterAction(list, panel, KeyEvent.VK_ENTER); installEscapeAction(list, panel, KeyEvent.VK_ESCAPE); JComponent component = ListWithFilter.wrap(list, new NavBarListWrapper(list), o -> panel.getPresentation().getPresentableText(o)); component.putClientProperty(JBLIST_KEY, list); return component; }
@Nonnull JBIterable<?> getSelection() { Object value = myModel.getSelectedValue(); if (value != null) return JBIterable.of(value); int size = myModel.size(); return JBIterable.of(size > 0 ? myModel.getElement(size - 1) : null); }
@NotNull @Override public PsiAnnotation[] getAnnotations() { PsiAnnotation[] result = myCache; if(result == null) { List<PsiAnnotation> filtered = JBIterable.of(myCandidates).filter(annotation -> AnnotationTargetUtil.isTypeAnnotation(annotation)).append(myOriginalProvider.getAnnotations()) .toList(); myCache = result = filtered.isEmpty() ? PsiAnnotation.EMPTY_ARRAY : filtered.toArray(new PsiAnnotation[filtered.size()]); } return result; }
@NotNull @Override public Iterable<PsiRequiresStatement> getRequires() { PsiJavaModuleStub stub = getGreenStub(); if(stub != null) { return JBIterable.of(stub.getChildrenByType(JavaElementType.REQUIRES_STATEMENT, PsiRequiresStatement.EMPTY_ARRAY)); } else { return psiTraverser().children(this).filter(PsiRequiresStatement.class); } }
@NotNull @Override public Iterable<PsiPackageAccessibilityStatement> getExports() { PsiJavaModuleStub stub = getGreenStub(); if(stub != null) { return JBIterable.of(stub.getChildrenByType(JavaElementType.EXPORTS_STATEMENT, PsiPackageAccessibilityStatement.EMPTY_ARRAY)); } else { return psiTraverser().children(this).filter(PsiPackageAccessibilityStatement.class).filter(statement -> statement.getRole() == PsiPackageAccessibilityStatement.Role.EXPORTS); } }
@NotNull @Override public Iterable<PsiPackageAccessibilityStatement> getOpens() { PsiJavaModuleStub stub = getGreenStub(); if(stub != null) { return JBIterable.of(stub.getChildrenByType(JavaElementType.OPENS_STATEMENT, PsiPackageAccessibilityStatement.EMPTY_ARRAY)); } else { return psiTraverser().children(this).filter(PsiPackageAccessibilityStatement.class).filter(statement -> statement.getRole() == PsiPackageAccessibilityStatement.Role.OPENS); } }
@Nullable public static PsiElement getTopmostBlockInSameClass(@NotNull PsiElement position) { return JBIterable. generate(position, PsiElement::getParent). takeWhile(e -> !(e instanceof PsiMember || e instanceof PsiFile || e instanceof PsiLambdaExpression)). filter(e -> e instanceof PsiCodeBlock || e instanceof PsiExpression && e.getParent() instanceof PsiLambdaExpression). last(); }
@NotNull static List<HighlightInfo> checkUnusedServices(@NotNull PsiJavaModule module) { List<HighlightInfo> results = ContainerUtil.newSmartList(); Set<String> exports = JBIterable.from(module.getExports()).map(st -> refText(st.getPackageReference())).filter(Objects::nonNull).toSet(); Set<String> uses = JBIterable.from(module.getUses()).map(st -> refText(st.getClassReference())).filter(Objects::nonNull).toSet(); Module host = findModule(module); for(PsiProvidesStatement statement : module.getProvides()) { PsiJavaCodeReferenceElement ref = statement.getInterfaceReference(); if(ref != null) { PsiElement target = ref.resolve(); if(target instanceof PsiClass && findModule(target) == host) { String className = refText(ref), packageName = StringUtil.getPackageName(className); if(!exports.contains(packageName) && !uses.contains(className)) { String message = JavaErrorMessages.message("module.service.unused"); results.add(HighlightInfo.newHighlightInfo(HighlightInfoType.WARNING).range(range(ref)).descriptionAndTooltip(message).create()); } } } } return results; }
@NotNull private static String getClassNameWithContainers(@NotNull PsiClass psiClass) { String name = ObjectUtils.assertNotNull(psiClass.getName()); for(PsiClass parent : JBIterable.generate(psiClass, PsiClass::getContainingClass)) { name = parent.getName() + "." + name; } return name; }
@NotNull @Override public <C> JBIterable<C> getDbChildren(@NotNull Class<C> clazz, @NotNull ObjectKind kind) { return null; }
@NotNull @Override public JBIterable<? extends DasObject> getModelRoots() { return null; }