protected boolean invokeImpl(
     final Project project, final PsiLocalVariable localVariable, final Editor editor) {
   final PsiElement parent = localVariable.getParent();
   if (!(parent instanceof PsiDeclarationStatement)) {
     String message =
         RefactoringBundle.getCannotRefactorMessage(
             RefactoringBundle.message("error.wrong.caret.position.local.or.expression.name"));
     CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, getHelpID());
     return false;
   }
   final LocalToFieldHandler localToFieldHandler =
       new LocalToFieldHandler(project, true) {
         @Override
         protected Settings showRefactoringDialog(
             PsiClass aClass,
             PsiLocalVariable local,
             PsiExpression[] occurences,
             boolean isStatic) {
           return IntroduceConstantHandler.this.showRefactoringDialog(
               project,
               editor,
               aClass,
               local.getInitializer(),
               local.getType(),
               occurences,
               local,
               null);
         }
       };
   return localToFieldHandler.convertLocalToField(localVariable, editor);
 }
 public DelegationPanel() {
   final BoxLayout boxLayout = new BoxLayout(this, BoxLayout.X_AXIS);
   setLayout(boxLayout);
   add(new JLabel(RefactoringBundle.message("delegation.panel.method.calls.label")));
   myRbModifyCalls = new JRadioButton();
   myRbModifyCalls.setText(RefactoringBundle.message("delegation.panel.modify.radio"));
   add(myRbModifyCalls);
   myRbGenerateDelegate = new JRadioButton();
   myRbGenerateDelegate.setText(
       RefactoringBundle.message("delegation.panel.delegate.via.overloading.method"));
   add(myRbGenerateDelegate);
   myRbModifyCalls.setSelected(true);
   final ButtonGroup bg = new ButtonGroup();
   bg.add(myRbModifyCalls);
   bg.add(myRbGenerateDelegate);
   add(Box.createHorizontalGlue());
   myRbModifyCalls.addItemListener(
       new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
           stateModified();
         }
       });
   myRbGenerateDelegate.addItemListener(
       new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
           stateModified();
         }
       });
 }
  @Nullable
  private MoveDestination selectDestination() {
    final String packageName = getTargetPackage().trim();
    if (packageName.length() > 0
        && !JavaPsiFacade.getInstance(myManager.getProject())
            .getNameHelper()
            .isQualifiedName(packageName)) {
      Messages.showErrorDialog(
          myProject,
          RefactoringBundle.message("please.enter.a.valid.target.package.name"),
          RefactoringBundle.message("move.title"));
      return null;
    }
    RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, packageName);
    PackageWrapper targetPackage = new PackageWrapper(myManager, packageName);
    if (!targetPackage.exists()) {
      final int ret =
          Messages.showYesNoDialog(
              myProject,
              RefactoringBundle.message("package.does.not.exist", packageName),
              RefactoringBundle.message("move.title"),
              Messages.getQuestionIcon());
      if (ret != 0) return null;
    }

    return ((DestinationFolderComboBox) myDestinationFolderCB).selectDirectory(targetPackage, true);
  }
  public void doClone(PsiElement element) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.copyClass");
    PsiClass[] classes = getTopLevelClasses(element);
    if (classes == null) {
      CopyFilesOrDirectoriesHandler.doCloneFile(element);
      return;
    }
    Project project = element.getProject();

    CopyClassDialog dialog = new CopyClassDialog(classes[0], null, project, true);
    dialog.setTitle(RefactoringBundle.message("copy.handler.clone.class"));
    dialog.show();
    if (dialog.isOK()) {
      String className = dialog.getClassName();
      PsiDirectory targetDirectory = element.getContainingFile().getContainingDirectory();
      copyClassesImpl(
          className,
          project,
          Collections.singletonMap(classes[0].getContainingFile(), classes),
          null,
          targetDirectory,
          targetDirectory,
          RefactoringBundle.message("copy.handler.clone.class"),
          true,
          true);
    }
  }
Esempio n. 5
0
 public static void checkFieldConflicts(
     @Nullable PsiClass aClass, String newName, final Map<PsiElement, String> conflicts) {
   PsiField existingField = aClass != null ? aClass.findFieldByName(newName, true) : null;
   if (existingField != null) {
     if (aClass.equals(existingField.getContainingClass())) {
       String className =
           aClass instanceof PsiAnonymousClass
               ? RefactoringBundle.message("current.class")
               : RefactoringUIUtil.getDescription(aClass, false);
       final String conflict =
           RefactoringBundle.message(
               "field.0.is.already.defined.in.the.1", existingField.getName(), className);
       conflicts.put(existingField, conflict);
     } else { // method somewhere in base class
       if (!existingField.hasModifierProperty(PsiModifier.PRIVATE)) {
         String fieldInfo =
             PsiFormatUtil.formatVariable(
                 existingField,
                 PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.TYPE_AFTER,
                 PsiSubstitutor.EMPTY);
         String className =
             RefactoringUIUtil.getDescription(existingField.getContainingClass(), false);
         final String descr =
             RefactoringBundle.message(
                 "field.0.will.hide.field.1.of.the.base.class", newName, fieldInfo, className);
         conflicts.put(existingField, descr);
       }
     }
   }
 }
 @Override
 public void visitReferenceExpression(GrReferenceExpression referenceExpression) {
   final PsiElement resolved = referenceExpression.resolve();
   if (resolved instanceof PsiVariable) {
     if (!isStaticFinalField((PsiVariable) resolved)) {
       if (expr instanceof GrClosableBlock) {
         if (!PsiTreeUtil.isContextAncestor(scope, resolved, true)) {
           throw new GrRefactoringError(
               GroovyRefactoringBundle.message("closure.uses.external.variables"));
         }
       } else {
         throw new GrRefactoringError(
             RefactoringBundle.message("selected.expression.cannot.be.a.constant.initializer"));
       }
     }
   } else if (resolved instanceof PsiMethod
       && ((PsiMethod) resolved).getContainingClass() != null) {
     final GrExpression qualifier = referenceExpression.getQualifierExpression();
     if (qualifier == null
         || (qualifier instanceof GrReferenceExpression
             && ((GrReferenceExpression) qualifier).resolve() instanceof PsiClass)) {
       if (!((PsiMethod) resolved).hasModifierProperty(PsiModifier.STATIC)) {
         throw new GrRefactoringError(
             RefactoringBundle.message("selected.expression.cannot.be.a.constant.initializer"));
       }
     }
   }
 }
  private static void checkInterfaceTarget(
      MemberInfoBase<? extends PsiMember>[] infos, MultiMap<PsiElement, String> conflictsList) {
    for (MemberInfoBase<? extends PsiMember> info : infos) {
      PsiElement member = info.getMember();

      if (member instanceof PsiField || member instanceof PsiClass) {

        if (!((PsiModifierListOwner) member).hasModifierProperty(PsiModifier.STATIC)
            && !(member instanceof PsiClass && ((PsiClass) member).isInterface())) {
          String message =
              RefactoringBundle.message(
                  "0.is.not.static.it.cannot.be.moved.to.the.interface",
                  RefactoringUIUtil.getDescription(member, false));
          message = CommonRefactoringUtil.capitalize(message);
          conflictsList.putValue(member, message);
        }
      }

      if (member instanceof PsiField && ((PsiField) member).getInitializer() == null) {
        String message =
            RefactoringBundle.message(
                "0.is.not.initialized.in.declaration.such.fields.are.not.allowed.in.interfaces",
                RefactoringUIUtil.getDescription(member, false));
        conflictsList.putValue(member, CommonRefactoringUtil.capitalize(message));
      }
    }
  }
  public void invoke(
      @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
    int offset = editor.getCaretModel().getOffset();
    editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    PsiElement element = file.findElementAt(offset);

    while (true) {
      if (element == null || element instanceof PsiFile) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "the.caret.should.be.positioned.inside.a.class.to.push.members.from"));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
        return;
      }

      if (element instanceof PsiClass
          || element instanceof PsiField
          || element instanceof PsiMethod) {
        if (element instanceof JspClass) {
          RefactoringMessageUtil.showNotSupportedForJspClassesError(
              project, editor, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
          return;
        }
        invoke(project, new PsiElement[] {element}, dataContext);
        return;
      }
      element = element.getParent();
    }
  }
  @Nullable
  private String verifyInnerClassDestination() {
    PsiClass targetClass = findTargetClass();
    if (targetClass == null) return null;

    for (PsiElement element : myElementsToMove) {
      if (PsiTreeUtil.isAncestor(element, targetClass, false)) {
        return RefactoringBundle.message("move.class.to.inner.move.to.self.error");
      }
      final Language targetClassLanguage = targetClass.getLanguage();
      if (!element.getLanguage().equals(targetClassLanguage)) {
        return RefactoringBundle.message(
            "move.to.different.language",
            UsageViewUtil.getType(element),
            ((PsiClass) element).getQualifiedName(),
            targetClass.getQualifiedName());
      }
      if (element.getLanguage().equals(Language.findLanguageByID("Groovy"))) {
        return RefactoringBundle.message("dont.support.inner.classes", "Groovy");
      }
    }

    while (targetClass != null) {
      if (targetClass.getContainingClass() != null
          && !targetClass.hasModifierProperty(PsiModifier.STATIC)) {
        return RefactoringBundle.message("move.class.to.inner.nonstatic.error");
      }
      targetClass = targetClass.getContainingClass();
    }

    return null;
  }
Esempio n. 10
0
 protected void doOKAction() {
   CommandProcessor.getInstance()
       .executeCommand(
           myProject,
           new Runnable() {
             public void run() {
               final Runnable action =
                   new Runnable() {
                     public void run() {
                       String directoryName =
                           myTargetDirectoryField.getText().replace(File.separatorChar, '/');
                       try {
                         myTargetDirectory =
                             DirectoryUtil.mkdirs(
                                 PsiManager.getInstance(myProject), directoryName);
                       } catch (IncorrectOperationException e) {
                       }
                     }
                   };
               ApplicationManager.getApplication().runWriteAction(action);
             }
           },
           RefactoringBundle.message("create.directory"),
           null);
   if (myTargetDirectory == null) {
     CommonRefactoringUtil.showErrorMessage(
         getTitle(), RefactoringBundle.message("cannot.create.directory"), myHelpID, myProject);
     return;
   }
   myCallback.run(this);
 }
 @Nullable
 private static String getCannotRefactorMessage(PsiMember member) {
   if (member == null) {
     return RefactoringBundle.message("locate.caret.inside.a.method");
   }
   if (member instanceof PsiMethod) {
     if (((PsiMethod) member).isConstructor()) {
       return RefactoringBundle.message("replace.with.method.call.does.not.work.for.constructors");
     }
     final PsiCodeBlock body = ((PsiMethod) member).getBody();
     if (body == null) {
       return RefactoringBundle.message("method.does.not.have.a.body", member.getName());
     }
     final PsiStatement[] statements = body.getStatements();
     if (statements.length == 0) {
       return RefactoringBundle.message("method.has.an.empty.body", member.getName());
     }
   } else if (member instanceof PsiField) {
     final PsiField field = (PsiField) member;
     if (field.getInitializer() == null) {
       return "Field " + member.getName() + " doesn't have initializer";
     }
     final PsiClass containingClass = field.getContainingClass();
     if (!field.hasModifierProperty(PsiModifier.FINAL)
         || !field.hasModifierProperty(PsiModifier.STATIC)
         || containingClass == null
         || containingClass.getQualifiedName() == null) {
       return "Replace Duplicates works with constants only";
     }
   } else {
     return "Caret should be inside method or constant";
   }
   return null;
 }
  protected void performRefactoring(
      Project project,
      PsiDirectory directory,
      PsiPackage aPackage,
      boolean searchInComments,
      boolean searchForTextOccurences) {
    final VirtualFile sourceRoot =
        ProjectRootManager.getInstance(project)
            .getFileIndex()
            .getSourceRootForFile(directory.getVirtualFile());
    if (sourceRoot == null) {
      Messages.showErrorDialog(
          project,
          RefactoringBundle.message("destination.directory.does.not.correspond.to.any.package"),
          RefactoringBundle.message("cannot.move"));
      return;
    }
    final JavaRefactoringFactory factory = JavaRefactoringFactory.getInstance(project);
    final MoveDestination destination =
        myPreserveSourceRoot.isSelected() && myPreserveSourceRoot.isVisible()
            ? factory.createSourceFolderPreservingMoveDestination(aPackage.getQualifiedName())
            : factory.createSourceRootMoveDestination(aPackage.getQualifiedName(), sourceRoot);

    MoveClassesOrPackagesProcessor processor =
        new MoveClassesOrPackagesProcessor(
            myDirectory.getProject(),
            myElementsToMove,
            destination,
            searchInComments,
            searchForTextOccurences,
            myMoveCallback);
    if (processor.verifyValidPackageName()) {
      processor.run();
    }
  }
  public Collection<PsiElement> getAdditionalElementsToDelete(
      @NotNull final PsiElement element,
      @NotNull final Collection<PsiElement> allElementsToDelete,
      final boolean askUser) {
    if (element instanceof PsiField) {
      PsiField field = (PsiField) element;
      final Project project = element.getProject();
      String propertyName =
          JavaCodeStyleManager.getInstance(project)
              .variableNameToPropertyName(field.getName(), VariableKind.FIELD);

      PsiClass aClass = field.getContainingClass();
      if (aClass != null) {
        boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
        PsiMethod[] getters =
            GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);
        if (getters != null) {
          final List<PsiMethod> validGetters = new ArrayList<>(1);
          for (PsiMethod getter : getters) {
            if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) {
              validGetters.add(getter);
            }
          }
          getters =
              validGetters.isEmpty()
                  ? null
                  : validGetters.toArray(new PsiMethod[validGetters.size()]);
        }

        PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);
        if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical())
          setter = null;
        if (askUser && (getters != null || setter != null)) {
          final String message =
              RefactoringMessageUtil.getGetterSetterMessage(
                  field.getName(),
                  RefactoringBundle.message("delete.title"),
                  getters != null ? getters[0] : null,
                  setter);
          if (!ApplicationManager.getApplication().isUnitTestMode()
              && Messages.showYesNoDialog(
                      project,
                      message,
                      RefactoringBundle.message("safe.delete.title"),
                      Messages.getQuestionIcon())
                  != Messages.YES) {
            getters = null;
            setter = null;
          }
        }
        List<PsiElement> elements = new ArrayList<>();
        if (setter != null) elements.add(setter);
        if (getters != null) Collections.addAll(elements, getters);
        return elements;
      }
    }
    return null;
  }
  protected JComponent createNorthPanel() {
    myNameField = new NameSuggestionsField(myProject);
    myNameChangedListener =
        new NameSuggestionsField.DataChanged() {
          public void dataChanged() {
            updateOkStatus();
          }
        };
    myNameField.addDataChangedListener(myNameChangedListener);

    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbConstraints = new GridBagConstraints();

    gbConstraints.insets = JBUI.insets(4);
    gbConstraints.anchor = GridBagConstraints.WEST;
    gbConstraints.fill = GridBagConstraints.BOTH;

    gbConstraints.gridwidth = 1;
    gbConstraints.weightx = 0;
    gbConstraints.weighty = 0;
    gbConstraints.gridx = 0;
    gbConstraints.gridy = 0;
    JLabel type = new JLabel(RefactoringBundle.message("variable.of.type"));
    panel.add(type, gbConstraints);

    gbConstraints.gridx++;
    myTypeSelector = myTypeSelectorManager.getTypeSelector();
    panel.add(myTypeSelector.getComponent(), gbConstraints);

    gbConstraints.gridwidth = 1;
    gbConstraints.weightx = 0;
    gbConstraints.weighty = 0;
    gbConstraints.gridx = 0;
    gbConstraints.gridy = 1;
    JLabel namePrompt = new JLabel(RefactoringBundle.message("name.prompt"));
    namePrompt.setLabelFor(myNameField.getComponent());
    panel.add(namePrompt, gbConstraints);

    gbConstraints.gridwidth = 1;
    gbConstraints.weightx = 1;
    gbConstraints.gridx = 1;
    gbConstraints.gridy = 1;
    panel.add(myNameField.getComponent(), gbConstraints);

    myNameSuggestionsManager =
        new NameSuggestionsManager(
            myTypeSelector,
            myNameField,
            new NameSuggestionsGenerator() {
              public SuggestedNameInfo getSuggestedNameInfo(PsiType type) {
                return IntroduceVariableBase.getSuggestedName(type, myExpression);
              }
            });
    myNameSuggestionsManager.setLabelsFor(type, namePrompt);

    return panel;
  }
Esempio n. 15
0
  public static void checkMethodConflicts(
      @Nullable PsiClass aClass,
      PsiMethod refactoredMethod,
      PsiMethod prototype,
      final MultiMap<PsiElement, String> conflicts) {
    if (prototype == null) return;

    PsiMethod method = aClass != null ? aClass.findMethodBySignature(prototype, true) : null;

    if (method != null && method != refactoredMethod) {
      if (aClass.equals(method.getContainingClass())) {
        final String classDescr =
            aClass instanceof PsiAnonymousClass
                ? RefactoringBundle.message("current.class")
                : RefactoringUIUtil.getDescription(aClass, false);
        conflicts.putValue(
            method,
            RefactoringBundle.message(
                "method.0.is.already.defined.in.the.1",
                getMethodPrototypeString(prototype),
                classDescr));
      } else { // method somewhere in base class
        if (JavaPsiFacade.getInstance(method.getProject())
            .getResolveHelper()
            .isAccessible(method, aClass, null)) {
          String protoMethodInfo = getMethodPrototypeString(prototype);
          String className =
              CommonRefactoringUtil.htmlEmphasize(
                  UsageViewUtil.getDescriptiveName(method.getContainingClass()));
          if (PsiUtil.getAccessLevel(prototype.getModifierList())
              >= PsiUtil.getAccessLevel(method.getModifierList())) {
            boolean isMethodAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
            boolean isMyMethodAbstract =
                refactoredMethod != null
                    && refactoredMethod.hasModifierProperty(PsiModifier.ABSTRACT);
            final String conflict =
                isMethodAbstract != isMyMethodAbstract
                    ? RefactoringBundle.message(
                        "method.0.will.implement.method.of.the.base.class",
                        protoMethodInfo,
                        className)
                    : RefactoringBundle.message(
                        "method.0.will.override.a.method.of.the.base.class",
                        protoMethodInfo,
                        className);
            conflicts.putValue(method, conflict);
          } else { // prototype is private, will be compile-error
            conflicts.putValue(
                method,
                RefactoringBundle.message(
                    "method.0.will.hide.method.of.the.base.class", protoMethodInfo, className));
          }
        }
      }
    }
  }
 private static boolean askToRenameAccesors(
     PsiMethod getter, PsiMethod setter, String newName, final Project project) {
   if (ApplicationManager.getApplication().isUnitTestMode()) return false;
   String text =
       RefactoringMessageUtil.getGetterSetterMessage(
           newName, RefactoringBundle.message("rename.title"), getter, setter);
   return Messages.showYesNoDialog(
           project, text, RefactoringBundle.message("rename.title"), Messages.getQuestionIcon())
       == 0;
 }
 @Nullable
 private static String getCannotInlineMessage(
     final PsiParameter psiParameter, final PsiMethod method) {
   if (psiParameter.isVarArgs()) {
     return RefactoringBundle.message("inline.parameter.error.varargs");
   }
   if (method.findSuperMethods().length > 0
       || OverridingMethodsSearch.search(method, true).toArray(PsiMethod.EMPTY_ARRAY).length > 0) {
     return RefactoringBundle.message("inline.parameter.error.hierarchy");
   }
   return null;
 }
  private void replaceDuplicates(
      final String includePath,
      final List<IncludeDuplicate<T>> duplicates,
      final Editor editor,
      final Project project) {
    if (duplicates.size() > 0) {
      final String message =
          RefactoringBundle.message(
              "idea.has.found.fragments.that.can.be.replaced.with.include.directive",
              ApplicationNamesInfo.getInstance().getProductName());
      final int exitCode =
          Messages.showYesNoDialog(
              project, message, getRefactoringName(), Messages.getInformationIcon());
      if (exitCode == DialogWrapper.OK_EXIT_CODE) {
        CommandProcessor.getInstance()
            .executeCommand(
                project,
                new Runnable() {
                  public void run() {
                    boolean replaceAll = false;
                    for (IncludeDuplicate<T> pair : duplicates) {
                      if (!replaceAll) {

                        highlightInEditor(project, pair, editor);

                        ReplacePromptDialog promptDialog =
                            new ReplacePromptDialog(
                                false, RefactoringBundle.message("replace.fragment"), project);
                        promptDialog.show();
                        final int promptResult = promptDialog.getExitCode();
                        if (promptResult == FindManager.PromptResult.SKIP) continue;
                        if (promptResult == FindManager.PromptResult.CANCEL) break;

                        if (promptResult == FindManager.PromptResult.OK) {
                          doReplaceRange(includePath, pair.getStart(), pair.getEnd());
                        } else if (promptResult == FindManager.PromptResult.ALL) {
                          doReplaceRange(includePath, pair.getStart(), pair.getEnd());
                          replaceAll = true;
                        } else {
                          LOG.error("Unknown return status");
                        }
                      } else {
                        doReplaceRange(includePath, pair.getStart(), pair.getEnd());
                      }
                    }
                  }
                },
                RefactoringBundle.message("remove.duplicates.command"),
                null);
      }
    }
  }
 public static void buildPackagePrefixChangedMessage(
     final VirtualFile[] virtualFiles, StringBuffer message, final String qualifiedName) {
   if (virtualFiles.length > 0) {
     message.append(
         RefactoringBundle.message(
             "package.occurs.in.package.prefixes.of.the.following.source.folders.n",
             qualifiedName));
     for (final VirtualFile virtualFile : virtualFiles) {
       message.append(virtualFile.getPresentableUrl()).append("\n");
     }
     message.append(RefactoringBundle.message("these.package.prefixes.will.be.changed"));
   }
 }
  protected JPanel createReplaceFieldsWithGettersPanel() {
    JPanel radioButtonPanel = new JPanel(new GridBagLayout());

    GridBagConstraints gbConstraints = new GridBagConstraints();
    gbConstraints.insets = new Insets(4, 8, 4, 8);
    gbConstraints.weighty = 1;
    gbConstraints.weightx = 1;
    gbConstraints.gridy = 0;
    gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
    gbConstraints.fill = GridBagConstraints.BOTH;
    gbConstraints.anchor = GridBagConstraints.WEST;
    radioButtonPanel.add(
        new JLabel(
            RefactoringBundle.message("replace.fields.used.in.expressions.with.their.getters")),
        gbConstraints);

    myReplaceFieldsWithGettersNoneRadio = new JRadioButton();
    myReplaceFieldsWithGettersNoneRadio.setText(RefactoringBundle.message("do.not.replace"));

    myReplaceFieldsWithGettersInaccessibleRadio = new JRadioButton();
    myReplaceFieldsWithGettersInaccessibleRadio.setText(
        RefactoringBundle.message("replace.fields.inaccessible.in.usage.context"));

    myReplaceFieldsWithGettersAllRadio = new JRadioButton();
    myReplaceFieldsWithGettersAllRadio.setText(RefactoringBundle.message("replace.all.fields"));

    gbConstraints.gridy++;
    radioButtonPanel.add(myReplaceFieldsWithGettersNoneRadio, gbConstraints);
    gbConstraints.gridy++;
    radioButtonPanel.add(myReplaceFieldsWithGettersInaccessibleRadio, gbConstraints);
    gbConstraints.gridy++;
    radioButtonPanel.add(myReplaceFieldsWithGettersAllRadio, gbConstraints);

    final int currentSetting =
        JavaRefactoringSettings.getInstance().INTRODUCE_PARAMETER_REPLACE_FIELDS_WITH_GETTERS;

    myReplaceFieldsWithGettersButtonGroup.add(myReplaceFieldsWithGettersNoneRadio);
    myReplaceFieldsWithGettersButtonGroup.add(myReplaceFieldsWithGettersInaccessibleRadio);
    myReplaceFieldsWithGettersButtonGroup.add(myReplaceFieldsWithGettersAllRadio);

    if (currentSetting == IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_ALL) {
      myReplaceFieldsWithGettersAllRadio.setSelected(true);
    } else if (currentSetting
        == IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_INACCESSIBLE) {
      myReplaceFieldsWithGettersInaccessibleRadio.setSelected(true);
    } else if (currentSetting == IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE) {
      myReplaceFieldsWithGettersNoneRadio.setSelected(true);
    }

    return radioButtonPanel;
  }
Esempio n. 21
0
  private void setNewName(@NotNull String newName) {
    if (myPrimaryElement == null) {
      myCommandName = RefactoringBundle.message("renaming.something");
      return;
    }

    myNewName = newName;
    myAllRenames.put(myPrimaryElement, newName);
    myCommandName =
        RefactoringBundle.message(
            "renaming.0.1.to.2",
            UsageViewUtil.getType(myPrimaryElement),
            UsageViewUtil.getDescriptiveName(myPrimaryElement),
            newName);
  }
Esempio n. 22
0
  private static ElementToWorkOn getElementToWorkOn(
      final Editor editor,
      final PsiFile file,
      final String refactoringName,
      final String helpId,
      final Project project,
      PsiLocalVariable localVar,
      PsiExpression expr) {
    int startOffset = 0;
    int endOffset = 0;
    if (localVar == null && expr == null) {
      startOffset = editor.getSelectionModel().getSelectionStart();
      endOffset = editor.getSelectionModel().getSelectionEnd();
      expr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset);
      if (expr == null) {
        PsiIdentifier ident =
            CodeInsightUtil.findElementInRange(file, startOffset, endOffset, PsiIdentifier.class);
        if (ident != null) {
          localVar = PsiTreeUtil.getParentOfType(ident, PsiLocalVariable.class);
        }
      }
    }

    if (expr == null && localVar == null) {
      PsiElement[] statements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset);
      if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) {
        expr = ((PsiExpressionStatement) statements[0]).getExpression();
      } else if (statements.length == 1 && statements[0] instanceof PsiDeclarationStatement) {
        PsiDeclarationStatement decl = (PsiDeclarationStatement) statements[0];
        PsiElement[] declaredElements = decl.getDeclaredElements();
        if (declaredElements.length == 1 && declaredElements[0] instanceof PsiLocalVariable) {
          localVar = (PsiLocalVariable) declaredElements[0];
        }
      }
    }
    if (localVar == null && expr == null) {
      expr = IntroduceVariableBase.getSelectedExpression(project, file, startOffset, endOffset);
    }

    if (localVar == null && expr == null) {
      String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("error.wrong.caret.position.local.or.expression.name"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId);
      return null;
    }
    return new ElementToWorkOn(localVar, expr);
  }
 public boolean checkConflicts(final ExtractSuperclassDialog dialog) {
   final MemberInfo[] infos =
       ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class);
   final PsiDirectory targetDirectory = dialog.getTargetDirectory();
   final PsiPackage targetPackage;
   if (targetDirectory != null) {
     targetPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory);
   } else {
     targetPackage = null;
   }
   final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
   if (!ProgressManager.getInstance()
       .runProcessWithProgressSynchronously(
           new Runnable() {
             public void run() {
               final PsiClass superClass =
                   mySubclass.getExtendsListTypes().length > 0 ? mySubclass.getSuperClass() : null;
               conflicts.putAllValues(
                   PullUpConflictsUtil.checkConflicts(
                       infos,
                       mySubclass,
                       superClass,
                       targetPackage,
                       targetDirectory,
                       dialog.getContainmentVerifier(),
                       false));
             }
           },
           RefactoringBundle.message("detecting.possible.conflicts"),
           true,
           myProject)) return false;
   ExtractSuperClassUtil.checkSuperAccessible(targetDirectory, conflicts, mySubclass);
   return ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject);
 }
 @Override
 public Collection<String> findConflicts(
     PsiElement element, PsiElement[] elements, UsageInfo[] usages) {
   String methodRefFound = null;
   if (!ApplicationManager.getApplication().isUnitTestMode()
       && (element instanceof PsiMethod || element instanceof PsiParameter)) {
     for (UsageInfo usage : usages) {
       final PsiElement refElement = usage.getElement();
       if (refElement instanceof PsiMethodReferenceExpression) {
         methodRefFound = RefactoringBundle.message("expand.method.reference.warning");
         break;
       }
     }
   }
   if (methodRefFound != null) {
     Collection<String> result = new ArrayList<>();
     result.add(methodRefFound);
     final Collection<String> conflicts = super.findConflicts(element, elements, usages);
     if (conflicts != null) {
       result.addAll(conflicts);
     }
     return result;
   }
   return super.findConflicts(element, elements, usages);
 }
  private static void invoke(final PsiClass aClass, Editor editor) {
    final PsiTypeParameterList typeParameterList = aClass.getTypeParameterList();
    Project project = aClass.getProject();
    if (typeParameterList == null) {
      final String message =
          RefactoringBundle.getCannotRefactorMessage(
              RefactoringBundle.message("changeClassSignature.no.type.parameters"));
      CommonRefactoringUtil.showErrorHint(
          project, editor, message, REFACTORING_NAME, HelpID.CHANGE_CLASS_SIGNATURE);
      return;
    }
    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return;

    ChangeClassSignatureDialog dialog = new ChangeClassSignatureDialog(aClass);
    dialog.show();
  }
 public MoveFilesOrDirectoriesDialog(Project project, Callback callback) {
   super(project, true);
   myProject = project;
   myCallback = callback;
   setTitle(RefactoringBundle.message("move.title"));
   init();
 }
  protected void createRemoveParamsPanel(GridBagConstraints gbConstraints, JPanel panel) {
    final JCheckBox[] removeParamsCb = new JCheckBox[myParametersToRemove.length];
    for (int i = 0; i < myParametersToRemove.length; i++) {
      PsiParameter parameter = myParametersToRemove[i];
      if (parameter == null) continue;
      final NonFocusableCheckBox cb =
          new NonFocusableCheckBox(
              RefactoringBundle.message("remove.parameter.0.no.longer.used", parameter.getName()));
      removeParamsCb[i] = cb;
      cb.setSelected(true);
      gbConstraints.gridy++;
      panel.add(cb, gbConstraints);
      final int i1 = i;
      cb.addChangeListener(
          new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
              myParametersToRemoveChecked[i1] = cb.isSelected();
            }
          });
      myParametersToRemoveChecked[i] = true;
    }

    updateControls(removeParamsCb);
    if (myCbReplaceAllOccurences != null) {
      myCbReplaceAllOccurences.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              updateControls(removeParamsCb);
            }
          });
    }
  }
 @Override
 protected void canRun() throws ConfigurationException {
   if (!areButtonsValid()) {
     throw new ConfigurationException(
         RefactoringBundle.message("refactoring.introduce.name.error"), getName());
   }
 }
  private static boolean invoke(
      final PsiMethod method,
      final Project project,
      @Nullable final Editor editor,
      ChangeSignatureHandler initSubstisutor) {
    PsiMethod newMethod =
        SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
    if (newMethod == null) return false;

    if (!newMethod.equals(method)) {
      ChangeSignatureUtil.invokeChangeSignatureOn(newMethod, project);
      return true;
    }

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, method)) return false;

    final PsiClass containingClass = method.getContainingClass();
    final PsiReferenceExpression refExpr =
        editor != null ? TargetElementUtil.findReferenceExpression(editor) : null;
    final boolean allowDelegation = containingClass != null && !containingClass.isInterface();
    final DialogWrapper dialog =
        new GosuChangeSignatureDialog(
            project,
            new GosuMethodDescriptor((IGosuMethod) method, initSubstisutor),
            allowDelegation,
            refExpr,
            initSubstisutor);
    return dialog.showAndGet();
  }
  private void invokeMoveToPackage() {
    final MoveDestination destination = selectDestination();
    if (destination == null) return;

    saveRefactoringSettings();
    for (final PsiElement element : myElementsToMove) {
      String message = verifyDestinationForElement(element, destination);
      if (message != null) {
        String helpId = HelpID.getMoveHelpID(myElementsToMove[0]);
        CommonRefactoringUtil.showErrorMessage(
            RefactoringBundle.message("error.title"), message, helpId, getProject());
        return;
      }
    }
    try {
      for (PsiElement element : myElementsToMove) {
        if (element instanceof PsiClass) {
          final PsiClass aClass = (PsiClass) element;
          LOG.assertTrue(aClass.isPhysical(), aClass);
          /*PsiElement toAdd;
          if (aClass.getContainingFile() instanceof PsiJavaFile && ((PsiJavaFile)aClass.getContainingFile()).getClasses().length > 1) {
            toAdd = aClass;
          }
          else {
            toAdd = aClass.getContainingFile();
          }*/

          final PsiDirectory targetDirectory =
              destination.getTargetIfExists(element.getContainingFile());
          if (targetDirectory != null) {
            MoveFilesOrDirectoriesUtil.checkMove(aClass, targetDirectory);
          }
        }
      }

      MoveClassesOrPackagesProcessor processor =
          createMoveToPackageProcessor(destination, myElementsToMove, myMoveCallback);
      if (processor.verifyValidPackageName()) {
        processor.setOpenInEditor(isOpenInEditor());
        invokeRefactoring(processor);
      }
    } catch (IncorrectOperationException e) {
      String helpId = HelpID.getMoveHelpID(myElementsToMove[0]);
      CommonRefactoringUtil.showErrorMessage(
          RefactoringBundle.message("error.title"), e.getMessage(), helpId, getProject());
    }
  }