Search in sources :

Example 6 with NullableFunction

use of com.intellij.util.NullableFunction in project intellij-community by JetBrains.

the class FunctionalInterfaceSuggester method suggestFunctionalInterfaces.

private static <T extends PsiElement> Collection<? extends PsiType> suggestFunctionalInterfaces(@NotNull final T element, final NullableFunction<PsiClass, PsiType> acceptanceChecker) {
    final Project project = element.getProject();
    final Set<PsiType> types = new HashSet<>();
    final Processor<PsiMember> consumer = member -> {
        if (member instanceof PsiClass && Java15APIUsageInspectionBase.getLastIncompatibleLanguageLevel(member, PsiUtil.getLanguageLevel(element)) == null) {
            if (!JavaResolveUtil.isAccessible(member, null, member.getModifierList(), element, null, null)) {
                return true;
            }
            ContainerUtil.addIfNotNull(types, acceptanceChecker.fun((PsiClass) member));
        }
        return true;
    };
    final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    final GlobalSearchScope allScope = GlobalSearchScope.allScope(project);
    final PsiClass functionalInterfaceClass = psiFacade.findClass(CommonClassNames.JAVA_LANG_FUNCTIONAL_INTERFACE, allScope);
    if (functionalInterfaceClass != null) {
        AnnotatedMembersSearch.search(functionalInterfaceClass, element.getResolveScope()).forEach(consumer);
    }
    for (String functionalInterface : FUNCTIONAL_INTERFACES) {
        final PsiClass aClass = psiFacade.findClass(functionalInterface, allScope);
        if (aClass != null) {
            consumer.process(aClass);
        }
    }
    final ArrayList<PsiType> typesToSuggest = new ArrayList<>(types);
    Collections.sort(typesToSuggest, Comparator.comparing(PsiType::getCanonicalText));
    return typesToSuggest;
}
Also used : TypeConversionUtil(com.intellij.psi.util.TypeConversionUtil) java.util(java.util) NullableFunction(com.intellij.util.NullableFunction) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Java15APIUsageInspectionBase(com.intellij.codeInspection.java15api.Java15APIUsageInspectionBase) ContainerUtil(com.intellij.util.containers.ContainerUtil) Nullable(org.jetbrains.annotations.Nullable) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) AnnotatedMembersSearch(com.intellij.psi.search.searches.AnnotatedMembersSearch) Processor(com.intellij.util.Processor) Project(com.intellij.openapi.project.Project) JavaResolveUtil(com.intellij.psi.impl.source.resolve.JavaResolveUtil) PsiUtil(com.intellij.psi.util.PsiUtil) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope)

Example 7 with NullableFunction

use of com.intellij.util.NullableFunction in project intellij-plugins by JetBrains.

the class AllInDirectoryRunSettingsSection method getConfigsInDir.

@NotNull
private static List<String> getConfigsInDir(@NotNull final Project project, @NotNull String dirPath) {
    List<String> result = Collections.emptyList();
    File dir = new File(dirPath);
    if (!StringUtil.isEmpty(dirPath) && dir.isDirectory() && dir.isAbsolute()) {
        VirtualFile directoryVFile = LocalFileSystem.getInstance().findFileByIoFile(dir);
        if (directoryVFile != null) {
            List<VirtualFile> configs = JstdSettingsUtil.collectJstdConfigFilesInDirectory(project, directoryVFile);
            result = ContainerUtil.filter(ContainerUtil.map(configs, (NullableFunction<VirtualFile, String>) virtualFile -> ProjectRootUtils.getRootRelativePath(project, virtualFile.getPath())), Condition.NOT_NULL);
            Collections.sort(result);
        }
    }
    return result;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) UIUtil(com.intellij.util.ui.UIUtil) TextChangeListener(com.google.jstestdriver.idea.util.TextChangeListener) FileChooserDescriptorFactory(com.intellij.openapi.fileChooser.FileChooserDescriptorFactory) ArrayUtil(com.intellij.util.ArrayUtil) JstdSettingsUtil(com.google.jstestdriver.idea.execution.JstdSettingsUtil) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ProjectRootUtils(com.google.jstestdriver.idea.util.ProjectRootUtils) TextFieldWithBrowseButton(com.intellij.openapi.ui.TextFieldWithBrowseButton) ContainerUtil(com.intellij.util.containers.ContainerUtil) JBLabel(com.intellij.ui.components.JBLabel) JstdRunSettings(com.google.jstestdriver.idea.execution.settings.JstdRunSettings) Project(com.intellij.openapi.project.Project) SwingUtils(com.google.jstestdriver.idea.util.SwingUtils) JBList(com.intellij.ui.components.JBList) StringUtil(com.intellij.openapi.util.text.StringUtil) NullableFunction(com.intellij.util.NullableFunction) ListCellRendererWrapper(com.intellij.ui.ListCellRendererWrapper) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) File(java.io.File) java.awt(java.awt) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) ObjectUtils(com.intellij.util.ObjectUtils) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) JBColor(com.intellij.ui.JBColor) Condition(com.intellij.openapi.util.Condition) javax.swing(javax.swing) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Example 8 with NullableFunction

use of com.intellij.util.NullableFunction in project intellij-community by JetBrains.

the class GutterIconsConfigurable method createComponent.

@Nullable
@Override
public JComponent createComponent() {
    ExtensionPoint<LineMarkerProvider> point = Extensions.getRootArea().getExtensionPoint(LineMarkerProviders.EP_NAME);
    @SuppressWarnings("unchecked") LanguageExtensionPoint<LineMarkerProvider>[] extensions = (LanguageExtensionPoint<LineMarkerProvider>[]) point.getExtensions();
    NullableFunction<LanguageExtensionPoint<LineMarkerProvider>, PluginDescriptor> function = point1 -> {
        LineMarkerProvider instance = point1.getInstance();
        return instance instanceof LineMarkerProviderDescriptor && ((LineMarkerProviderDescriptor) instance).getName() != null ? point1.getPluginDescriptor() : null;
    };
    MultiMap<PluginDescriptor, LanguageExtensionPoint<LineMarkerProvider>> map = ContainerUtil.groupBy(Arrays.asList(extensions), function);
    Map<GutterIconDescriptor, PluginDescriptor> pluginDescriptorMap = ContainerUtil.newHashMap();
    Set<String> ids = new HashSet<>();
    myDescriptors = new ArrayList<>();
    for (final PluginDescriptor descriptor : map.keySet()) {
        Collection<LanguageExtensionPoint<LineMarkerProvider>> points = map.get(descriptor);
        for (LanguageExtensionPoint<LineMarkerProvider> extensionPoint : points) {
            GutterIconDescriptor instance = (GutterIconDescriptor) extensionPoint.getInstance();
            if (instance.getOptions().length > 0) {
                for (GutterIconDescriptor option : instance.getOptions()) {
                    if (ids.add(option.getId())) {
                        myDescriptors.add(option);
                    }
                    pluginDescriptorMap.put(option, descriptor);
                }
            } else {
                if (ids.add(instance.getId())) {
                    myDescriptors.add(instance);
                }
                pluginDescriptorMap.put(instance, descriptor);
            }
        }
    }
    /*
    List<GutterIconDescriptor> options = new ArrayList<GutterIconDescriptor>();
    for (Iterator<GutterIconDescriptor> iterator = myDescriptors.iterator(); iterator.hasNext(); ) {
      GutterIconDescriptor descriptor = iterator.next();
      if (descriptor.getOptions().length > 0) {
        options.addAll(Arrays.asList(descriptor.getOptions()));
        iterator.remove();
      }
    }
    myDescriptors.addAll(options);
    */
    myDescriptors.sort((o1, o2) -> {
        if (pluginDescriptorMap.get(o1) != pluginDescriptorMap.get(o2))
            return 0;
        return Comparing.compare(o1.getName(), o2.getName());
    });
    PluginDescriptor current = null;
    for (GutterIconDescriptor descriptor : myDescriptors) {
        PluginDescriptor pluginDescriptor = pluginDescriptorMap.get(descriptor);
        if (pluginDescriptor != current) {
            myFirstDescriptors.put(descriptor, pluginDescriptor);
            current = pluginDescriptor;
        }
    }
    myList.setItems(myDescriptors, GutterIconDescriptor::getName);
    myShowGutterIconsJBCheckBox.addChangeListener(e -> myList.setEnabled(myShowGutterIconsJBCheckBox.isSelected()));
    return myPanel;
}
Also used : java.util(java.util) ContainerUtil(com.intellij.util.containers.ContainerUtil) Nls(org.jetbrains.annotations.Nls) ProjectManager(com.intellij.openapi.project.ProjectManager) Comparing(com.intellij.openapi.util.Comparing) CheckBoxList(com.intellij.ui.CheckBoxList) EditorSettingsExternalizable(com.intellij.openapi.editor.ex.EditorSettingsExternalizable) Project(com.intellij.openapi.project.Project) HashSet(com.intellij.util.containers.hash.HashSet) ChangeListener(javax.swing.event.ChangeListener) MultiMap(com.intellij.util.containers.MultiMap) IdeaPluginDescriptor(com.intellij.ide.plugins.IdeaPluginDescriptor) Extensions(com.intellij.openapi.extensions.Extensions) EmptyIcon(com.intellij.util.ui.EmptyIcon) ExtensionPoint(com.intellij.openapi.extensions.ExtensionPoint) JBCheckBox(com.intellij.ui.components.JBCheckBox) NullableFunction(com.intellij.util.NullableFunction) Configurable(com.intellij.openapi.options.Configurable) SeparatorWithText(com.intellij.ui.SeparatorWithText) com.intellij.codeInsight.daemon(com.intellij.codeInsight.daemon) TestOnly(org.jetbrains.annotations.TestOnly) java.awt(java.awt) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) LanguageExtensionPoint(com.intellij.lang.LanguageExtensionPoint) PluginDescriptor(com.intellij.openapi.extensions.PluginDescriptor) ConfigurationException(com.intellij.openapi.options.ConfigurationException) NotNull(org.jetbrains.annotations.NotNull) javax.swing(javax.swing) LanguageExtensionPoint(com.intellij.lang.LanguageExtensionPoint) IdeaPluginDescriptor(com.intellij.ide.plugins.IdeaPluginDescriptor) PluginDescriptor(com.intellij.openapi.extensions.PluginDescriptor) HashSet(com.intellij.util.containers.hash.HashSet) Nullable(org.jetbrains.annotations.Nullable)

Example 9 with NullableFunction

use of com.intellij.util.NullableFunction in project intellij-community by JetBrains.

the class DfaPsiUtil method getVariableAssignmentsInFile.

@NotNull
public static Collection<PsiExpression> getVariableAssignmentsInFile(@NotNull PsiVariable psiVariable, final boolean literalsOnly, final PsiElement place) {
    Ref<Boolean> modificationRef = Ref.create(Boolean.FALSE);
    PsiElement codeBlock = place == null ? null : getTopmostBlockInSameClass(place);
    int placeOffset = codeBlock != null ? place.getTextRange().getStartOffset() : 0;
    PsiFile containingFile = psiVariable.getContainingFile();
    LocalSearchScope scope = new LocalSearchScope(new PsiElement[] { containingFile }, null, true);
    Collection<PsiReference> references = ReferencesSearch.search(psiVariable, scope).findAll();
    List<PsiExpression> list = ContainerUtil.mapNotNull(references, (NullableFunction<PsiReference, PsiExpression>) psiReference -> {
        if (modificationRef.get())
            return null;
        final PsiElement parent = psiReference.getElement().getParent();
        if (parent instanceof PsiAssignmentExpression) {
            final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression) parent;
            final IElementType operation = assignmentExpression.getOperationTokenType();
            if (assignmentExpression.getLExpression() == psiReference) {
                if (JavaTokenType.EQ.equals(operation)) {
                    final PsiExpression rValue = assignmentExpression.getRExpression();
                    if (!literalsOnly || allOperandsAreLiterals(rValue)) {
                        if (codeBlock != null && PsiTreeUtil.isAncestor(codeBlock, parent, true) && placeOffset < parent.getTextRange().getStartOffset()) {
                            return null;
                        }
                        return rValue;
                    } else {
                        modificationRef.set(Boolean.TRUE);
                    }
                } else if (JavaTokenType.PLUSEQ.equals(operation)) {
                    modificationRef.set(Boolean.TRUE);
                }
            }
        }
        return null;
    });
    if (modificationRef.get())
        return Collections.emptyList();
    PsiExpression initializer = psiVariable.getInitializer();
    if (initializer != null && (!literalsOnly || allOperandsAreLiterals(initializer))) {
        list = ContainerUtil.concat(list, Collections.singletonList(initializer));
    }
    return list;
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) JBIterable(com.intellij.util.containers.JBIterable) IElementType(com.intellij.psi.tree.IElementType) com.intellij.psi.util(com.intellij.psi.util) NullableFunction(com.intellij.util.NullableFunction) ContainerUtil(com.intellij.util.containers.ContainerUtil) NullableNotNullManager(com.intellij.codeInsight.NullableNotNullManager) Instruction(com.intellij.codeInspection.dataFlow.instructions.Instruction) ReturnInstruction(com.intellij.codeInspection.dataFlow.instructions.ReturnInstruction) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) Nullable(org.jetbrains.annotations.Nullable) Stack(com.intellij.util.containers.Stack) AnnotationUtil(com.intellij.codeInsight.AnnotationUtil) com.intellij.psi(com.intellij.psi) PsiJavaPatterns(com.intellij.patterns.PsiJavaPatterns) NotNull(org.jetbrains.annotations.NotNull) JavaLanguage(com.intellij.lang.java.JavaLanguage) Ref(com.intellij.openapi.util.Ref) MultiMap(com.intellij.util.containers.MultiMap) MethodCallInstruction(com.intellij.codeInspection.dataFlow.instructions.MethodCallInstruction) IElementType(com.intellij.psi.tree.IElementType) NotNull(org.jetbrains.annotations.NotNull)

Example 10 with NullableFunction

use of com.intellij.util.NullableFunction in project intellij-community by JetBrains.

the class LoadContextAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = getProject(e);
    assert project != null;
    DefaultActionGroup group = new DefaultActionGroup();
    final WorkingContextManager manager = WorkingContextManager.getInstance(project);
    List<ContextInfo> history = manager.getContextHistory();
    List<ContextHolder> infos = new ArrayList<>(ContainerUtil.map2List(history, (Function<ContextInfo, ContextHolder>) info -> new ContextHolder() {

        @Override
        void load(final boolean clear) {
            LoadContextUndoableAction undoableAction = LoadContextUndoableAction.createAction(manager, clear, info.name);
            UndoableCommand.execute(project, undoableAction, "Load context " + info.comment, "Context");
        }

        @Override
        void remove() {
            manager.removeContext(info.name);
        }

        @Override
        Date getDate() {
            return new Date(info.date);
        }

        @Override
        String getComment() {
            return info.comment;
        }

        @Override
        Icon getIcon() {
            return TasksIcons.SavedContext;
        }
    }));
    final TaskManager taskManager = TaskManager.getManager(project);
    List<LocalTask> tasks = taskManager.getLocalTasks();
    infos.addAll(ContainerUtil.mapNotNull(tasks, (NullableFunction<LocalTask, ContextHolder>) task -> {
        if (task.isActive()) {
            return null;
        }
        return new ContextHolder() {

            @Override
            void load(boolean clear) {
                LoadContextUndoableAction undoableAction = LoadContextUndoableAction.createAction(manager, clear, task);
                UndoableCommand.execute(project, undoableAction, "Load context " + TaskUtil.getTrimmedSummary(task), "Context");
            }

            @Override
            void remove() {
                SwitchTaskAction.removeTask(project, task, taskManager);
            }

            @Override
            Date getDate() {
                return task.getUpdated();
            }

            @Override
            String getComment() {
                return TaskUtil.getTrimmedSummary(task);
            }

            @Override
            Icon getIcon() {
                return task.getIcon();
            }
        };
    }));
    Collections.sort(infos, (o1, o2) -> o2.getDate().compareTo(o1.getDate()));
    final Ref<Boolean> shiftPressed = Ref.create(false);
    boolean today = true;
    Calendar now = Calendar.getInstance();
    for (int i = 0, historySize = Math.min(MAX_ROW_COUNT, infos.size()); i < historySize; i++) {
        final ContextHolder info = infos.get(i);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(info.getDate());
        if (today && (calendar.get(Calendar.YEAR) != now.get(Calendar.YEAR) || calendar.get(Calendar.DAY_OF_YEAR) != now.get(Calendar.DAY_OF_YEAR))) {
            group.addSeparator();
            today = false;
        }
        group.add(createItem(info, shiftPressed));
    }
    final ListPopupImpl popup = (ListPopupImpl) JBPopupFactory.getInstance().createActionGroupPopup("Load Context", group, e.getDataContext(), false, null, MAX_ROW_COUNT);
    popup.setAdText("Press SHIFT to merge with current context");
    popup.registerAction("shiftPressed", KeyStroke.getKeyStroke("shift pressed SHIFT"), new AbstractAction() {

        public void actionPerformed(ActionEvent e) {
            shiftPressed.set(true);
            popup.setCaption("Merge with Current Context");
        }
    });
    popup.registerAction("shiftReleased", KeyStroke.getKeyStroke("released SHIFT"), new AbstractAction() {

        public void actionPerformed(ActionEvent e) {
            shiftPressed.set(false);
            popup.setCaption("Load Context");
        }
    });
    popup.registerAction("invoke", KeyStroke.getKeyStroke("shift ENTER"), new AbstractAction() {

        public void actionPerformed(ActionEvent e) {
            popup.handleSelect(true);
        }
    });
    popup.addPopupListener(new JBPopupAdapter() {

        @Override
        public void onClosed(LightweightWindowEvent event) {
        }
    });
    popup.showCenteredInCurrentWindow(project);
}
Also used : ActionEvent(java.awt.event.ActionEvent) LightweightWindowEvent(com.intellij.openapi.ui.popup.LightweightWindowEvent) NullableFunction(com.intellij.util.NullableFunction) Function(com.intellij.util.Function) ContextInfo(com.intellij.tasks.context.ContextInfo) WorkingContextManager(com.intellij.tasks.context.WorkingContextManager) LocalTask(com.intellij.tasks.LocalTask) NullableFunction(com.intellij.util.NullableFunction) Project(com.intellij.openapi.project.Project) LoadContextUndoableAction(com.intellij.tasks.context.LoadContextUndoableAction) TaskManager(com.intellij.tasks.TaskManager) ListPopupImpl(com.intellij.ui.popup.list.ListPopupImpl) JBPopupAdapter(com.intellij.openapi.ui.popup.JBPopupAdapter)

Aggregations

NullableFunction (com.intellij.util.NullableFunction)19 NotNull (org.jetbrains.annotations.NotNull)17 ContainerUtil (com.intellij.util.containers.ContainerUtil)15 Nullable (org.jetbrains.annotations.Nullable)13 List (java.util.List)12 Project (com.intellij.openapi.project.Project)11 StringUtil (com.intellij.openapi.util.text.StringUtil)7 Logger (com.intellij.openapi.diagnostic.Logger)6 java.util (java.util)6 Collections (java.util.Collections)6 Comparing (com.intellij.openapi.util.Comparing)5 VirtualFile (com.intellij.openapi.vfs.VirtualFile)5 com.intellij.psi (com.intellij.psi)5 java.awt (java.awt)5 javax.swing (javax.swing)5 ArrayList (java.util.ArrayList)4 Extensions (com.intellij.openapi.extensions.Extensions)3 Ref (com.intellij.openapi.util.Ref)3 PsiFile (com.intellij.psi.PsiFile)3 ActionEvent (java.awt.event.ActionEvent)3