com.intellij.refactoring.util.CommonRefactoringUtil Java Examples

The following examples show how to use com.intellij.refactoring.util.CommonRefactoringUtil. 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: ChangeSignatureDialogBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void doAction() {
  if (myParametersTable != null) {
    TableUtil.stopEditing(myParametersTable);
  }
  String message = validateAndCommitData();
  if (message != null) {
    if (message != EXIT_SILENTLY) {
      CommonRefactoringUtil.showErrorMessage(getTitle(), message, getHelpId(), myProject);
    }
    return;
  }
  if (myMethodsToPropagateParameters != null && !mayPropagateParameters()) {
    Messages.showWarningDialog(myProject, RefactoringBundle.message("changeSignature.parameters.wont.propagate"),
                               ChangeSignatureHandler.REFACTORING_NAME);
    myMethodsToPropagateParameters = null;
  }

  invokeRefactoring(createRefactoringProcessor());
}
 
Example #2
Source File: InlineRefactoringActionHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(@Nonnull final Project project, Editor editor, PsiFile file, DataContext dataContext) {
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);

  PsiElement element = dataContext.getData(LangDataKeys.PSI_ELEMENT);
  if (element == null) {
    element = BaseRefactoringAction.getElementAtCaret(editor, file);
  }
  if (element != null) {
    for(InlineActionHandler handler: Extensions.getExtensions(InlineActionHandler.EP_NAME)) {
      if (handler.canInlineElementInEditor(element, editor)) {
        handler.inlineElement(project, editor, element);
        return;
      }
    }

    if (invokeInliner(editor, element)) return;

    String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.method.or.local.name"));
    CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, null);
  }
}
 
Example #3
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nullable
protected PsiElement performRefactoring(@Nonnull CSharpIntroduceOperation operation)
{
	PsiElement anchor = operation.isReplaceAll() ? findAnchor(operation.getOccurrences()) : findAnchor(operation.getInitializer());
	if(anchor == null)
	{
		CommonRefactoringUtil.showErrorHint(operation.getProject(), operation.getEditor(), RefactoringBundle.getCannotRefactorMessage(null), RefactoringBundle.getCannotRefactorMessage(null),
				null);
		return null;
	}
	PsiElement declaration = createDeclaration(operation);
	if(declaration == null)
	{
		showCannotPerformError(operation.getProject(), operation.getEditor());
		return null;
	}

	declaration = performReplace(declaration, operation);
	if(declaration != null)
	{
		declaration = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(declaration);
	}
	return declaration;
}
 
Example #4
Source File: ExtractSuperclassHandler.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  int offset = editor.getCaretModel().getOffset();
  PsiElement element = file.findElementAt(offset);
  while (true) {
    if (element == null || element instanceof PsiFile) {
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.class"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_SUPERCLASS);
      return;
    }
    if (element instanceof PsiClass) {
      invoke(project, new PsiElement[]{element}, dataContext);
      return;
    }
    element = element.getParent();
  }
}
 
Example #5
Source File: HaxePushDownHandler.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext context) {
  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 HaxeClassDeclaration || element instanceof HaxeFieldDeclaration || element instanceof HaxeMethod) {
      //if (element instanceof JspClass) {
      //  RefactoringMessageUtil.showNotSupportedForJspClassesError(project, editor, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
      //  return;
      //}
      invoke(project, new PsiElement[]{element}, context);
      return;
    }
    element = element.getParent();
  }
}
 
Example #6
Source File: ExtractInterfaceHandler.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
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("error.wrong.caret.position.class"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.EXTRACT_INTERFACE);
      return;
    }
    if (element instanceof PsiClass && !(element instanceof PsiAnonymousClass)) {
      invoke(project, new PsiElement[]{element}, dataContext);
      return;
    }
    element = element.getParent();
  }
}
 
Example #7
Source File: PsiElementRenameHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void invoke(PsiElement element, Project project, PsiElement nameSuggestionContext, @Nullable Editor editor) {
  if (element != null && !canRename(project, editor, element)) {
    return;
  }

  VirtualFile contextFile = PsiUtilCore.getVirtualFile(nameSuggestionContext);

  if (nameSuggestionContext != null &&
      nameSuggestionContext.isPhysical() &&
      (contextFile == null || !ScratchUtil.isScratch(contextFile) && !PsiManager.getInstance(project).isInProject(nameSuggestionContext))) {
    final String message = "Selected element is used from non-project files. These usages won't be renamed. Proceed anyway?";
    if (ApplicationManager.getApplication().isUnitTestMode()) throw new CommonRefactoringUtil.RefactoringErrorHintException(message);
    if (Messages.showYesNoDialog(project, message, RefactoringBundle.getCannotRefactorMessage(null), Messages.getWarningIcon()) != Messages.YES) {
      return;
    }
  }

  FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.rename");

  rename(element, project, nameSuggestionContext, editor);
}
 
Example #8
Source File: ClassRefactoringHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  int offset = editor.getCaretModel().getOffset();
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  final PsiElement position = file.findElementAt(offset);
  PsiElement element = position;

  while (true) {
    if (element == null || element instanceof PsiFile) {
      String message = RefactoringBundle
        .getCannotRefactorMessage(getInvalidPositionMessage());
      CommonRefactoringUtil.showErrorHint(project, editor, message, getTitle(), getHelpId());
      return;
    }

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return;

    if (acceptsElement(element)) {
      invoke(project, new PsiElement[]{position}, dataContext);
      return;
    }
    element = element.getParent();
  }
}
 
Example #9
Source File: EncodingUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void saveIn(@Nonnull final Document document, final Editor editor, @Nonnull final VirtualFile virtualFile, @Nonnull final Charset charset) {
  FileDocumentManager documentManager = FileDocumentManager.getInstance();
  documentManager.saveDocument(document);
  final Project project = ProjectLocator.getInstance().guessProjectForFile(virtualFile);
  boolean writable = project == null ? virtualFile.isWritable() : ReadonlyStatusHandler.ensureFilesWritable(project, virtualFile);
  if (!writable) {
    CommonRefactoringUtil.showErrorHint(project, editor, "Cannot save the file " + virtualFile.getPresentableUrl(), "Unable to Save", null);
    return;
  }

  EncodingProjectManagerImpl.suppressReloadDuring(() -> {
    EncodingManager.getInstance().setEncoding(virtualFile, charset);
    try {
      ApplicationManager.getApplication().runWriteAction((ThrowableComputable<Object, IOException>)() -> {
        virtualFile.setCharset(charset);
        LoadTextUtil.write(project, virtualFile, virtualFile, document.getText(), document.getModificationStamp());
        return null;
      });
    }
    catch (IOException io) {
      Messages.showErrorDialog(project, io.getMessage(), "Error Writing File");
    }
  });
}
 
Example #10
Source File: SafeDeleteHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  PsiElement element = dataContext.getData(CommonDataKeys.PSI_ELEMENT);
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  if (element == null || !SafeDeleteProcessor.validElement(element)) {
    String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("is.not.supported.in.the.current.context", REFACTORING_NAME));
    CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, "refactoring.safeDelete");
    return;
  }
  invoke(project, new PsiElement[]{element}, dataContext);
}
 
Example #11
Source File: ExtractIncludeDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doOKAction() {
  final Project project = myCurrentDirectory.getProject();

  final String directoryName = myTargetDirectoryField.getText().replace(File.separatorChar, '/');
  final String targetFileName = getTargetFileName();

  if (isFileExist(directoryName, targetFileName)) {
    Messages.showErrorDialog(project, RefactoringBundle.message("file.already.exist", targetFileName), RefactoringBundle.message("file.already.exist.title"));
    return;
  }

  final FileType type = FileTypeChooser.getKnownFileTypeOrAssociate(targetFileName);
  if (type == null) {
    return;
  }

  CommandProcessor.getInstance().executeCommand(project, new Runnable() {
    @Override
    public void run() {
      final Runnable action = new Runnable() {
        @Override
        public void run() {
          try {
            PsiDirectory targetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(project), directoryName);
            targetDirectory.checkCreateFile(targetFileName);
            final String webPath = PsiFileSystemItemUtil.getRelativePath(myCurrentDirectory, targetDirectory);
            myTargetDirectory = webPath == null ? null : targetDirectory;
          }
          catch (IncorrectOperationException e) {
            CommonRefactoringUtil.showErrorMessage(REFACTORING_NAME, e.getMessage(), null, project);
          }
        }
      };
      ApplicationManager.getApplication().runWriteAction(action);
    }
  }, RefactoringBundle.message("create.directory"), null);
  if (myTargetDirectory == null) return;
  super.doOKAction();
}
 
Example #12
Source File: MoveHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * called by an Action in AtomicAction when refactoring is invoked from Editor
 */
@Override
public void invoke(@Nonnull 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) {
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.at.the.class.method.or.field.to.be.refactored"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, null);
      return;
    }

    if (tryToMoveElement(element, project, dataContext, null, editor)) {
      return;
    }
    final TextRange range = element.getTextRange();
    if (range != null) {
      int relative = offset - range.getStartOffset();
      final PsiReference reference = element.findReferenceAt(relative);
      if (reference != null) {
        final PsiElement refElement = reference.resolve();
        if (refElement != null && tryToMoveElement(refElement, project, dataContext, reference, editor)) return;
      }
    }

    element = element.getParent();
  }
}
 
Example #13
Source File: MoveFilesOrDirectoriesDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doOKAction() {
  PropertiesComponent.getInstance().setValue(MOVE_FILES_OPEN_IN_EDITOR, myOpenInEditorCb.isSelected(), false);
  //myTargetDirectoryField.getChildComponent().addCurrentTextToHistory();
  RecentsManager.getInstance(myProject).registerRecentEntry(RECENT_KEYS, myTargetDirectoryField.getChildComponent().getText());
  RefactoringSettings.getInstance().MOVE_SEARCH_FOR_REFERENCES_FOR_FILE = myCbSearchForReferences.isSelected();

  if (DumbService.isDumb(myProject)) {
    Messages.showMessageDialog(myProject, "Move refactoring is not available while indexing is in progress", "Indexing", null);
    return;
  }

  CommandProcessor.getInstance().executeCommand(myProject, () -> {
    final Runnable action = () -> {
      String directoryName = myTargetDirectoryField.getChildComponent().getText().replace(File.separatorChar, '/');
      try {
        myTargetDirectory = DirectoryUtil.mkdirs(PsiManager.getInstance(myProject), directoryName);
      }
      catch (IncorrectOperationException e) {
        // ignore
      }
    };

    ApplicationManager.getApplication().runWriteAction(action);
    if (myTargetDirectory == null) {
      CommonRefactoringUtil.showErrorMessage(getTitle(),
                                             RefactoringBundle.message("cannot.create.directory"), myHelpID, myProject);
      return;
    }
    myCallback.run(this);
  }, RefactoringBundle.message("move.title"), null);
}
 
Example #14
Source File: InplaceRefactoring.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void unableToStartWarning(Project project, Editor editor) {
  final StartMarkAction startMarkAction = StartMarkAction.canStart(project);
  final String message = startMarkAction.getCommandName() + " is not finished yet.";
  final Document oldDocument = startMarkAction.getDocument();
  if (editor == null || oldDocument != editor.getDocument()) {
    final int exitCode = Messages.showYesNoDialog(project, message,
                                                  RefactoringBundle.getCannotRefactorMessage(null),
                                                  "Continue Started", "Cancel Started", Messages.getErrorIcon());
    navigateToStarted(oldDocument, project, exitCode);
  }
  else {
    CommonRefactoringUtil.showErrorHint(project, editor, message, RefactoringBundle.getCannotRefactorMessage(null), null);
  }
}
 
Example #15
Source File: PsiElementRenameHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean canRename(Project project, Editor editor, PsiElement element) throws CommonRefactoringUtil.RefactoringErrorHintException {
  String message = renameabilityStatus(project, element);
  if (StringUtil.isNotEmpty(message)) {
    showErrorMessage(project, editor, message);
    return false;
  }
  return true;
}
 
Example #16
Source File: HaxePullUpHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private boolean checkWritable(PsiClass superClass, MemberInfo[] infos) {
  if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, superClass)) return false;
  for (MemberInfo info : infos) {
    if (info.getMember() instanceof PsiClass && info.getOverrides() != null) continue;
    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, info.getMember())) return false;
  }
  return true;
}
 
Example #17
Source File: CSharpCopyClassHandlerDelegate.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
private static void doCopy(@Nonnull CSharpTypeDeclaration typeDeclaration, @Nullable PsiDirectory defaultTargetDirectory, Project project)
{
	PsiDirectory targetDirectory;
	String newName;
	boolean openInEditor;
	VirtualFile virtualFile = PsiUtilCore.getVirtualFile(typeDeclaration);
	CopyFilesOrDirectoriesDialog dialog = new CopyFilesOrDirectoriesDialog(new PsiElement[]{typeDeclaration.getContainingFile()}, defaultTargetDirectory, project, false);
	if(dialog.showAndGet())
	{
		newName = dialog.getNewName();
		targetDirectory = dialog.getTargetDirectory();
		openInEditor = dialog.openInEditor();
	}
	else
	{
		return;
	}

	if(targetDirectory != null)
	{
		PsiManager manager = PsiManager.getInstance(project);
		try
		{
			if(virtualFile.isDirectory())
			{
				PsiFileSystemItem psiElement = manager.findDirectory(virtualFile);
				MoveFilesOrDirectoriesUtil.checkIfMoveIntoSelf(psiElement, targetDirectory);
			}
		}
		catch(IncorrectOperationException e)
		{
			CommonRefactoringUtil.showErrorHint(project, null, e.getMessage(), CommonBundle.getErrorTitle(), null);
			return;
		}

		CommandProcessor.getInstance().executeCommand(project, () -> doCopy(typeDeclaration, newName, targetDirectory, false, openInEditor), RefactoringBundle.message("copy.handler.copy.files" +
				".directories"), null);
	}
}
 
Example #18
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nullable
public PsiElement addDeclaration(CSharpIntroduceOperation operation, PsiElement declaration)
{
	PsiElement anchor = operation.isReplaceAll() ? findAnchor(operation.getOccurrences()) : findAnchor(operation.getInitializer());
	if(anchor == null)
	{
		CommonRefactoringUtil.showErrorHint(operation.getProject(), operation.getEditor(), RefactoringBundle.getCannotRefactorMessage(null), RefactoringBundle.getCannotRefactorMessage(null),
				null);
		return null;
	}
	final PsiElement parent = anchor.getParent();
	PsiElement psiElement = parent.addBefore(declaration, anchor);
	CodeStyleManager.getInstance(declaration.getProject()).reformat(psiElement);
	return psiElement;
}
 
Example #19
Source File: PushDownConflicts.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
protected void visitClassMemberReferenceElement(PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) {
  if(myMovedMembers.contains(classMember) && !myAbstractMembers.contains(classMember)) {
    String message = RefactoringBundle.message("0.uses.1.which.is.pushed.down", RefactoringUIUtil.getDescription(mySource, false),
                                               RefactoringUIUtil.getDescription(classMember, false));
    message = CommonRefactoringUtil.capitalize(message);
    myConflicts.putValue(mySource, message);
  }
}
 
Example #20
Source File: ExtractInterfaceHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public void invoke(@NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
  if (elements.length != 1) return;

  myProject = project;
  myClass = (PsiClass)elements[0];


  if (!CommonRefactoringUtil.checkReadOnlyStatus(project, myClass)) return;

  final ExtractInterfaceDialog dialog = new ExtractInterfaceDialog(myProject, myClass);
  if (!dialog.showAndGet() || !dialog.isExtractSuperclass()) {
    return;
  }
  final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
  ExtractSuperClassUtil.checkSuperAccessible(dialog.getTargetDirectory(), conflicts, myClass);
  if (!ExtractSuperClassUtil.showConflicts(dialog, conflicts, myProject)) return;
  CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        public void run() {
          myInterfaceName = dialog.getExtractedSuperName();
          mySelectedMembers = ArrayUtil.toObjectArray(dialog.getSelectedMemberInfos(), MemberInfo.class);
          myTargetDir = dialog.getTargetDirectory();
          myJavaDocPolicy = new DocCommentPolicy(dialog.getDocCommentPolicy());
          try {
            doRefactoring();
          }
          catch (IncorrectOperationException e) {
            LOG.error(e);
          }
        }
      });
    }
  }, REFACTORING_NAME, null);
}
 
Example #21
Source File: HaxeIntroduceHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void showCannotPerformError(Project project, Editor editor) {
  CommonRefactoringUtil.showErrorHint(
    project,
    editor,
    HaxeBundle.message("refactoring.introduce.selection.error"),
    myDialogTitle,
    "refactoring.extractMethod"
  );
}
 
Example #22
Source File: HaxePullUpHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext context) {
  int offset = editor.getCaretModel().getOffset();
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  PsiElement element = file.findElementAt(offset);
  //HaxeClassDeclaration classDeclaration;
  //PsiElement parentElement;

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

    /*classDeclaration = PsiTreeUtil.getParentOfType(element, HaxeClassDeclaration.class, false);

    parentElement = null;
    parentElement = PsiTreeUtil.getParentOfType(element, HaxeVarDeclaration.class, false);
    if (parentElement == null) {
      parentElement = PsiTreeUtil.getParentOfType(element, HaxeFunctionDeclarationWithAttributes.class, false);
    }*/

    if (element instanceof HaxeClassDeclaration || element instanceof HaxeInterfaceDeclaration || element instanceof PsiField || element instanceof PsiMethod) {
      invoke(project, new PsiElement[]{element}, context);
      return;
    }

    //if (classDeclaration != null) {
    //  invoke(project, context, classDeclaration, parentElement);
    //  return;
    //}
    element = element.getParent();
  }
}
 
Example #23
Source File: HaxeIntroduceHandler.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
protected void performAction(HaxeIntroduceOperation operation) {
  final PsiFile file = operation.getFile();
  if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) {
    return;
  }
  final Editor editor = operation.getEditor();
  if (editor.getSettings().isVariableInplaceRenameEnabled()) {
    final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
    if (templateState != null && !templateState.isFinished()) {
      return;
    }
  }

  PsiElement element1 = null;
  PsiElement element2 = null;
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (selectionModel.hasSelection()) {
    element1 = file.findElementAt(selectionModel.getSelectionStart());
    element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
  }
  else {
    if (smartIntroduce(operation)) {
      return;
    }
    final CaretModel caretModel = editor.getCaretModel();
    final Document document = editor.getDocument();
    int lineNumber = document.getLineNumber(caretModel.getOffset());
    if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
      element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
      element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
    }
  }
  if (element1 instanceof PsiWhiteSpace) {
    int startOffset = element1.getTextRange().getEndOffset();
    element1 = file.findElementAt(startOffset);
  }
  if (element2 instanceof PsiWhiteSpace) {
    int endOffset = element2.getTextRange().getStartOffset();
    element2 = file.findElementAt(endOffset - 1);
  }


  final Project project = operation.getProject();
  if (element1 == null || element2 == null) {
    showCannotPerformError(project, editor);
    return;
  }

  element1 = HaxeRefactoringUtil.getSelectedExpression(project, file, element1, element2);
  if (!isValidForExtraction(element1)) {
    showCannotPerformError(project, editor);
    return;
  }

  if (!checkIntroduceContext(file, editor, element1)) {
    return;
  }
  operation.setElement(element1);
  performActionOnElement(operation);
}
 
Example #24
Source File: PsiElementRenameHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
static void showErrorMessage(Project project, @Nullable Editor editor, String message) {
  CommonRefactoringUtil.showErrorHint(project, editor, message, RefactoringBundle.message("rename.title"), null);
}
 
Example #25
Source File: PostfixTemplatesUtils.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void showErrorHint(@Nonnull Project project, @Nonnull Editor editor) {
  CommonRefactoringUtil.showErrorHint(project, editor, "Can't expand postfix template", "Can't expand postfix template", "");
}
 
Example #26
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
private void showCannotPerformError(Project project, Editor editor)
{
	CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.message("refactoring.introduce.selection.error"), myDialogTitle, "refactoring.extractMethod");
}
 
Example #27
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
public void performAction(CSharpIntroduceOperation operation)
{
	final PsiFile file = operation.getFile();
	if(!CommonRefactoringUtil.checkReadOnlyStatus(file))
	{
		return;
	}
	final Editor editor = operation.getEditor();
	if(editor.getSettings().isVariableInplaceRenameEnabled())
	{
		final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
		if(templateState != null && !templateState.isFinished())
		{
			return;
		}
	}

	PsiElement element1 = null;
	PsiElement element2 = null;
	final SelectionModel selectionModel = editor.getSelectionModel();
	if(selectionModel.hasSelection())
	{
		element1 = file.findElementAt(selectionModel.getSelectionStart());
		element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
		if(element1 instanceof PsiWhiteSpace)
		{
			int startOffset = element1.getTextRange().getEndOffset();
			element1 = file.findElementAt(startOffset);
		}
		if(element2 instanceof PsiWhiteSpace)
		{
			int endOffset = element2.getTextRange().getStartOffset();
			element2 = file.findElementAt(endOffset - 1);
		}
	}
	else
	{
		if(smartIntroduce(operation))
		{
			return;
		}
		final CaretModel caretModel = editor.getCaretModel();
		final Document document = editor.getDocument();
		int lineNumber = document.getLineNumber(caretModel.getOffset());
		if((lineNumber >= 0) && (lineNumber < document.getLineCount()))
		{
			element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
			element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
		}
	}
	final Project project = operation.getProject();
	if(element1 == null || element2 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	element1 = CSharpRefactoringUtil.getSelectedExpression(project, file, element1, element2);
	if(element1 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	if(!checkIntroduceContext(file, editor, element1))
	{
		return;
	}
	operation.setElement(element1);
	performActionOnElement(operation);
}
 
Example #28
Source File: LombokElementRenameVetoHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void invokeInner(Project project, Editor editor) {
  CommonRefactoringUtil.showErrorHint(project, editor,
    RefactoringBundle.getCannotRefactorMessage("This element cannot be renamed."),
    RefactoringBundle.message("rename.title"), null);
}
 
Example #29
Source File: BaseRefactoringProcessor.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean ensureFilesWritable(@Nonnull Project project, @Nonnull Collection<? extends PsiElement> elements) {
  PsiElement[] psiElements = PsiUtilCore.toPsiElementArray(elements);
  return CommonRefactoringUtil.checkReadOnlyStatus(project, psiElements);
}
 
Example #30
Source File: CopyFilesOrDirectoriesHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
private static void doCopyAsFiles(PsiElement[] elements, @Nullable PsiDirectory defaultTargetDirectory, Project project) {
  PsiDirectory targetDirectory;
  String newName;
  boolean openInEditor;
  VirtualFile[] files = Arrays.stream(elements).map(el -> ((PsiFileSystemItem)el).getVirtualFile()).toArray(VirtualFile[]::new);
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    targetDirectory = defaultTargetDirectory;
    newName = null;
    openInEditor = true;
  }
  else {
    CopyFilesOrDirectoriesDialog dialog = new CopyFilesOrDirectoriesDialog(elements, defaultTargetDirectory, project, false);
    if (dialog.showAndGet()) {
      newName = elements.length == 1 ? dialog.getNewName() : null;
      targetDirectory = dialog.getTargetDirectory();
      openInEditor = dialog.openInEditor();
    }
    else {
      return;
    }
  }


  if (targetDirectory != null) {
    PsiManager manager = PsiManager.getInstance(project);
    try {
      for (VirtualFile file : files) {
        if (file.isDirectory()) {
          PsiFileSystemItem psiElement = manager.findDirectory(file);
          MoveFilesOrDirectoriesUtil.checkIfMoveIntoSelf(psiElement, targetDirectory);
        }
      }
    }
    catch (IncorrectOperationException e) {
      CommonRefactoringUtil.showErrorHint(project, null, e.getMessage(), CommonBundle.getErrorTitle(), null);
      return;
    }

    CommandProcessor.getInstance()
            .executeCommand(project, () -> copyImpl(files, newName, targetDirectory, false, openInEditor), RefactoringBundle.message("copy.handler.copy.files.directories"), null);

  }
}