com.intellij.refactoring.listeners.RefactoringElementListener Java Examples

The following examples show how to use com.intellij.refactoring.listeners.RefactoringElementListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RefactoringTransactionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void elementRenamed(@Nonnull final PsiElement newElement) {
  myRunnables.add(new Runnable() {
    @Override
    public void run() {
      for (RefactoringElementListener refactoringElementListener : myListenerList) {
        try {
          refactoringElementListener.elementRenamed(newElement);
        }
        catch (Throwable e) {
          LOG.error(e);
        }
      }
    }
  });
}
 
Example #2
Source File: SdkRunConfig.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
@Override
public RefactoringElementListener getRefactoringElementListener(final PsiElement element) {
  final String filePath = getFields().getFilePath();
  if (filePath == null) return null;

  final String affectedPath = getAffectedPath(element);
  if (affectedPath == null) return null;

  if (element instanceof PsiFile && filePath.equals(affectedPath)) {
    return new RenameRefactoringListener(affectedPath);
  }

  if (element instanceof PsiDirectory && filePath.startsWith(affectedPath + "/")) {
    return new RenameRefactoringListener(affectedPath);
  }

  return null;
}
 
Example #3
Source File: RefactoringTransactionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void elementMoved(@Nonnull final PsiElement newElement) {
  myRunnables.add(new Runnable() {
    @Override
    public void run() {
      for (RefactoringElementListener refactoringElementListener : myListenerList) {
        try {
          refactoringElementListener.elementMoved(newElement);
        }
        catch (Throwable e) {
          LOG.error(e);
        }
      }
    }
  });
}
 
Example #4
Source File: SdkRunConfig.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
@Override
public RefactoringElementListener getRefactoringElementListener(final PsiElement element) {
  final String filePath = getFields().getFilePath();
  if (filePath == null) return null;

  final String affectedPath = getAffectedPath(element);
  if (affectedPath == null) return null;

  if (element instanceof PsiFile && filePath.equals(affectedPath)) {
    return new RenameRefactoringListener(affectedPath);
  }

  if (element instanceof PsiDirectory && filePath.startsWith(affectedPath + "/")) {
    return new RenameRefactoringListener(affectedPath);
  }

  return null;
}
 
Example #5
Source File: RenameFileDirectoryTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void testExecute_RenameFileNoChanges() {
    when(mockVirtualFile.getPath()).thenReturn(CURRENT_FILE_PATH);
    when(CommandUtils.getStatusForFiles(any(Project.class), eq(mockServerContext), eq(ImmutableList.of(CURRENT_FILE_PATH))))
            .thenReturn(Collections.EMPTY_LIST);

    RenameFileDirectory.execute(mockPsiFile, NEW_FILE_NAME, usageInfos, mockListener);

    verifyStatic(times(1));
    CommandUtils.renameFile(eq(mockServerContext), eq(CURRENT_FILE_PATH), eq(NEW_FILE_PATH));
    PersistentFS.getInstance().processEvents(any(List.class));
    verify(mockListener).elementRenamed(mockPsiFile);

    verifyStatic(never());
    RenameUtil.doRenameGenericNamedElement(any(PsiElement.class), any(String.class), any(UsageInfo[].class), any(RefactoringElementListener.class));
}
 
Example #6
Source File: RenameFileDirectoryTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void testExecute_RenameDirectoryNoChanges() {
    String dirName = Path.combine("/path/to/the", "directory");
    when(mockVirtualFile.getPath()).thenReturn(dirName);
    when(CommandUtils.getStatusForFiles(any(Project.class), eq(mockServerContext), eq(ImmutableList.of(dirName))))
            .thenReturn(Collections.EMPTY_LIST);

    RenameFileDirectory.execute(mockPsiFile, NEW_DIRECTORY_NAME, usageInfos, mockListener);

    verifyStatic(times(1));
    CommandUtils.renameFile(eq(mockServerContext), eq(dirName), eq(Path.combine("/path/to/the", "newDirectory")));
    PersistentFS.getInstance().processEvents(any(List.class));
    verify(mockListener).elementRenamed(mockPsiFile);

    verifyStatic(never());
    RenameUtil.doRenameGenericNamedElement(any(PsiElement.class), any(String.class), any(UsageInfo[].class), any(RefactoringElementListener.class));
}
 
Example #7
Source File: RenameFileDirectoryTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void testExecute_RenameFileEditChanges() {
    when(mockPendingChange.getChangeTypes()).thenReturn(ImmutableList.of(ServerStatusType.EDIT));
    when(mockVirtualFile.getPath()).thenReturn(CURRENT_FILE_PATH);
    when(CommandUtils.getStatusForFiles(any(Project.class), eq(mockServerContext), eq(ImmutableList.of(CURRENT_FILE_PATH))))
            .thenReturn(ImmutableList.of(mockPendingChange));

    RenameFileDirectory.execute(mockPsiFile, NEW_FILE_NAME, usageInfos, mockListener);

    verifyStatic(times(1));
    CommandUtils.renameFile(eq(mockServerContext), eq(CURRENT_FILE_PATH), eq(NEW_FILE_PATH));
    PersistentFS.getInstance().processEvents(any(List.class));
    verify(mockListener).elementRenamed(mockPsiFile);

    verifyStatic(never());
    RenameUtil.doRenameGenericNamedElement(any(PsiElement.class), any(String.class), any(UsageInfo[].class), any(RefactoringElementListener.class));
}
 
Example #8
Source File: RenameFileDirectoryTest.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Test
public void testExecute_RenameFileEditRenameChanges() {
    when(mockPendingChange.getChangeTypes()).thenReturn(ImmutableList.of(ServerStatusType.EDIT, ServerStatusType.RENAME));
    when(mockVirtualFile.getPath()).thenReturn(CURRENT_FILE_PATH);
    when(CommandUtils.getStatusForFiles(any(Project.class), eq(mockServerContext), eq(ImmutableList.of(CURRENT_FILE_PATH))))
            .thenReturn(ImmutableList.of(mockPendingChange));

    RenameFileDirectory.execute(mockPsiFile, NEW_FILE_NAME, usageInfos, mockListener);

    verifyStatic(times(1));
    CommandUtils.renameFile(eq(mockServerContext), eq(CURRENT_FILE_PATH), eq(NEW_FILE_PATH));
    PersistentFS.getInstance().processEvents(any(List.class));
    verify(mockListener).elementRenamed(mockPsiFile);

    verifyStatic(never());
    RenameUtil.doRenameGenericNamedElement(any(PsiElement.class), any(String.class), any(UsageInfo[].class), any(RefactoringElementListener.class));
}
 
Example #9
Source File: RefactoringTransactionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void addAffectedElement(PsiElement oldElement) {
  if(myOldElementToListenerListMap.get(oldElement) != null) return;
  ArrayList<RefactoringElementListener> listenerList = new ArrayList<RefactoringElementListener>();
  for (RefactoringElementListenerProvider provider : myListenerProviders) {
    try {
      final RefactoringElementListener listener = provider.getListener(oldElement);
      if (listener != null) {
        listenerList.add(listener);
      }
    }
    catch (Throwable e) {
      LOG.error(e);
    }
  }
  myOldElementToListenerListMap.put(oldElement, listenerList);
}
 
Example #10
Source File: MoveDirectoryWithClassesHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean move(PsiFile psiFile,
                       PsiDirectory moveDestination,
                       Map<PsiElement, PsiElement> oldToNewElementsMapping,
                       List<PsiFile> movedFiles,
                       RefactoringElementListener listener) {
  if (moveDestination.equals(psiFile.getContainingDirectory())) {
    return false;
  }

  MoveFileHandler.forElement(psiFile).prepareMovedFile(psiFile, moveDestination, oldToNewElementsMapping);

  PsiFile moving = moveDestination.findFile(psiFile.getName());
  if (moving == null) {
    MoveFilesOrDirectoriesUtil.doMoveFile(psiFile, moveDestination);
  }
  moving = moveDestination.findFile(psiFile.getName());
  movedFiles.add(moving);
  listener.elementMoved(psiFile);
  return true;
}
 
Example #11
Source File: RenameUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void doRename(final PsiElement element, String newName, UsageInfo[] usages, final Project project,
                            @Nullable final RefactoringElementListener listener) throws IncorrectOperationException{
  final RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(element);
  final String fqn = element instanceof PsiFile ? ((PsiFile)element).getVirtualFile().getPath() : QualifiedNameProviders.elementToFqn(element);
  if (fqn != null) {
    UndoableAction action = new BasicUndoableAction() {
      @Override
      public void undo() throws UnexpectedUndoException {
        if (listener instanceof UndoRefactoringElementListener) {
          ((UndoRefactoringElementListener)listener).undoElementMovedOrRenamed(element, fqn);
        }
      }

      @Override
      public void redo() throws UnexpectedUndoException {
      }
    };
    UndoManager.getInstance(project).undoableActionPerformed(action);
  }
  processor.renameElement(element, newName, usages, listener);
}
 
Example #12
Source File: RefactoringScopeElementListenerProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public RefactoringElementListener getListener(PsiElement element) {
  final PsiFile containingFile = element.getContainingFile();
  if (!(element instanceof PsiQualifiedNamedElement)) return null;
  final String oldName = ((PsiQualifiedNamedElement)element).getQualifiedName();
  RefactoringElementListenerComposite composite = null;
  for (final NamedScopesHolder holder : NamedScopeManager.getAllNamedScopeHolders(element.getProject())) {
    final NamedScope[] scopes = holder.getEditableScopes();
    for (int i = 0; i < scopes.length; i++) {
      final NamedScope scope = scopes[i];
      final PackageSet packageSet = scope.getValue();
      if (packageSet != null && (containingFile == null || packageSet.contains(containingFile, holder))) {
        composite = traverse(new OldScopeDescriptor(oldName, scope, i, holder), composite, packageSet);
      }
    }
  }
  return composite;
}
 
Example #13
Source File: RunConfigurationRefactoringElementListenerProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public RefactoringElementListener getListener(final PsiElement element) {
  RefactoringElementListenerComposite composite = null;
  final RunConfiguration[] configurations = RunManager.getInstance(element.getProject()).getAllConfigurations();

  for (RunConfiguration configuration : configurations) {
    if (configuration instanceof RefactoringListenerProvider) { // todo: perhaps better way to handle listeners?
      final RefactoringElementListener listener;
      try {
        listener = ((RefactoringListenerProvider)configuration).getRefactoringElementListener(element);
      }
      catch (Exception e) {
        LOG.error(e);
        continue;
      }
      if (listener != null) {
        if (composite == null) {
          composite = new RefactoringElementListenerComposite();
        }
        composite.addListener(listener);
      }
    }
  }
  return composite;
}
 
Example #14
Source File: WorkspaceEditHandler.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
public static void applyEdit(PsiElement elem, String newName, UsageInfo[] infos,
                             RefactoringElementListener listener, List<VirtualFile> openedEditors) {
    Map<String, List<TextEdit>> edits = new HashMap<>();
    if (elem instanceof LSPPsiElement) {
        LSPPsiElement lspElem = (LSPPsiElement) elem;
        if (Stream.of(infos).allMatch(info -> info.getElement() instanceof LSPPsiElement)) {
            Stream.of(infos).forEach(ui -> {
                Editor editor = FileUtils.editorFromVirtualFile(ui.getVirtualFile(), ui.getProject());
                TextRange range = ui.getElement().getTextRange();
                Range lspRange = new Range(DocumentUtils.offsetToLSPPos(editor, range.getStartOffset()),
                        DocumentUtils.offsetToLSPPos(editor, range.getEndOffset()));
                TextEdit edit = new TextEdit(lspRange, newName);
                String uri = null;
                try {
                    uri = FileUtils.sanitizeURI(
                            new URL(ui.getVirtualFile().getUrl().replace(" ", FileUtils.SPACE_ENCODED)).toURI()
                                    .toString());
                } catch (MalformedURLException | URISyntaxException e) {
                    LOG.warn(e);
                }
                if (edits.keySet().contains(uri)) {
                    edits.get(uri).add(edit);
                } else {
                    List<TextEdit> textEdits = new ArrayList<>();
                    textEdits.add(edit);
                    edits.put(uri, textEdits);
                }
            });
            WorkspaceEdit workspaceEdit = new WorkspaceEdit(edits);
            applyEdit(workspaceEdit, "Rename " + lspElem.getName() + " to " + newName, openedEditors);
        }
    }
}
 
Example #15
Source File: RefactoringTransactionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void undoElementMovedOrRenamed(@Nonnull PsiElement newElement, @Nonnull String oldQualifiedName) {
  for (RefactoringElementListener listener : myListenerList) {
    if (listener instanceof UndoRefactoringElementListener) {
      ((UndoRefactoringElementListener)listener).undoElementMovedOrRenamed(newElement, oldQualifiedName);
    }
  }
}
 
Example #16
Source File: RefactoringTransactionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public RefactoringElementListener getElementListener(PsiElement oldElement) {
  RefactoringElementListener listener =
    myOldElementToTransactionListenerMap.get(oldElement);
  if(listener == null) {
    listener = new MyRefactoringElementListener(oldElement);
    myOldElementToTransactionListenerMap.put(oldElement, listener);
  }
  return listener;
}
 
Example #17
Source File: RenameRefactoringProvider.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public RefactoringElementListener getListener(PsiElement psiElement) {
    if(!(psiElement instanceof  PsiFile))
    {
        return null;
    }

    PsiFile file = (PsiFile) psiElement;
    String extension = file.getVirtualFile().getExtension();

    if(!ServiceManager.getService(file.getProject(), DojoSettings.class).isNeedsMoreDojoEnabled())
    {
        return null; // don't want to refactor if we've disabled Needs More Dojo.
    }

    if(!ServiceManager.getService(file.getProject(), DojoSettings.class).isRefactoringEnabled())
    {
        return null;
    }

    if(!extension.equals("js"))
    {
        return null;
    }

    if(!file.getText().contains("define"))
    {
        return null; // not a dojo module
    }

    return new RenameRefactoringListener(file, file.getName());
}
 
Example #18
Source File: HaxeRenameProcessor.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public void renameElement(@NotNull PsiElement element,
                          @NotNull String newName,
                          @NotNull UsageInfo[] usages,
                          @Nullable RefactoringElementListener listener) throws IncorrectOperationException {
  // Here, the element is actually being renamed.  If it shouldn't be renamed, then we'll just skip it.
  // We have to do so, because the element to be renamed is still on the list of elements due to
  // the PomRenameProcessor stating that it could handle the rename after we've already substituted the
  // proper elements.  But since we are handling it anyway the PomRenameProcessor is cut out of the loop.
  if (canBeRenamed(element)) {
    super.renameElement(element, newName, usages, listener);
  }
}
 
Example #19
Source File: LSPRenameProcessor.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void renameElement(@NotNull PsiElement element, @NotNull String newName, @NotNull UsageInfo[] usages,
                          RefactoringElementListener listener) {
    WorkspaceEditHandler.applyEdit(element, newName, usages, listener, new ArrayList<>(openedEditors));
    openedEditors.clear();
    elements.clear();
    curElem = null;
}
 
Example #20
Source File: RefactoringListenerProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
@javax.annotation.Nullable
RefactoringElementListener getRefactoringElementListener(final PsiElement element);
 
Example #21
Source File: RenamePsiElementProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void renameElement(final PsiElement element, String newName, UsageInfo[] usages,
                          @Nullable RefactoringElementListener listener) throws IncorrectOperationException {
  RenameUtil.doRenameGenericNamedElement(element, newName, usages, listener);
}
 
Example #22
Source File: RenamePsiElementProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
public Runnable getPostRenameCallback(final PsiElement element, final String newName, final RefactoringElementListener elementListener) {
  return null;
}
 
Example #23
Source File: MoveRefactoringProvider.java    From needsmoredojo with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public RefactoringElementListener getListener(PsiElement psiElement)
{
    if(!(psiElement instanceof PsiFile))
    {
        return null;
    }

    PsiFile file = (PsiFile) psiElement;
    String extension = file.getVirtualFile().getExtension();

    if(!extension.equals("js"))
    {
        return null;
    }

    if(!file.getText().contains("define"))
    {
        return null; // not a dojo module
    }

    if(!ServiceManager.getService(file.getProject(), DojoSettings.class).isNeedsMoreDojoEnabled())
    {
        return null; // don't want to refactor if we've disabled Needs More Dojo.
    }

    if(!ServiceManager.getService(file.getProject(), DojoSettings.class).isRefactoringEnabled())
    {
        return null;
    }

    VirtualFile[] sources = SourcesLocator.getProjectSourceDirectories(file.getProject(), true);
    if(sources.length == 0 || sources[0] == null)
    {
        // no project sources, so we can't really refactor
        return null;
    }

    return new MoveRefactoringListener(file, file.getName());
}
 
Example #24
Source File: MoveDirectoryWithClassesHelper.java    From consulo with Apache License 2.0 4 votes vote down vote up
public abstract boolean move(PsiFile file,
PsiDirectory moveDestination,
Map<PsiElement, PsiElement> oldToNewElementsMapping,
List<PsiFile> movedFiles,
RefactoringElementListener listener);
 
Example #25
Source File: RenameFileDirectory.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
public static void execute(final PsiElement element, final String newName, final UsageInfo[] usages,
                           @Nullable final RefactoringElementListener listener) throws IncorrectOperationException {
    try {
        final VirtualFile virtualFile;
        if (element instanceof PsiFile) {
            logger.info("Renaming file...");
            virtualFile = ((PsiFile) element).getVirtualFile();
        } else if (element instanceof PsiDirectory) {
            logger.info("Renaming directory...");
            virtualFile = ((PsiDirectory) element).getVirtualFile();
        } else {
            // should never reach here since we check if file/directory before making a rename
            logger.warn("RenameFile: failed to find proper object to rename: " + element.getClass());
            throw new IncorrectOperationException("Can't perform rename on objects other than files and directories");
        }

        final String currentPath = virtualFile.getPath();
        final String parentDirectory = virtualFile.getParent().getPath();
        final String newPath = Path.combine(parentDirectory, newName);
        final Project project = element.getProject();

        // a single file may have 0, 1, or 2 pending changes to it
        // 0 - file has not been touched in the local workspace
        // 1 - file has versioned OR unversioned changes
        // 2 - file has versioned AND unversioned changes (rare but can happen)
        final List<PendingChange> pendingChanges = new ArrayList<>(2);
        pendingChanges.addAll(
                CommandUtils.getStatusForFiles(
                        project,
                        TFSVcs.getInstance(project).getServerContext(true),
                        ImmutableList.of(currentPath)));

        // ** Rename logic **
        // If 1 change and it's an add that means it's a new unversioned file so rename thru the file system
        // Anything else can be renamed
        // Deleted files should not be at this point since IDE disables rename option for them
        if (pendingChanges.size() == 1 && pendingChanges.get(0).getChangeTypes().contains(ServerStatusType.ADD)) {
            logger.info("Renaming unversioned file thru file system");
            RenameUtil.doRenameGenericNamedElement(element, newName, usages, listener);
        } else {
            logger.info("Renaming file thru tf commandline");
            CommandUtils.renameFile(TFSVcs.getInstance(project).getServerContext(true), currentPath, newPath);

            // this alerts that a rename has taken place so any additional processing can take place
            final VFileEvent event = new VFilePropertyChangeEvent(element.getManager(), virtualFile, "name", currentPath, newName, false);
            PersistentFS.getInstance().processEvents(Collections.singletonList(event));
        }
    } catch (Throwable t) {
        logger.warn("renameElement experienced a failure while trying to rename a file", t);
        throw new IncorrectOperationException(t);
    }

    if (listener != null) {
        listener.elementRenamed(element);
    }
}
 
Example #26
Source File: SdkAttachConfig.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nullable
@Override
public RefactoringElementListener getRefactoringElementListener(PsiElement element) {
  return null;
}
 
Example #27
Source File: SdkAttachConfig.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Nullable
@Override
public RefactoringElementListener getRefactoringElementListener(PsiElement element) {
  return null;
}
 
Example #28
Source File: RefactoringTransaction.java    From consulo with Apache License 2.0 2 votes vote down vote up
/**
 * Returns listener for element (element must belong to set of affected elements).
 * Refactorings should call appropriate methods of a listener, giving a modified (or new) element.
 * @param element
 * @return
 */
RefactoringElementListener getElementListener(PsiElement element);