Search in sources :

Example 11 with Condition

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

the class TreeFileChooserDialog method filterFiles.

private Object[] filterFiles(final Object[] list) {
    Condition<PsiFile> condition = psiFile -> {
        if (myFilter != null && !myFilter.accept(psiFile)) {
            return false;
        }
        boolean accepted = myFileType == null || psiFile.getFileType() == myFileType;
        VirtualFile virtualFile = psiFile.getVirtualFile();
        if (virtualFile != null && !accepted) {
            accepted = virtualFile.getFileType() == myFileType;
        }
        return accepted;
    };
    final List<Object> result = new ArrayList<>(list.length);
    for (Object o : list) {
        final PsiFile psiFile;
        if (o instanceof PsiFile) {
            psiFile = (PsiFile) o;
        } else if (o instanceof PsiFileNode) {
            psiFile = ((PsiFileNode) o).getValue();
        } else {
            psiFile = null;
        }
        if (psiFile != null && !condition.value(psiFile)) {
            continue;
        } else {
            if (o instanceof ProjectViewNode) {
                final ProjectViewNode projectViewNode = (ProjectViewNode) o;
                if (!projectViewNode.canHaveChildrenMatching(condition)) {
                    continue;
                }
            }
        }
        result.add(o);
    }
    return ArrayUtil.toObjectArray(result);
}
Also used : UIUtil(com.intellij.util.ui.UIUtil) FileTypeIndex(com.intellij.psi.search.FileTypeIndex) BaseProjectTreeBuilder(com.intellij.ide.projectView.BaseProjectTreeBuilder) ProjectTreeBuilder(com.intellij.ide.projectView.impl.ProjectTreeBuilder) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ModalityState(com.intellij.openapi.application.ModalityState) THashSet(gnu.trove.THashSet) ChooseByNamePopupComponent(com.intellij.ide.util.gotoByName.ChooseByNamePopupComponent) ChooseByNamePanel(com.intellij.ide.util.gotoByName.ChooseByNamePanel) PsiManager(com.intellij.psi.PsiManager) TreeSpeedSearch(com.intellij.ui.TreeSpeedSearch) ProjectAbstractTreeStructureBase(com.intellij.ide.projectView.impl.ProjectAbstractTreeStructureBase) JBUI(com.intellij.util.ui.JBUI) Disposer(com.intellij.openapi.util.Disposer) ChangeListener(javax.swing.event.ChangeListener) PsiFileNode(com.intellij.ide.projectView.impl.nodes.PsiFileNode) AbstractProjectTreeStructure(com.intellij.ide.projectView.impl.AbstractProjectTreeStructure) DefaultTreeModel(javax.swing.tree.DefaultTreeModel) ChangeEvent(javax.swing.event.ChangeEvent) TreePath(javax.swing.tree.TreePath) GotoFileCellRenderer(com.intellij.ide.util.gotoByName.GotoFileCellRenderer) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) KeyEvent(java.awt.event.KeyEvent) DoubleClickListener(com.intellij.ui.DoubleClickListener) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) IdeBundle(com.intellij.ide.IdeBundle) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Function(com.intellij.util.Function) ApplicationManager(com.intellij.openapi.application.ApplicationManager) WindowManagerEx(com.intellij.openapi.wm.ex.WindowManagerEx) NotNull(org.jetbrains.annotations.NotNull) TabbedPaneWrapper(com.intellij.ui.TabbedPaneWrapper) TreeStructureProvider(com.intellij.ide.projectView.TreeStructureProvider) java.util(java.util) ArrayUtil(com.intellij.util.ArrayUtil) FilenameIndex(com.intellij.psi.search.FilenameIndex) ContainerUtil(com.intellij.util.containers.ContainerUtil) KeyAdapter(java.awt.event.KeyAdapter) NodeRenderer(com.intellij.ide.util.treeView.NodeRenderer) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent) ChooseByNameModel(com.intellij.ide.util.gotoByName.ChooseByNameModel) TreeSelectionListener(javax.swing.event.TreeSelectionListener) DialogWrapper(com.intellij.openapi.ui.DialogWrapper) PsiElement(com.intellij.psi.PsiElement) AlphaComparator(com.intellij.ide.util.treeView.AlphaComparator) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) Tree(com.intellij.ui.treeStructure.Tree) DumbAware(com.intellij.openapi.project.DumbAware) ProjectViewNode(com.intellij.ide.projectView.ProjectViewNode) FileType(com.intellij.openapi.fileTypes.FileType) TreeSelectionModel(javax.swing.tree.TreeSelectionModel) MouseEvent(java.awt.event.MouseEvent) java.awt(java.awt) Condition(com.intellij.openapi.util.Condition) ScrollPaneFactory(com.intellij.ui.ScrollPaneFactory) javax.swing(javax.swing) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFileNode(com.intellij.ide.projectView.impl.nodes.PsiFileNode) ProjectViewNode(com.intellij.ide.projectView.ProjectViewNode) PsiFile(com.intellij.psi.PsiFile)

Example 12 with Condition

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

the class FindDialog method createGlobalScopePanel.

@NotNull
private JComponent createGlobalScopePanel() {
    JPanel scopePanel = new JPanel();
    scopePanel.setLayout(new GridBagLayout());
    scopePanel.setBorder(IdeBorderFactory.createTitledBorder(FindBundle.message("find.scope.group"), true));
    GridBagConstraints gbConstraints = new GridBagConstraints();
    gbConstraints.fill = GridBagConstraints.HORIZONTAL;
    gbConstraints.anchor = GridBagConstraints.WEST;
    gbConstraints.gridx = 0;
    gbConstraints.gridy = 0;
    gbConstraints.gridwidth = 3;
    gbConstraints.weightx = 1;
    final boolean canAttach = ProjectAttachProcessor.canAttachToProject();
    myRbProject = new JRadioButton(canAttach ? FindBundle.message("find.scope.all.projects.radio") : FindBundle.message("find.scope.whole.project.radio"), true);
    scopePanel.add(myRbProject, gbConstraints);
    ItemListener resultsPreviewUpdateListener = new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            scheduleResultsUpdate();
        }
    };
    myRbProject.addItemListener(resultsPreviewUpdateListener);
    gbConstraints.gridx = 0;
    gbConstraints.gridy++;
    gbConstraints.weightx = 0;
    gbConstraints.gridwidth = 1;
    myRbModule = new JRadioButton(canAttach ? FindBundle.message("find.scope.project.radio") : FindBundle.message("find.scope.module.radio"), false);
    scopePanel.add(myRbModule, gbConstraints);
    myRbModule.addItemListener(resultsPreviewUpdateListener);
    gbConstraints.gridx = 1;
    gbConstraints.gridwidth = 2;
    gbConstraints.weightx = 1;
    Module[] modules = ModuleManager.getInstance(myProject).getModules();
    String[] names = new String[modules.length];
    for (int i = 0; i < modules.length; i++) {
        names[i] = modules[i].getName();
    }
    Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
    myModuleComboBox = new ComboBox(names);
    myModuleComboBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            scheduleResultsUpdate();
        }
    });
    scopePanel.add(myModuleComboBox, gbConstraints);
    if (modules.length == 1) {
        myModuleComboBox.setVisible(false);
        myRbModule.setVisible(false);
    }
    gbConstraints.gridx = 0;
    gbConstraints.gridy++;
    gbConstraints.weightx = 0;
    gbConstraints.gridwidth = 1;
    myRbDirectory = new JRadioButton(FindBundle.message("find.scope.directory.radio"), false);
    scopePanel.add(myRbDirectory, gbConstraints);
    myRbDirectory.addItemListener(resultsPreviewUpdateListener);
    gbConstraints.gridx = 1;
    gbConstraints.weightx = 1;
    myDirectoryComboBox = new ComboBox(200);
    Component editorComponent = myDirectoryComboBox.getEditor().getEditorComponent();
    if (editorComponent instanceof JTextField) {
        JTextField field = (JTextField) editorComponent;
        field.setColumns(40);
    }
    initCombobox(myDirectoryComboBox);
    myDirectoryComboBox.setSwingPopup(false);
    myDirectoryComboBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            scheduleResultsUpdate();
        }
    });
    scopePanel.add(myDirectoryComboBox, gbConstraints);
    gbConstraints.weightx = 0;
    gbConstraints.gridx = 2;
    mySelectDirectoryButton = new FixedSizeButton(myDirectoryComboBox);
    TextFieldWithBrowseButton.MyDoClickAction.addTo(mySelectDirectoryButton, myDirectoryComboBox);
    mySelectDirectoryButton.setMargin(new Insets(0, 0, 0, 0));
    scopePanel.add(mySelectDirectoryButton, gbConstraints);
    gbConstraints.gridx = 0;
    gbConstraints.gridy++;
    gbConstraints.weightx = 1;
    gbConstraints.gridwidth = 3;
    gbConstraints.insets = new Insets(0, 16, 0, 0);
    myCbWithSubdirectories = createCheckbox(true, FindBundle.message("find.scope.directory.recursive.checkbox"));
    myCbWithSubdirectories.setSelected(true);
    myCbWithSubdirectories.addItemListener(resultsPreviewUpdateListener);
    scopePanel.add(myCbWithSubdirectories, gbConstraints);
    gbConstraints.gridx = 0;
    gbConstraints.gridy++;
    gbConstraints.weightx = 0;
    gbConstraints.gridwidth = 1;
    gbConstraints.insets = new Insets(0, 0, 0, 0);
    myRbCustomScope = new JRadioButton(FindBundle.message("find.scope.custom.radio"), false);
    scopePanel.add(myRbCustomScope, gbConstraints);
    gbConstraints.gridx++;
    gbConstraints.weightx = 1;
    gbConstraints.gridwidth = 2;
    myScopeCombo = new ScopeChooserCombo();
    myScopeCombo.init(myProject, true, true, FindSettings.getInstance().getDefaultScopeName(), new Condition<ScopeDescriptor>() {

        //final String projectFilesScopeName = PsiBundle.message("psi.search.scope.project");
        private final String moduleFilesScopeName;

        {
            String moduleScopeName = PsiBundle.message("search.scope.module", "");
            final int ind = moduleScopeName.indexOf(' ');
            moduleFilesScopeName = moduleScopeName.substring(0, ind + 1);
        }

        @Override
        public boolean value(ScopeDescriptor descriptor) {
            final String display = descriptor.getDisplay();
            return /*!projectFilesScopeName.equals(display) &&*/
            !display.startsWith(moduleFilesScopeName);
        }
    });
    myScopeCombo.getComboBox().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            scheduleResultsUpdate();
        }
    });
    myRbCustomScope.addItemListener(resultsPreviewUpdateListener);
    Disposer.register(myDisposable, myScopeCombo);
    scopePanel.add(myScopeCombo, gbConstraints);
    ButtonGroup bgScope = new ButtonGroup();
    bgScope.add(myRbProject);
    bgScope.add(myRbModule);
    bgScope.add(myRbDirectory);
    bgScope.add(myRbCustomScope);
    myRbProject.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            validateScopeControls();
            validateFindButton();
        }
    });
    myRbCustomScope.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            validateScopeControls();
            validateFindButton();
            myScopeCombo.getComboBox().requestFocusInWindow();
        }
    });
    myRbDirectory.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            validateScopeControls();
            validateFindButton();
            myDirectoryComboBox.getEditor().getEditorComponent().requestFocusInWindow();
        }
    });
    myRbModule.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            validateScopeControls();
            validateFindButton();
            myModuleComboBox.requestFocusInWindow();
        }
    });
    mySelectDirectoryButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
            FileChooser.chooseFiles(descriptor, myProject, null, files -> myDirectoryComboBox.setSelectedItem(files.get(0).getPresentableUrl()));
        }
    });
    return scopePanel;
}
Also used : Language(com.intellij.lang.Language) FileUtilRt(com.intellij.openapi.util.io.FileUtilRt) UIUtil(com.intellij.util.ui.UIUtil) ReadTask(com.intellij.openapi.progress.util.ReadTask) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ModalityState(com.intellij.openapi.application.ModalityState) Document(com.intellij.openapi.editor.Document) UniqueVFilePathBuilder(com.intellij.openapi.fileEditor.UniqueVFilePathBuilder) ScopeDescriptor(com.intellij.ide.util.scopeChooser.ScopeDescriptor) DocumentEvent(com.intellij.openapi.editor.event.DocumentEvent) TableCellRenderer(javax.swing.table.TableCellRenderer) SmartList(com.intellij.util.SmartList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JBUI(com.intellij.util.ui.JBUI) Disposer(com.intellij.openapi.util.Disposer) DocumentAdapter(com.intellij.openapi.editor.event.DocumentAdapter) FileChooserDescriptor(com.intellij.openapi.fileChooser.FileChooserDescriptor) Logger(com.intellij.openapi.diagnostic.Logger) Module(com.intellij.openapi.module.Module) ListSelectionEvent(javax.swing.event.ListSelectionEvent) PatternSyntaxException(java.util.regex.PatternSyntaxException) ModuleUtilCore(com.intellij.openapi.module.ModuleUtilCore) DefaultTableModel(javax.swing.table.DefaultTableModel) PlainTextFileType(com.intellij.openapi.fileTypes.PlainTextFileType) com.intellij.ui(com.intellij.ui) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) JBScrollPane(com.intellij.ui.components.JBScrollPane) HelpManager(com.intellij.openapi.help.HelpManager) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) java.awt.event(java.awt.event) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Registry(com.intellij.openapi.util.registry.Registry) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) PsiBundle(com.intellij.psi.PsiBundle) FileChooserDescriptorFactory(com.intellij.openapi.fileChooser.FileChooserDescriptorFactory) ProgressIndicatorBase(com.intellij.openapi.progress.util.ProgressIndicatorBase) java.util(java.util) PsiFileFactory(com.intellij.psi.PsiFileFactory) ArrayUtil(com.intellij.util.ArrayUtil) ModuleManager(com.intellij.openapi.module.ModuleManager) UsageInfo(com.intellij.usageView.UsageInfo) ProgressIndicatorUtils(com.intellij.openapi.progress.util.ProgressIndicatorUtils) SearchScope(com.intellij.psi.search.SearchScope) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) Comparing(com.intellij.openapi.util.Comparing) STYLE_PLAIN(com.intellij.ui.SimpleTextAttributes.STYLE_PLAIN) CommonBundle(com.intellij.CommonBundle) UsagePreviewPanel(com.intellij.usages.impl.UsagePreviewPanel) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) PropertyKey(org.jetbrains.annotations.PropertyKey) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) StringUtil(com.intellij.openapi.util.text.StringUtil) com.intellij.usages(com.intellij.usages) Convertor(com.intellij.util.containers.Convertor) com.intellij.find(com.intellij.find) FileType(com.intellij.openapi.fileTypes.FileType) ProjectAttachProcessor(com.intellij.projectImport.ProjectAttachProcessor) JTextComponent(javax.swing.text.JTextComponent) Disposable(com.intellij.openapi.Disposable) java.awt(java.awt) com.intellij.openapi.actionSystem(com.intellij.openapi.actionSystem) JBTable(com.intellij.ui.table.JBTable) DumbAwareAction(com.intellij.openapi.project.DumbAwareAction) LanguageFileType(com.intellij.openapi.fileTypes.LanguageFileType) ScopeChooserCombo(com.intellij.ide.util.scopeChooser.ScopeChooserCombo) com.intellij.openapi.ui(com.intellij.openapi.ui) ShowUsagesAction(com.intellij.find.actions.ShowUsagesAction) UsageViewBundle(com.intellij.usageView.UsageViewBundle) ListSelectionListener(javax.swing.event.ListSelectionListener) FileChooser(com.intellij.openapi.fileChooser.FileChooser) TransactionGuard(com.intellij.openapi.application.TransactionGuard) Condition(com.intellij.openapi.util.Condition) Alarm(com.intellij.util.Alarm) javax.swing(javax.swing) ScopeChooserCombo(com.intellij.ide.util.scopeChooser.ScopeChooserCombo) JTextComponent(javax.swing.text.JTextComponent) ScopeDescriptor(com.intellij.ide.util.scopeChooser.ScopeDescriptor) FileChooserDescriptor(com.intellij.openapi.fileChooser.FileChooserDescriptor) Module(com.intellij.openapi.module.Module) NotNull(org.jetbrains.annotations.NotNull)

Example 13 with Condition

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

the class PostfixLiveTemplate method createIsApplicationTemplateFunction.

private static Condition<PostfixTemplate> createIsApplicationTemplateFunction(@NotNull final PostfixTemplateProvider provider, @NotNull String key, @NotNull PsiFile file, @NotNull Editor editor) {
    int currentOffset = editor.getCaretModel().getOffset();
    final int newOffset = currentOffset - key.length();
    CharSequence fileContent = editor.getDocument().getCharsSequence();
    StringBuilder fileContentWithoutKey = new StringBuilder();
    fileContentWithoutKey.append(fileContent.subSequence(0, newOffset));
    fileContentWithoutKey.append(fileContent.subSequence(currentOffset, fileContent.length()));
    PsiFile copyFile = copyFile(file, fileContentWithoutKey);
    Document copyDocument = copyFile.getViewProvider().getDocument();
    if (copyDocument == null) {
        return Conditions.alwaysFalse();
    }
    copyFile = provider.preCheck(copyFile, editor, newOffset);
    copyDocument = copyFile.getViewProvider().getDocument();
    if (copyDocument == null) {
        return Conditions.alwaysFalse();
    }
    final PsiElement context = CustomTemplateCallback.getContext(copyFile, positiveOffset(newOffset));
    final Document finalCopyDocument = copyDocument;
    return template -> template != null && template.isEnabled(provider) && template.isApplicable(context, finalCopyDocument, newOffset);
}
Also used : Language(com.intellij.lang.Language) PsiFileImpl(com.intellij.psi.impl.source.PsiFileImpl) PsiFileFactory(com.intellij.psi.PsiFileFactory) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) ContainerUtil(com.intellij.util.containers.ContainerUtil) CustomLiveTemplateBase(com.intellij.codeInsight.template.CustomLiveTemplateBase) TemplateLanguageUtil(com.intellij.psi.templateLanguages.TemplateLanguageUtil) PsiElement(com.intellij.psi.PsiElement) FeatureUsageTracker(com.intellij.featureStatistics.FeatureUsageTracker) PsiFile(com.intellij.psi.PsiFile) Conditions(com.intellij.openapi.util.Conditions) Logger(com.intellij.openapi.diagnostic.Logger) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) AttachmentFactory(com.intellij.diagnostic.AttachmentFactory) StringUtil(com.intellij.openapi.util.text.StringUtil) Collection(java.util.Collection) CustomLiveTemplateLookupElement(com.intellij.codeInsight.template.impl.CustomLiveTemplateLookupElement) Set(java.util.Set) UndoConstants(com.intellij.openapi.command.undo.UndoConstants) Editor(com.intellij.openapi.editor.Editor) Sets(com.google.common.collect.Sets) CustomTemplateCallback(com.intellij.codeInsight.template.CustomTemplateCallback) PostfixTemplateLookupElement(com.intellij.codeInsight.template.postfix.completion.PostfixTemplateLookupElement) CommandProcessor(com.intellij.openapi.command.CommandProcessor) Nullable(org.jetbrains.annotations.Nullable) PsiUtilCore(com.intellij.psi.util.PsiUtilCore) TemplateSettings(com.intellij.codeInsight.template.impl.TemplateSettings) PostfixTemplatesSettings(com.intellij.codeInsight.template.postfix.settings.PostfixTemplatesSettings) ApplicationManager(com.intellij.openapi.application.ApplicationManager) NotNull(org.jetbrains.annotations.NotNull) Condition(com.intellij.openapi.util.Condition) PsiFile(com.intellij.psi.PsiFile) Document(com.intellij.openapi.editor.Document) PsiElement(com.intellij.psi.PsiElement)

Example 14 with Condition

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

the class ProjectStartupConfigurable method createNewWrapper.

private ChooseRunConfigurationPopup.ItemWrapper<Void> createNewWrapper(final AnActionButton button) {
    return new ChooseRunConfigurationPopup.ItemWrapper<Void>(null) {

        @Override
        public Icon getIcon() {
            return IconUtil.getAddIcon();
        }

        @Override
        public String getText() {
            return UIUtil.removeMnemonic(ExecutionBundle.message("add.new.run.configuration.acrtion.name"));
        }

        @Override
        public void perform(@NotNull final Project project, @NotNull final Executor executor, @NotNull DataContext context) {
            final RunManagerImpl runManager = RunManagerImpl.getInstanceImpl(project);
            final ConfigurationType[] factories = runManager.getConfigurationFactories();
            final Condition<ConfigurationType> filter = new Condition<ConfigurationType>() {

                private final RunnerRegistry myRegistry = RunnerRegistry.getInstance();

                @Override
                public boolean value(ConfigurationType configurationType) {
                    ConfigurationFactory factory;
                    return !UnknownConfigurationType.INSTANCE.equals(configurationType) && ((factory = runManager.getFactory(configurationType.getId(), null)) != null) && myRegistry.getRunner(executor.getId(), runManager.getConfigurationTemplate(factory).getConfiguration()) != null;
                }
            };
            final List<ConfigurationType> factoriesList = ContainerUtil.filter(Arrays.asList(factories), filter);
            final ListPopup popup = NewRunConfigurationPopup.createAddPopup(factoriesList, "", factory -> ApplicationManager.getApplication().invokeLater(() -> {
                final EditConfigurationsDialog dialog = new EditConfigurationsDialog(project, factory);
                if (dialog.showAndGet()) {
                    ApplicationManager.getApplication().invokeLater(() -> {
                        RunnerAndConfigurationSettings configuration = RunManager.getInstance(project).getSelectedConfiguration();
                        if (configuration != null) {
                            addConfiguration(configuration);
                        }
                    }, ModalityState.any(), project.getDisposed());
                }
            }, ModalityState.any(), project.getDisposed()), null, EmptyRunnable.getInstance(), false);
            showPopup(button, popup);
        }

        @Override
        public boolean available(Executor executor) {
            return true;
        }
    };
}
Also used : ConfigurationType(com.intellij.execution.configurations.ConfigurationType) UnknownConfigurationType(com.intellij.execution.configurations.UnknownConfigurationType) Condition(com.intellij.openapi.util.Condition) EditConfigurationsDialog(com.intellij.execution.impl.EditConfigurationsDialog) ListPopup(com.intellij.openapi.ui.popup.ListPopup) NotNull(org.jetbrains.annotations.NotNull) Project(com.intellij.openapi.project.Project) DataContext(com.intellij.openapi.actionSystem.DataContext) DefaultRunExecutor(com.intellij.execution.executors.DefaultRunExecutor) ConfigurationFactory(com.intellij.execution.configurations.ConfigurationFactory) RunManagerImpl(com.intellij.execution.impl.RunManagerImpl)

Example 15 with Condition

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

the class JavaClassNameCompletionContributor method addAllClasses.

public static void addAllClasses(@NotNull CompletionParameters parameters, final boolean filterByScope, @NotNull final PrefixMatcher matcher, @NotNull final Consumer<LookupElement> consumer) {
    final PsiElement insertedElement = parameters.getPosition();
    if (JavaCompletionContributor.ANNOTATION_NAME.accepts(insertedElement)) {
        MultiMap<String, PsiClass> annoMap = getAllAnnotationClasses(insertedElement, matcher);
        Processor<PsiClass> processor = new LimitedAccessibleClassPreprocessor(parameters, filterByScope, anno -> {
            JavaPsiClassReferenceElement item = AllClassesGetter.createLookupItem(anno, JAVA_CLASS_INSERT_HANDLER);
            item.addLookupStrings(getClassNameWithContainers(anno));
            consumer.consume(item);
        });
        for (String name : CompletionUtil.sortMatching(matcher, annoMap.keySet())) {
            if (!ContainerUtil.process(annoMap.get(name), processor))
                break;
        }
        return;
    }
    final ElementFilter filter = IN_EXTENDS_IMPLEMENTS.accepts(insertedElement) ? new ExcludeDeclaredFilter(new ClassFilter(PsiClass.class)) : IN_TYPE_PARAMETER.accepts(insertedElement) ? new ExcludeDeclaredFilter(new ClassFilter(PsiTypeParameter.class)) : TrueFilter.INSTANCE;
    final boolean inJavaContext = parameters.getPosition() instanceof PsiIdentifier;
    final boolean afterNew = AFTER_NEW.accepts(insertedElement);
    if (afterNew) {
        final PsiExpression expr = PsiTreeUtil.getContextOfType(insertedElement, PsiExpression.class, true);
        for (final ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(expr, true)) {
            final PsiType type = info.getType();
            final PsiClass psiClass = PsiUtil.resolveClassInType(type);
            if (psiClass != null && psiClass.getName() != null) {
                consumer.consume(createClassLookupItem(psiClass, inJavaContext));
            }
            final PsiType defaultType = info.getDefaultType();
            if (!defaultType.equals(type)) {
                final PsiClass defClass = PsiUtil.resolveClassInType(defaultType);
                if (defClass != null && defClass.getName() != null) {
                    consumer.consume(createClassLookupItem(defClass, true));
                }
            }
        }
    }
    final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
    AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {

        @Override
        public void consume(PsiClass psiClass) {
            processClass(psiClass, null, "");
        }

        private void processClass(PsiClass psiClass, @Nullable Set<PsiClass> visited, String prefix) {
            boolean isInnerClass = StringUtil.isNotEmpty(prefix);
            if (isInnerClass && isProcessedIndependently(psiClass)) {
                return;
            }
            if (filter.isAcceptable(psiClass, insertedElement)) {
                if (!inJavaContext) {
                    JavaPsiClassReferenceElement element = AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING);
                    element.setLookupString(prefix + element.getLookupString());
                    consumer.consume(element);
                } else {
                    Condition<PsiClass> condition = eachClass -> filter.isAcceptable(eachClass, insertedElement) && AllClassesGetter.isAcceptableInContext(insertedElement, eachClass, filterByScope, pkgContext);
                    for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew, JAVA_CLASS_INSERT_HANDLER, condition)) {
                        element.setLookupString(prefix + element.getLookupString());
                        JavaConstructorCallElement.wrap(element, insertedElement).forEach(consumer::consume);
                    }
                }
            } else {
                String name = psiClass.getName();
                if (name != null) {
                    PsiClass[] innerClasses = psiClass.getInnerClasses();
                    if (innerClasses.length > 0) {
                        if (visited == null)
                            visited = ContainerUtil.newHashSet();
                        for (PsiClass innerClass : innerClasses) {
                            if (visited.add(innerClass)) {
                                processClass(innerClass, visited, prefix + name + ".");
                            }
                        }
                    }
                }
            }
        }

        private boolean isProcessedIndependently(PsiClass psiClass) {
            String innerName = psiClass.getName();
            return innerName != null && matcher.prefixMatches(innerName);
        }
    });
}
Also used : Condition(com.intellij.openapi.util.Condition) ExcludeDeclaredFilter(com.intellij.psi.filters.element.ExcludeDeclaredFilter) ExpectedTypeInfo(com.intellij.codeInsight.ExpectedTypeInfo) ClassFilter(com.intellij.psi.filters.ClassFilter) ElementFilter(com.intellij.psi.filters.ElementFilter)

Aggregations

Condition (com.intellij.openapi.util.Condition)48 NotNull (org.jetbrains.annotations.NotNull)26 Nullable (org.jetbrains.annotations.Nullable)23 Project (com.intellij.openapi.project.Project)21 VirtualFile (com.intellij.openapi.vfs.VirtualFile)21 List (java.util.List)16 StringUtil (com.intellij.openapi.util.text.StringUtil)15 ContainerUtil (com.intellij.util.containers.ContainerUtil)14 javax.swing (javax.swing)13 PsiElement (com.intellij.psi.PsiElement)11 Module (com.intellij.openapi.module.Module)10 java.util (java.util)10 Logger (com.intellij.openapi.diagnostic.Logger)9 ApplicationManager (com.intellij.openapi.application.ApplicationManager)8 NonNls (org.jetbrains.annotations.NonNls)8 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)7 Collection (java.util.Collection)7 ModalityState (com.intellij.openapi.application.ModalityState)6 Document (com.intellij.openapi.editor.Document)6 DialogWrapper (com.intellij.openapi.ui.DialogWrapper)6