Search in sources :

Example 1 with MemberChooser

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

the class DefineParamsDefaultValueAction method getParams.

@Nullable
protected PsiParameter[] getParams(PsiElement element) {
    final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
    assert method != null;
    final PsiParameter[] parameters = method.getParameterList().getParameters();
    if (parameters.length == 1) {
        return parameters;
    }
    final ParameterClassMember[] members = new ParameterClassMember[parameters.length];
    for (int i = 0; i < members.length; i++) {
        members[i] = new ParameterClassMember(parameters[i]);
    }
    final PsiParameter selectedParam = PsiTreeUtil.getParentOfType(element, PsiParameter.class);
    final int idx = selectedParam != null ? ArrayUtil.find(parameters, selectedParam) : -1;
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        return idx >= 0 ? new PsiParameter[] { selectedParam } : null;
    }
    final MemberChooser<ParameterClassMember> chooser = new MemberChooser<>(members, false, true, element.getProject());
    if (idx >= 0) {
        chooser.selectElements(new ClassMember[] { members[idx] });
    } else {
        chooser.selectElements(members);
    }
    chooser.setTitle("Choose Default Value Parameters");
    chooser.setCopyJavadocVisible(false);
    if (chooser.showAndGet()) {
        final List<ParameterClassMember> elements = chooser.getSelectedElements();
        if (elements != null) {
            PsiParameter[] params = new PsiParameter[elements.size()];
            for (int i = 0; i < params.length; i++) {
                params[i] = elements.get(i).getParameter();
            }
            return params;
        }
    }
    return null;
}
Also used : ParameterClassMember(com.intellij.codeInsight.intention.impl.ParameterClassMember) MemberChooser(com.intellij.ide.util.MemberChooser) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with MemberChooser

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

the class BaseDartGenerateHandler method invoke.

public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file, final int offset) {
    final DartClass dartClass = PsiTreeUtil.getParentOfType(file.findElementAt(offset), DartClassDefinition.class);
    if (dartClass == null)
        return;
    final List<DartComponent> candidates = new ArrayList<>();
    collectCandidates(dartClass, candidates);
    List<DartNamedElementNode> selectedElements = Collections.emptyList();
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        selectedElements = ContainerUtil.map(candidates, DartNamedElementNode::new);
    } else if (!candidates.isEmpty()) {
        final MemberChooser<DartNamedElementNode> chooser = createMemberChooserDialog(project, dartClass, candidates, getTitle());
        chooser.show();
        if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE)
            return;
        selectedElements = chooser.getSelectedElements();
    }
    doInvoke(project, editor, file, selectedElements, createFix(dartClass));
}
Also used : DartClass(com.jetbrains.lang.dart.psi.DartClass) DartComponent(com.jetbrains.lang.dart.psi.DartComponent) DartNamedElementNode(com.jetbrains.lang.dart.ide.DartNamedElementNode) MemberChooser(com.intellij.ide.util.MemberChooser)

Example 3 with MemberChooser

use of com.intellij.ide.util.MemberChooser in project Perl5-IDEA by Camelcade.

the class PerlCodeGeneratorImpl method generateOverrideMethod.

@Override
public void generateOverrideMethod(PsiElement anchor, Editor editor) {
    if (anchor != null) {
        final List<PerlMethodMember> subDefinitions = new ArrayList<>();
        PerlPackageUtil.processNotOverridedMethods(PsiTreeUtil.getParentOfType(anchor, PerlNamespaceDefinitionElement.class), subDefinitionBase -> {
            subDefinitions.add(new PerlMethodMember(subDefinitionBase));
            return true;
        });
        final MemberChooser<PerlMethodMember> chooser = new MemberChooser<PerlMethodMember>(subDefinitions.toArray(new PerlMethodMember[subDefinitions.size()]), false, true, anchor.getProject()) {

            @Override
            protected SpeedSearchComparator getSpeedSearchComparator() {
                return new SpeedSearchComparator(false) {

                    @Nullable
                    @Override
                    public Iterable<TextRange> matchingFragments(@NotNull String pattern, @NotNull String text) {
                        return super.matchingFragments(PerlMethodMember.trimUnderscores(pattern), text);
                    }
                };
            }

            @Override
            protected ShowContainersAction getShowContainersAction() {
                return new ShowContainersAction(IdeBundle.message("action.show.classes"), PerlIcons.PACKAGE_GUTTER_ICON);
            }
        };
        chooser.setTitle("Override/Implement Method");
        chooser.setCopyJavadocVisible(false);
        chooser.show();
        if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE) {
            return;
        }
        StringBuilder generatedCode = new StringBuilder("");
        if (chooser.getSelectedElements() != null) {
            for (PerlMethodMember methodMember : chooser.getSelectedElements()) {
                String code = getOverrideCodeText(methodMember.getPsiElement());
                if (StringUtil.isNotEmpty(code)) {
                    generatedCode.append(code);
                    generatedCode.append("\n\n");
                }
            }
            insertCodeAfterElement(anchor, generatedCode.toString(), editor);
        }
    }
}
Also used : PerlNamespaceDefinitionElement(com.perl5.lang.perl.psi.PerlNamespaceDefinitionElement) ArrayList(java.util.ArrayList) TextRange(com.intellij.openapi.util.TextRange) SpeedSearchComparator(com.intellij.ui.SpeedSearchComparator) PerlMethodMember(com.perl5.lang.perl.idea.codeInsight.PerlMethodMember) MemberChooser(com.intellij.ide.util.MemberChooser) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with MemberChooser

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

the class CreateConstructorMatchingSuperFix method chooseConstructor2Delegate.

public static void chooseConstructor2Delegate(final Project project, final Editor editor, PsiSubstitutor substitutor, List<PsiMethodMember> baseConstructors, PsiMethod[] baseConstrs, final PsiClass targetClass) {
    PsiMethodMember[] constructors = baseConstructors.toArray(new PsiMethodMember[baseConstructors.size()]);
    if (constructors.length == 0) {
        constructors = new PsiMethodMember[baseConstrs.length];
        for (int i = 0; i < baseConstrs.length; i++) {
            constructors[i] = new PsiMethodMember(baseConstrs[i], substitutor);
        }
    }
    // Otherwise we won't have been messing with all this stuff
    LOG.assertTrue(constructors.length >= 1);
    boolean isCopyJavadoc = true;
    if (constructors.length > 1 && !ApplicationManager.getApplication().isUnitTestMode()) {
        MemberChooser<PsiMethodMember> chooser = new MemberChooser<>(constructors, false, true, project);
        chooser.setTitle(QuickFixBundle.message("super.class.constructors.chooser.title"));
        chooser.show();
        if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE)
            return;
        constructors = chooser.getSelectedElements(new PsiMethodMember[0]);
        isCopyJavadoc = chooser.isCopyJavadoc();
    }
    final PsiMethodMember[] constructors1 = constructors;
    final boolean isCopyJavadoc1 = isCopyJavadoc;
    ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            if (targetClass.getLBrace() == null) {
                PsiClass psiClass = JavaPsiFacade.getInstance(targetClass.getProject()).getElementFactory().createClass("X");
                targetClass.addRangeAfter(psiClass.getLBrace(), psiClass.getRBrace(), targetClass.getLastChild());
            }
            JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), project);
            CodeStyleManager formatter = CodeStyleManager.getInstance(project);
            PsiMethod derived = null;
            for (PsiMethodMember candidate : constructors1) {
                PsiMethod base = candidate.getElement();
                derived = GenerateMembersUtil.substituteGenericMethod(base, candidate.getSubstitutor(), targetClass);
                if (!isCopyJavadoc1) {
                    final PsiDocComment docComment = derived.getDocComment();
                    if (docComment != null) {
                        docComment.delete();
                    }
                }
                final String targetClassName = targetClass.getName();
                LOG.assertTrue(targetClassName != null, targetClass);
                derived.setName(targetClassName);
                ConstructorBodyGenerator generator = ConstructorBodyGenerator.INSTANCE.forLanguage(derived.getLanguage());
                if (generator != null) {
                    StringBuilder buffer = new StringBuilder();
                    generator.start(buffer, derived.getName(), PsiParameter.EMPTY_ARRAY);
                    generator.generateSuperCallIfNeeded(buffer, derived.getParameterList().getParameters());
                    generator.finish(buffer);
                    PsiMethod stub = factory.createMethodFromText(buffer.toString(), targetClass);
                    derived.getBody().replace(stub.getBody());
                }
                derived = (PsiMethod) formatter.reformat(derived);
                derived = (PsiMethod) JavaCodeStyleManager.getInstance(project).shortenClassReferences(derived);
                PsiGenerationInfo<PsiMethod> info = OverrideImplementUtil.createGenerationInfo(derived);
                info.insert(targetClass, null, true);
                derived = info.getPsiMember();
            }
            if (derived != null) {
                editor.getCaretModel().moveToOffset(derived.getTextRange().getStartOffset());
                editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            }
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
        UndoUtil.markPsiFileForUndo(targetClass.getContainingFile());
    });
}
Also used : PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) MemberChooser(com.intellij.ide.util.MemberChooser) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 5 with MemberChooser

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

the class CreateConstructorParameterFromFieldFix method invoke.

@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    if (!FileModificationService.getInstance().prepareFileForWrite(file))
        return;
    PsiMethod[] constructors = myClass.getConstructors();
    if (constructors.length == 0) {
        final AddDefaultConstructorFix defaultConstructorFix = new AddDefaultConstructorFix(myClass);
        ApplicationManager.getApplication().runWriteAction(() -> defaultConstructorFix.invoke(project, editor, file));
        constructors = myClass.getConstructors();
    }
    Arrays.sort(constructors, new Comparator<PsiMethod>() {

        @Override
        public int compare(PsiMethod c1, PsiMethod c2) {
            final PsiMethod cc1 = RefactoringUtil.getChainedConstructor(c1);
            final PsiMethod cc2 = RefactoringUtil.getChainedConstructor(c2);
            if (cc1 == c2)
                return 1;
            if (cc2 == c1)
                return -1;
            if (cc1 == null) {
                return cc2 == null ? 0 : compare(c1, cc2);
            } else {
                return cc2 == null ? compare(cc1, c2) : compare(cc1, cc2);
            }
        }
    });
    final List<SmartPsiElementPointer<PsiElement>> cleanupElements = new ArrayList<>();
    final List<PsiMethod> filtered = filterConstructorsIfFieldAlreadyAssigned(constructors, getField());
    if (filtered.size() > 1) {
        final PsiMethodMember[] members = new PsiMethodMember[filtered.size()];
        int i = 0;
        for (PsiMethod constructor : filtered) {
            members[i++] = new PsiMethodMember(constructor);
        }
        final List<PsiMethodMember> elements;
        if (ApplicationManager.getApplication().isUnitTestMode()) {
            elements = Arrays.asList(members);
        } else {
            final MemberChooser<PsiMethodMember> chooser = new MemberChooser<>(members, false, true, project);
            chooser.setTitle("Choose Constructors to Add Parameter to");
            chooser.show();
            elements = chooser.getSelectedElements();
            if (elements == null)
                return;
        }
        for (PsiMethodMember member : elements) {
            if (!addParameterToConstructor(project, file, editor, member.getElement(), new PsiField[] { getField() }, cleanupElements)) {
                break;
            }
        }
    } else if (!filtered.isEmpty()) {
        final Collection<SmartPsiElementPointer<PsiField>> fieldsToFix = getFieldsToFix();
        try {
            final PsiMethod constructor = filtered.get(0);
            final LinkedHashSet<PsiField> fields = new LinkedHashSet<>();
            getFieldsToFix().add(myField);
            for (SmartPsiElementPointer<PsiField> elementPointer : fieldsToFix) {
                final PsiField field = elementPointer.getElement();
                if (field != null && isAvailable(field) && filterConstructorsIfFieldAlreadyAssigned(new PsiMethod[] { constructor }, field).contains(constructor)) {
                    fields.add(field);
                }
            }
            if (filtered.size() == constructors.length && fields.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode()) {
                PsiFieldMember[] members = new PsiFieldMember[fields.size()];
                int i = 0;
                for (PsiField field : fields) {
                    members[i++] = new PsiFieldMember(field);
                }
                MemberChooser<PsiElementClassMember> chooser = new MemberChooser<>(members, false, true, project);
                chooser.setTitle("Choose Fields to Generate Constructor Parameters for");
                chooser.show();
                if (chooser.getExitCode() != DialogWrapper.OK_EXIT_CODE)
                    return;
                final List<PsiElementClassMember> selectedElements = chooser.getSelectedElements();
                if (selectedElements == null)
                    return;
                fields.clear();
                for (PsiElementClassMember member : selectedElements) {
                    fields.add((PsiField) member.getElement());
                }
            }
            addParameterToConstructor(project, file, editor, constructor, filtered.size() == constructors.length ? fields.toArray(new PsiField[fields.size()]) : new PsiField[] { getField() }, cleanupElements);
        } finally {
            fieldsToFix.clear();
        }
    }
    GlobalInspectionContextBase.cleanupElements(project, null, cleanupElements);
}
Also used : PsiMethodMember(com.intellij.codeInsight.generation.PsiMethodMember) PsiFieldMember(com.intellij.codeInsight.generation.PsiFieldMember) MemberChooser(com.intellij.ide.util.MemberChooser) PsiElementClassMember(com.intellij.codeInsight.generation.PsiElementClassMember)

Aggregations

MemberChooser (com.intellij.ide.util.MemberChooser)8 PsiElementClassMember (com.intellij.codeInsight.generation.PsiElementClassMember)2 PsiFieldMember (com.intellij.codeInsight.generation.PsiFieldMember)2 TreeClassChooser (com.intellij.ide.util.TreeClassChooser)2 DocumentAdapter (com.intellij.ui.DocumentAdapter)2 ActionEvent (java.awt.event.ActionEvent)2 ActionListener (java.awt.event.ActionListener)2 List (java.util.List)2 DocumentEvent (javax.swing.event.DocumentEvent)2 PsiMethodMember (com.intellij.codeInsight.generation.PsiMethodMember)1 ParameterClassMember (com.intellij.codeInsight.intention.impl.ParameterClassMember)1 ConfigurationException (com.intellij.openapi.options.ConfigurationException)1 TextRange (com.intellij.openapi.util.TextRange)1 CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)1 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)1 PsiDocComment (com.intellij.psi.javadoc.PsiDocComment)1 SpeedSearchComparator (com.intellij.ui.SpeedSearchComparator)1 IncorrectOperationException (com.intellij.util.IncorrectOperationException)1 DartNamedElementNode (com.jetbrains.lang.dart.ide.DartNamedElementNode)1 DartClass (com.jetbrains.lang.dart.psi.DartClass)1