Esempio n. 1
0
    @Override
    public void hyperlinkUpdate(@NotNull HyperlinkEvent e) {
      if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) {
        return;
      }

      String description = e.getDescription();
      if (StringUtil.isEmpty(description)
          || !description.startsWith(DocumentationManager.PSI_ELEMENT_PROTOCOL)) {
        return;
      }

      String elementName =
          e.getDescription().substring(DocumentationManager.PSI_ELEMENT_PROTOCOL.length());

      final PsiElement targetElement =
          myProvider.getDocumentationElementForLink(
              PsiManager.getInstance(myProject), elementName, myContext);
      if (targetElement != null) {
        LightweightHint hint = myHint;
        if (hint != null) {
          hint.hide(true);
        }
        myDocumentationManager.showJavaDocInfo(targetElement, myContext, true, null);
      }
    }
  @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);
  }
    @Override
    public void navigate(Project project) {
      VirtualFile currentVirtualFile = null;

      AccessToken accessToken = ReadAction.start();

      try {
        if (!myVirtualFile.isValid()) return;

        PsiFile psiFile = PsiManager.getInstance(project).findFile(myVirtualFile);
        if (psiFile != null) {
          PsiElement navigationElement =
              psiFile.getNavigationElement(); // Sources may be downloaded.
          if (navigationElement instanceof PsiFile) {
            currentVirtualFile = ((PsiFile) navigationElement).getVirtualFile();
          }
        }

        if (currentVirtualFile == null) {
          currentVirtualFile = myVirtualFile;
        }
      } finally {
        accessToken.finish();
      }

      new OpenFileHyperlinkInfo(myProject, currentVirtualFile, myLineNumber - 1).navigate(project);
    }
  private void createTreeModel() {
    final PsiManager psiManager = PsiManager.getInstance(myProject);
    final FileIndex fileIndex =
        myModule != null
            ? ModuleRootManager.getInstance(myModule).getFileIndex()
            : ProjectRootManager.getInstance(myProject).getFileIndex();
    fileIndex.iterateContent(
        new ContentIterator() {
          public boolean processFile(VirtualFile fileOrDir) {
            if (fileOrDir.isDirectory() && fileIndex.isInSourceContent(fileOrDir)) {
              final PsiDirectory psiDirectory = psiManager.findDirectory(fileOrDir);
              LOG.assertTrue(psiDirectory != null);
              PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
              if (aPackage != null) {
                addPackage(aPackage);
              }
            }
            return true;
          }
        });

    TreeUtil.sort(
        myModel,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1;
            DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2;
            PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject();
            PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject();
            return element1.getName().compareToIgnoreCase(element2.getName());
          }
        });
  }
    private PsiElement[] getElementsToDelete() {
      ArrayList<PsiElement> result = new ArrayList<PsiElement>();
      Object[] elements = getSelectedNodeElements();
      for (int idx = 0; elements != null && idx < elements.length; idx++) {
        if (elements[idx] instanceof PsiElement) {
          final PsiElement element = (PsiElement) elements[idx];
          result.add(element);
          if (element instanceof PsiDirectory) {
            final VirtualFile virtualFile = ((PsiDirectory) element).getVirtualFile();
            final String path = virtualFile.getPath();
            if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root
              final VirtualFile vFile =
                  LocalFileSystem.getInstance()
                      .findFileByPath(
                          path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length()));
              if (vFile != null) {
                final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile);
                if (psiFile != null) {
                  elements[idx] = psiFile;
                }
              }
            }
          }
        }
      }

      return result.toArray(new PsiElement[result.size()]);
    }
  public MoveClassesOrPackagesDialog(
      Project project,
      boolean searchTextOccurences,
      PsiElement[] elementsToMove,
      final PsiElement initialTargetElement,
      MoveCallback moveCallback) {
    super(project, true);
    myElementsToMove = elementsToMove;
    myMoveCallback = moveCallback;
    myManager = PsiManager.getInstance(myProject);
    setTitle(MoveHandler.REFACTORING_NAME);
    mySearchTextOccurencesEnabled = searchTextOccurences;

    selectInitialCard();

    init();

    if (initialTargetElement instanceof PsiClass) {
      myMakeInnerClassOfRadioButton.setSelected(true);

      myInnerClassChooser.setText(((PsiClass) initialTargetElement).getQualifiedName());

      ApplicationManager.getApplication()
          .invokeLater(
              () -> myInnerClassChooser.requestFocus(),
              ModalityState.stateForComponent(myMainPanel));
    } else if (initialTargetElement instanceof PsiPackage) {
      myClassPackageChooser.setText(((PsiPackage) initialTargetElement).getQualifiedName());
    }

    updateControlsEnabled();
    myToPackageRadioButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateControlsEnabled();
            myClassPackageChooser.requestFocus();
          }
        });
    myMakeInnerClassOfRadioButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            updateControlsEnabled();
            myInnerClassChooser.requestFocus();
          }
        });

    for (PsiElement element : elementsToMove) {
      if (element.getContainingFile() != null) {
        myOpenInEditorPanel.add(initOpenInEditorCb(), BorderLayout.EAST);
        break;
      }
    }
  }
 protected PsiDirectory[] getSelectedDirectoriesInAmbiguousCase(
     @NotNull final DefaultMutableTreeNode node) {
   final Object userObject = node.getUserObject();
   if (userObject instanceof AbstractModuleNode) {
     final Module module = ((AbstractModuleNode) userObject).getValue();
     if (module != null) {
       final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
       final VirtualFile[] sourceRoots = moduleRootManager.getSourceRoots();
       List<PsiDirectory> dirs = new ArrayList<PsiDirectory>(sourceRoots.length);
       final PsiManager psiManager = PsiManager.getInstance(myProject);
       for (final VirtualFile sourceRoot : sourceRoots) {
         final PsiDirectory directory = psiManager.findDirectory(sourceRoot);
         if (directory != null) {
           dirs.add(directory);
         }
       }
       return dirs.toArray(new PsiDirectory[dirs.size()]);
     }
   }
   return PsiDirectory.EMPTY_ARRAY;
 }
 @Override
 protected void canRun() throws ConfigurationException {
   if (isMoveToPackage()) {
     String name = getTargetPackage().trim();
     if (name.length() != 0
         && !PsiNameHelper.getInstance(myManager.getProject()).isQualifiedName(name)) {
       throw new ConfigurationException("\'" + name + "\' is invalid destination package name");
     }
   } else {
     if (findTargetClass() == null)
       throw new ConfigurationException("Destination class not found");
     final String validationError = verifyInnerClassDestination();
     if (validationError != null) throw new ConfigurationException(validationError);
   }
 }
  private void reportErrorsToWolf() {
    if (!myFile.getViewProvider().isPhysical()) return; // e.g. errors in evaluate expression
    Project project = myFile.getProject();
    if (!PsiManager.getInstance(project).isInProject(myFile))
      return; // do not report problems in libraries
    VirtualFile file = myFile.getVirtualFile();
    if (file == null) return;

    List<Problem> problems = convertToProblems(getInfos(), file, myHasErrorElement);
    WolfTheProblemSolver wolf = WolfTheProblemSolver.getInstance(project);

    boolean hasErrors = DaemonCodeAnalyzerImpl.hasErrors(project, getDocument());
    if (!hasErrors || isWholeFileHighlighting()) {
      wolf.reportProblems(file, problems);
    } else {
      wolf.weHaveGotProblems(file, problems);
    }
  }
  private void createUIComponents() {
    myMainPanel = new JPanel();

    myWithBrowseButtonReference = createPackageChooser();
    myClassPackageChooser = createPackageChooser();

    myInnerClassChooser =
        new ClassNameReferenceEditor(
            PsiManager.getInstance(myProject), null, ProjectScope.getProjectScope(myProject));
    myInnerClassChooser.addDocumentListener(
        new DocumentAdapter() {
          public void documentChanged(DocumentEvent e) {
            validateButtons();
          }
        });

    // override CardLayout sizing behavior
    myCardPanel =
        new JPanel() {
          public Dimension getMinimumSize() {
            return myHavePackages
                ? myMovePackagePanel.getMinimumSize()
                : myMoveClassPanel.getMinimumSize();
          }

          public Dimension getPreferredSize() {
            return myHavePackages
                ? myMovePackagePanel.getPreferredSize()
                : myMoveClassPanel.getPreferredSize();
          }
        };

    myDestinationFolderCB =
        new DestinationFolderComboBox() {
          @Override
          public String getTargetPackage() {
            return MoveClassesOrPackagesDialog.this.getTargetPackage();
          }
        };
  }
 @Nullable
 private PsiClass findTargetClass() {
   String name = myInnerClassChooser.getText().trim();
   return JavaPsiFacade.getInstance(myManager.getProject())
       .findClass(name, ProjectScope.getProjectScope(myProject));
 }
  @Override
  protected String validateAndCommitData() {
    PsiManager manager = PsiManager.getInstance(myProject);
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();

    String name = getMethodName();
    if (!JavaPsiFacade.getInstance(manager.getProject()).getNameHelper().isIdentifier(name)) {
      return RefactoringMessageUtil.getIncorrectIdentifierMessage(name);
    }

    if (myMethod.canChangeReturnType() == MethodDescriptor.ReadWriteOption.ReadWrite) {
      try {
        ((PsiTypeCodeFragment) myReturnTypeCodeFragment).getType();
      } catch (PsiTypeCodeFragment.TypeSyntaxException e) {
        myReturnTypeField.requestFocus();
        return RefactoringBundle.message(
            "changeSignature.wrong.return.type", myReturnTypeCodeFragment.getText());
      } catch (PsiTypeCodeFragment.NoTypeException e) {
        myReturnTypeField.requestFocus();
        return RefactoringBundle.message("changeSignature.no.return.type");
      }
    }

    List<ParameterTableModelItemBase<ParameterInfoImpl>> parameterInfos =
        myParametersTableModel.getItems();
    final int newParametersNumber = parameterInfos.size();

    for (int i = 0; i < newParametersNumber; i++) {
      final ParameterTableModelItemBase<ParameterInfoImpl> item = parameterInfos.get(i);

      if (!JavaPsiFacade.getInstance(manager.getProject())
          .getNameHelper()
          .isIdentifier(item.parameter.getName())) {
        return RefactoringMessageUtil.getIncorrectIdentifierMessage(item.parameter.getName());
      }

      final PsiType type;
      try {
        type = ((PsiTypeCodeFragment) parameterInfos.get(i).typeCodeFragment).getType();
      } catch (PsiTypeCodeFragment.TypeSyntaxException e) {
        return RefactoringBundle.message(
            "changeSignature.wrong.type.for.parameter",
            item.typeCodeFragment.getText(),
            item.parameter.getName());
      } catch (PsiTypeCodeFragment.NoTypeException e) {
        return RefactoringBundle.message(
            "changeSignature.no.type.for.parameter", item.parameter.getName());
      }

      item.parameter.setType(type);

      if (type instanceof PsiEllipsisType && i != newParametersNumber - 1) {
        return RefactoringBundle.message("changeSignature.vararg.not.last");
      }

      if (item.parameter.oldParameterIndex < 0) {
        item.parameter.defaultValue =
            ApplicationManager.getApplication()
                .runWriteAction(
                    new Computable<String>() {
                      @Override
                      public String compute() {
                        return JavaCodeStyleManager.getInstance(myProject)
                            .qualifyClassReferences(item.defaultValueCodeFragment)
                            .getText();
                      }
                    });
        String def = item.parameter.defaultValue;
        def = def.trim();
        if (!(type instanceof PsiEllipsisType)) {
          try {
            if (!StringUtil.isEmpty(def)) {
              factory.createExpressionFromText(def, null);
            }
          } catch (IncorrectOperationException e) {
            return e.getMessage();
          }
        }
      }
    }

    ThrownExceptionInfo[] exceptionInfos = myExceptionsModel.getThrownExceptions();
    PsiTypeCodeFragment[] typeCodeFragments = myExceptionsModel.getTypeCodeFragments();
    for (int i = 0; i < exceptionInfos.length; i++) {
      ThrownExceptionInfo exceptionInfo = exceptionInfos[i];
      PsiTypeCodeFragment typeCodeFragment = typeCodeFragments[i];
      try {
        PsiType type = typeCodeFragment.getType();
        if (!(type instanceof PsiClassType)) {
          return RefactoringBundle.message(
              "changeSignature.wrong.type.for.exception", typeCodeFragment.getText());
        }

        PsiClassType throwable =
            JavaPsiFacade.getInstance(myProject)
                .getElementFactory()
                .createTypeByFQClassName("java.lang.Throwable", type.getResolveScope());
        if (!throwable.isAssignableFrom(type)) {
          return RefactoringBundle.message(
              "changeSignature.not.throwable.type", typeCodeFragment.getText());
        }
        exceptionInfo.setType((PsiClassType) type);
      } catch (PsiTypeCodeFragment.TypeSyntaxException e) {
        return RefactoringBundle.message(
            "changeSignature.wrong.type.for.exception", typeCodeFragment.getText());
      } catch (PsiTypeCodeFragment.NoTypeException e) {
        return RefactoringBundle.message("changeSignature.no.type.for.exception");
      }
    }

    // warnings
    try {
      if (myMethod.canChangeReturnType() == MethodDescriptor.ReadWriteOption.ReadWrite) {
        if (!RefactoringUtil.isResolvableType(
            ((PsiTypeCodeFragment) myReturnTypeCodeFragment).getType())) {
          if (Messages.showOkCancelDialog(
                  myProject,
                  RefactoringBundle.message(
                      "changeSignature.cannot.resolve.return.type",
                      myReturnTypeCodeFragment.getText()),
                  RefactoringBundle.message("changeSignature.refactoring.name"),
                  Messages.getWarningIcon())
              != 0) {
            return EXIT_SILENTLY;
          }
        }
      }
      for (ParameterTableModelItemBase<ParameterInfoImpl> item : parameterInfos) {

        if (!RefactoringUtil.isResolvableType(
            ((PsiTypeCodeFragment) item.typeCodeFragment).getType())) {
          if (Messages.showOkCancelDialog(
                  myProject,
                  RefactoringBundle.message(
                      "changeSignature.cannot.resolve.parameter.type",
                      item.typeCodeFragment.getText(),
                      item.parameter.getName()),
                  RefactoringBundle.message("changeSignature.refactoring.name"),
                  Messages.getWarningIcon())
              != 0) {
            return EXIT_SILENTLY;
          }
        }
      }
    } catch (PsiTypeCodeFragment.IncorrectTypeException ignored) {
    }
    return null;
  }
  private void installPropertiesChangeListeners() {
    final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
    if (myVfsListener != null) {
      assert false;
      virtualFileManager.removeVirtualFileListener(myVfsListener);
    }
    myVfsListener =
        new VirtualFileAdapter() {
          @Override
          public void fileCreated(@NotNull VirtualFileEvent event) {
            if (PropertiesImplUtil.isPropertiesFile(event.getFile(), myProject)) {
              recreateEditorsPanel();
            }
          }

          @Override
          public void fileDeleted(@NotNull VirtualFileEvent event) {
            for (PropertiesFile file : myEditors.keySet()) {
              if (Comparing.equal(file.getVirtualFile(), event.getFile())) {
                recreateEditorsPanel();
                return;
              }
            }
          }

          @Override
          public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
            if (PropertiesImplUtil.isPropertiesFile(event.getFile(), myProject)) {
              if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) {
                recreateEditorsPanel();
              } else {
                updateEditorsFromProperties();
              }
            }
          }
        };

    virtualFileManager.addVirtualFileListener(myVfsListener, this);
    PsiTreeChangeAdapter psiTreeChangeAdapter =
        new PsiTreeChangeAdapter() {
          @Override
          public void childAdded(@NotNull PsiTreeChangeEvent event) {
            childrenChanged(event);
          }

          @Override
          public void childRemoved(@NotNull PsiTreeChangeEvent event) {
            childrenChanged(event);
          }

          @Override
          public void childReplaced(@NotNull PsiTreeChangeEvent event) {
            childrenChanged(event);
          }

          @Override
          public void childMoved(@NotNull PsiTreeChangeEvent event) {
            childrenChanged(event);
          }

          @Override
          public void childrenChanged(@NotNull PsiTreeChangeEvent event) {
            final PsiFile file = event.getFile();
            PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(file);
            if (propertiesFile == null) return;
            if (!propertiesFile.getResourceBundle().equals(myResourceBundle)) return;
            updateEditorsFromProperties();
          }
        };
    PsiManager.getInstance(myProject).addPsiTreeChangeListener(psiTreeChangeAdapter, this);
  }