Java Code Examples for com.intellij.openapi.command.CommandProcessor#getInstance()

The following examples show how to use com.intellij.openapi.command.CommandProcessor#getInstance() . 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: OkJsonUpdateNavigationHandler.java    From NutzCodeInsight with Apache License 2.0 6 votes vote down vote up
@Override
public void navigate(MouseEvent mouseEvent, PsiElement psiElement) {
    JsonFormat jsonFormat = new JsonFormat();
    if (value.startsWith(JSON_PREFIX)) {
        try {
            jsonFormat = GSON.fromJson(value.substring(JSON_PREFIX.length()), JsonFormat.class);
        } catch (Exception e) {
            Messages.showErrorDialog("json格式化信息书写错误!", "错误提示");
        }
    }
    Application applicationManager = ApplicationManager.getApplication();
    CommandProcessor processor = CommandProcessor.getInstance();
    Project project = psiElement.getProject();
    PsiFile psiFile = psiElement.getContainingFile();
    Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
    int startOffset = psiElement.getTextRange().getStartOffset();
    int endOffset = psiElement.getTextRange().getEndOffset();
    OkJsonFastEditor dialog = new OkJsonFastEditor(jsonFormat, (json) ->
            applicationManager.runWriteAction(() ->
                    processor.executeCommand(project, new DocumentReplace(document, startOffset, endOffset, json), "", document)
            )
    );
    dialog.pack();
    dialog.setVisible(true);
}
 
Example 2
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void startTemplateWithPrefix(final Editor editor,
                                    final TemplateImpl template,
                                    final int templateStart,
                                    @Nullable final PairProcessor<String, String> processor,
                                    @Nullable final String argument) {
  final int caretOffset = editor.getCaretModel().getOffset();
  final TemplateState templateState = initTemplateState(editor);
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(myProject, () -> {
    editor.getDocument().deleteString(templateStart, caretOffset);
    editor.getCaretModel().moveToOffset(templateStart);
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    editor.getSelectionModel().removeSelection();
    Map<String, String> predefinedVarValues = null;
    if (argument != null) {
      predefinedVarValues = new HashMap<>();
      predefinedVarValues.put(TemplateImpl.ARG, argument);
    }
    templateState.start(template, processor, predefinedVarValues);
  }, CodeInsightBundle.message("insert.code.template.command"), null);
}
 
Example 3
Source File: CloseAllEditorsAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent e) {
  final Project project = e.getData(CommonDataKeys.PROJECT);
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(project, () -> {
    final EditorWindow window = e.getData(EditorWindow.DATA_KEY);
    if (window != null) {
      final VirtualFile[] files = window.getFiles();
      for (final VirtualFile file : files) {
        window.closeFile(file);
      }
      return;
    }
    FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project);
    VirtualFile selectedFile = fileEditorManager.getSelectedFiles()[0];
    VirtualFile[] openFiles = fileEditorManager.getSiblings(selectedFile);
    for (final VirtualFile openFile : openFiles) {
      fileEditorManager.closeFile(openFile);
    }
  }, IdeBundle.message("command.close.all.editors"), null);
}
 
Example 4
Source File: FileStructurePopup.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean navigateSelectedElement() {
  AbstractTreeNode selectedNode = getSelectedNode();
  if (ApplicationManager.getApplication().isInternal()) {
    String enteredPrefix = mySpeedSearch.getEnteredPrefix();
    String itemText = getSpeedSearchText(selectedNode);
    if (StringUtil.isNotEmpty(enteredPrefix) && StringUtil.isNotEmpty(itemText)) {
      LOG.info("Chosen in file structure popup by prefix '" + enteredPrefix + "': '" + itemText + "'");
    }
  }

  Ref<Boolean> succeeded = new Ref<>();
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(myProject, () -> {
    if (selectedNode != null) {
      if (selectedNode.canNavigateToSource()) {
        selectedNode.navigate(true);
        myPopup.cancel();
        succeeded.set(true);
      }
      else {
        succeeded.set(false);
      }
    }
    else {
      succeeded.set(false);
    }

    IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation();
  }, "Navigate", null);
  return succeeded.get();
}
 
Example 5
Source File: SettingsPanel.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
public void setPreviewText(@Nonnull String text) {
    final CommandProcessor processor = CommandProcessor.getInstance();
    processor.executeCommand(null, () -> {
        final Application application = ApplicationManager.getApplication();
        application.runWriteAction(() -> {
            previewDocument.replaceString(INITIAL_OFFSET, previewDocument.getTextLength(), text);

            final int textLength = previewDocument.getTextLength();
            final CaretModel caret = previewEditor.getCaretModel();
            if (caret.getOffset() >= textLength) {
                caret.moveToOffset(textLength);
            }
        });
    }, null, null);
}
 
Example 6
Source File: ExecutionHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void openMessagesView(@Nonnull final ErrorViewPanel errorTreeView, @Nonnull final Project myProject, @Nonnull final String tabDisplayName) {
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(myProject, new Runnable() {
    @Override
    public void run() {
      final MessageView messageView = ServiceManager.getService(myProject, MessageView.class);
      final Content content = ContentFactory.getInstance().createContent(errorTreeView, tabDisplayName, true);
      messageView.getContentManager().addContent(content);
      Disposer.register(content, errorTreeView);
      messageView.getContentManager().setSelectedContent(content);
      removeContents(content, myProject, tabDisplayName);
    }
  }, "Open message view", null);
}
 
Example 7
Source File: ActionTracker.java    From consulo with Apache License 2.0 5 votes vote down vote up
void ignoreCurrentDocumentChange() {
  final CommandProcessor commandProcessor = CommandProcessor.getInstance();
  if (commandProcessor.getCurrentCommand() == null) return;

  myIgnoreDocumentChanges = true;
  commandProcessor.addCommandListener(new CommandListener() {
    @Override
    public void commandFinished(CommandEvent event) {
      commandProcessor.removeCommandListener(this);
      myIgnoreDocumentChanges = false;
    }
  });
}
 
Example 8
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void assertInsideCommand() {
  if (!myAssertThreading) return;
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  if (!commandProcessor.isUndoTransparentActionInProgress() && commandProcessor.getCurrentCommand() == null) {
    throw new IncorrectOperationException(
            "Must not change document outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor");
  }
}
 
Example 9
Source File: PomModelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void startTransaction(@Nonnull PomTransaction transaction) {
  final PsiDocumentManagerBase manager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject);
  final PsiToDocumentSynchronizer synchronizer = manager.getSynchronizer();
  final PsiElement changeScope = transaction.getChangeScope();

  final PsiFile containingFileByTree = getContainingFileByTree(changeScope);
  if (containingFileByTree != null && !(containingFileByTree instanceof DummyHolder) && !manager.isCommitInProgress()) {
    PsiUtilCore.ensureValid(containingFileByTree);
  }

  boolean physical = changeScope.isPhysical();
  if (synchronizer.toProcessPsiEvent()) {
    // fail-fast to prevent any psi modifications that would cause psi/document text mismatch
    // PsiToDocumentSynchronizer assertions happen inside event processing and are logged by PsiManagerImpl.fireEvent instead of being rethrown
    // so it's important to throw something outside event processing
    if (isDocumentUncommitted(containingFileByTree)) {
      throw new IllegalStateException("Attempt to modify PSI for non-committed Document!");
    }
    CommandProcessor commandProcessor = CommandProcessor.getInstance();
    if (physical && !commandProcessor.isUndoTransparentActionInProgress() && commandProcessor.getCurrentCommand() == null) {
      throw new IncorrectOperationException(
              "Must not change PSI outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor");
    }
  }

  if (containingFileByTree != null) {
    ((SmartPointerManagerImpl)SmartPointerManager.getInstance(myProject)).fastenBelts(containingFileByTree.getViewProvider().getVirtualFile());
    if (containingFileByTree instanceof PsiFileImpl) {
      ((PsiFileImpl)containingFileByTree).beforeAstChange();
    }
  }

  BlockSupportImpl.sendBeforeChildrenChangeEvent((PsiManagerImpl)PsiManager.getInstance(myProject), changeScope, true);
  Document document = containingFileByTree == null ? null : physical ? manager.getDocument(containingFileByTree) : manager.getCachedDocument(containingFileByTree);
  if (document != null) {
    synchronizer.startTransaction(myProject, document, changeScope);
  }
}
 
Example 10
Source File: PrevSplitAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  final Project project = e.getData(CommonDataKeys.PROJECT);
  final CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(
    project, new Runnable(){
      public void run() {
        final FileEditorManagerEx manager = FileEditorManagerEx.getInstanceEx(project);
        manager.setCurrentWindow(manager.getPrevWindow(manager.getCurrentWindow()));
      }
    }, IdeBundle.message("command.go.to.prev.split"), null
  );
}
 
Example 11
Source File: CloseEditorsActionBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(final AnActionEvent e) {
  final Project project = e.getData(CommonDataKeys.PROJECT);
  final CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.executeCommand(project, () -> {
    List<Pair<EditorComposite, EditorWindow>> filesToClose = getFilesToClose(e);
    for (int i = 0; i != filesToClose.size(); ++i) {
      final Pair<EditorComposite, EditorWindow> we = filesToClose.get(i);
      we.getSecond().closeFile(we.getFirst().getFile());
    }
  }, IdeBundle.message("command.close.all.unmodified.editors"), null);
}
 
Example 12
Source File: DefaultRawTypedHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void beginUndoablePostProcessing() {
  if (myInOuterCommand) {
    return;
  }
  if (myCurrentCommandToken == null) {
    throw new IllegalStateException("Not in a typed action at this time");
  }
  CommandProcessorEx commandProcessorEx = (CommandProcessorEx)CommandProcessor.getInstance();
  Project project = myCurrentCommandToken.getProject();
  commandProcessorEx.finishCommand(myCurrentCommandToken, null);
  myCurrentCommandToken = commandProcessorEx.startCommand(project, "", null, UndoConfirmationPolicy.DEFAULT);
}
 
Example 13
Source File: DefaultRawTypedHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@Nonnull final Editor editor, final char charTyped, @Nonnull final DataContext dataContext) {
  CommandProcessorEx commandProcessorEx = (CommandProcessorEx)CommandProcessor.getInstance();
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (myCurrentCommandToken != null) {
    throw new IllegalStateException("Unexpected reentrancy of DefaultRawTypedHandler");
  }
  myCurrentCommandToken = commandProcessorEx.startCommand(project, "", editor.getDocument(), UndoConfirmationPolicy.DEFAULT);
  myInOuterCommand = myCurrentCommandToken == null;
  try {
    if (!EditorModificationUtil.requestWriting(editor)) {
      return;
    }
    ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(editor.getDocument(), editor.getProject()) {
      @Override
      public void run() {
        Document doc = editor.getDocument();
        doc.startGuardedBlockChecking();
        try {
          myAction.getHandler().execute(editor, charTyped, dataContext);
        }
        catch (ReadOnlyFragmentModificationException e) {
          EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e);
        }
        finally {
          doc.stopGuardedBlockChecking();
        }
      }
    });
  }
  finally {
    if (!myInOuterCommand) {
      commandProcessorEx.finishCommand(myCurrentCommandToken, null);
      myCurrentCommandToken = null;
    }
    myInOuterCommand = false;
  }
}
 
Example 14
Source File: DeleteAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void deleteCharAtCaret(Editor editor) {
  int lineNumber = editor.getCaretModel().getLogicalPosition().line;
  int afterLineEnd = EditorModificationUtil.calcAfterLineEnd(editor);
  Document document = editor.getDocument();
  int offset = editor.getCaretModel().getOffset();
  if (afterLineEnd < 0
      // There is a possible case that caret is located right before the soft wrap position at the last logical line
      // (popular use case with the soft wraps at the commit message dialog).
      || (offset < document.getTextLength() - 1 && editor.getSoftWrapModel().getSoftWrap(offset) != null)) {
    FoldRegion region = editor.getFoldingModel().getCollapsedRegionAtOffset(offset);
    if (region != null && region.shouldNeverExpand()) {
      document.deleteString(region.getStartOffset(), region.getEndOffset());
      editor.getCaretModel().moveToOffset(region.getStartOffset());
    }
    else {
      document.deleteString(offset, DocumentUtil.getNextCodePointOffset(document, offset));
    }
    return;
  }

  if (lineNumber + 1 >= document.getLineCount()) return;

  // Do not group delete newline and other deletions.
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  commandProcessor.setCurrentCommandGroupId(null);

  int nextLineStart = document.getLineStartOffset(lineNumber + 1);
  int nextLineEnd = document.getLineEndOffset(lineNumber + 1);
  if (nextLineEnd - nextLineStart > 0) {
    StringBuilder buf = new StringBuilder();
    StringUtil.repeatSymbol(buf, ' ', afterLineEnd);
    document.insertString(getCaretLineStart(editor) + getCaretLineLength(editor), buf.toString());
    nextLineStart = document.getLineStartOffset(lineNumber + 1);
  }
  int thisLineEnd = document.getLineEndOffset(lineNumber);
  document.deleteString(thisLineEnd, nextLineStart);
}
 
Example 15
Source File: VariableInplaceRenamer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean performRefactoring() {
  boolean bind = false;
  if (myInsertedName != null) {

    final CommandProcessor commandProcessor = CommandProcessor.getInstance();
    if (commandProcessor.getCurrentCommand() != null && getVariable() != null) {
      commandProcessor.setCurrentCommandName(getCommandName());
    }

    bind = true;
    if (!isIdentifier(myInsertedName, myLanguage)) {
      performOnInvalidIdentifier(myInsertedName, myNameSuggestions);
    }
    else {
      if (mySnapshot != null) {
        if (isIdentifier(myInsertedName, myLanguage)) {
          ApplicationManager.getApplication().runWriteAction(new Runnable() {
            @Override
            public void run() {
              mySnapshot.apply(myInsertedName);
            }
          });
        }
      }
    }
    performRefactoringRename(myInsertedName, myMarkAction);
  }
  return bind;
}
 
Example 16
Source File: MacPathChooserDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void choose(@Nullable VirtualFile toSelect, @Nonnull Consumer<List<VirtualFile>> callback) {
  if (toSelect != null && toSelect.getParent() != null) {

    String directoryName;
    String fileName = null;
    if (toSelect.isDirectory()) {
      directoryName = toSelect.getCanonicalPath();
    }
    else {
      directoryName = toSelect.getParent().getCanonicalPath();
      fileName = toSelect.getPath();
    }
    myFileDialog.setDirectory(directoryName);
    myFileDialog.setFile(fileName);
  }


  myFileDialog.setFilenameFilter((dir, name) -> {
    File file = new File(dir, name);
    return myFileChooserDescriptor.isFileSelectable(fileToVirtualFile(file));
  });

  myFileDialog.setMultipleMode(myFileChooserDescriptor.isChooseMultiple());

  final CommandProcessorEx commandProcessor = ApplicationManager.getApplication() != null ? (CommandProcessorEx)CommandProcessor.getInstance() : null;
  final boolean appStarted = commandProcessor != null;


  if (appStarted) {
    commandProcessor.enterModal();
    LaterInvocator.enterModal(myFileDialog);
  }

  Component parent = myParent.get();
  try {
    myFileDialog.setVisible(true);
  }
  finally {
    if (appStarted) {
      commandProcessor.leaveModal();
      LaterInvocator.leaveModal(myFileDialog);
      if (parent != null) {
        IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> {
          IdeFocusManager.getGlobalInstance().requestFocus(parent, true);
        });
      }
    }
  }

  File[] files = myFileDialog.getFiles();
  List<VirtualFile> virtualFileList = getChosenFiles(Stream.of(files));
  virtualFiles = virtualFileList.toArray(VirtualFile.EMPTY_ARRAY);

  if (!virtualFileList.isEmpty()) {
    try {
      if (virtualFileList.size() == 1) {
        myFileChooserDescriptor.isFileSelectable(virtualFileList.get(0));
      }
      myFileChooserDescriptor.validateSelectedFiles(virtualFiles);
    }
    catch (Exception e) {
      if (parent == null) {
        Messages.showErrorDialog(myProject, e.getMessage(), myTitle);
      }
      else {
        Messages.showErrorDialog(parent, e.getMessage(), myTitle);
      }

      return;
    }

    if (!ArrayUtil.isEmpty(files)) {
      callback.consume(virtualFileList);
      return;
    }
  }
  if (callback instanceof FileChooser.FileChooserConsumer) {
    ((FileChooser.FileChooserConsumer)callback).cancelled();
  }
}
 
Example 17
Source File: DialogWrapperPeerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public ActionCallback show() {
  LOG.assertTrue(EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only");

  LOG.assertTrue(EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only");
  final ActionCallback result = new ActionCallback();

  final AnCancelAction anCancelAction = new AnCancelAction();
  final JRootPane rootPane = getRootPane();
  SwingUIDecorator.apply(SwingUIDecorator::decorateWindowTitle, rootPane);
  anCancelAction.registerCustomShortcutSet(CommonShortcuts.ESCAPE, rootPane);
  myDisposeActions.add(() -> anCancelAction.unregisterCustomShortcutSet(rootPane));

  if (!myCanBeParent && myWindowManager != null) {
    myWindowManager.doNotSuggestAsParent(TargetAWT.from(myDialog.getWindow()));
  }

  final CommandProcessorEx commandProcessor = ApplicationManager.getApplication() != null ? (CommandProcessorEx)CommandProcessor.getInstance() : null;
  final boolean appStarted = commandProcessor != null;

  boolean changeModalityState = appStarted && myDialog.isModal() && !isProgressDialog(); // ProgressWindow starts a modality state itself
  Project project = myProject;

  if (changeModalityState) {
    commandProcessor.enterModal();
    if (ModalityPerProjectEAPDescriptor.is()) {
      LaterInvocator.enterModal(project, myDialog.getWindow());
    }
    else {
      LaterInvocator.enterModal(myDialog);
    }
  }

  if (appStarted) {
    hidePopupsIfNeeded();
  }

  try {
    myDialog.show();
  }
  finally {
    if (changeModalityState) {
      commandProcessor.leaveModal();
      if (ModalityPerProjectEAPDescriptor.is()) {
        LaterInvocator.leaveModal(project, myDialog.getWindow());
      }
      else {
        LaterInvocator.leaveModal(myDialog);
      }
    }

    myDialog.getFocusManager().doWhenFocusSettlesDown(result.createSetDoneRunnable());
  }

  return result;
}
 
Example 18
Source File: CodeFormatterFacade.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Emulates pressing {@code Enter} at current caret position.
 *
 * @param editor  target editor
 * @param project target project
 * @param shifts  two-elements array which is expected to be filled with the following info:
 *                1. The first element holds added lines number;
 *                2. The second element holds added symbols number;
 */
private static void emulateEnter(@Nonnull final Editor editor, @Nonnull Project project, int[] shifts) {
  final DataContext dataContext = prepareContext(editor.getComponent(), project);
  int caretOffset = editor.getCaretModel().getOffset();
  Document document = editor.getDocument();
  SelectionModel selectionModel = editor.getSelectionModel();
  int startSelectionOffset = 0;
  int endSelectionOffset = 0;
  boolean restoreSelection = selectionModel.hasSelection();
  if (restoreSelection) {
    startSelectionOffset = selectionModel.getSelectionStart();
    endSelectionOffset = selectionModel.getSelectionEnd();
    selectionModel.removeSelection();
  }
  int textLengthBeforeWrap = document.getTextLength();
  int lineCountBeforeWrap = document.getLineCount();

  DataManager.getInstance().saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, true);
  CommandProcessor commandProcessor = CommandProcessor.getInstance();
  try {
    Runnable command = () -> EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER).execute(editor, dataContext);
    if (commandProcessor.getCurrentCommand() == null) {
      commandProcessor.executeCommand(editor.getProject(), command, WRAP_LINE_COMMAND_NAME, null);
    }
    else {
      command.run();
    }
  }
  finally {
    DataManager.getInstance().saveInDataContext(dataContext, WRAP_LONG_LINE_DURING_FORMATTING_IN_PROGRESS_KEY, null);
  }
  int symbolsDiff = document.getTextLength() - textLengthBeforeWrap;
  if (restoreSelection) {
    int newSelectionStart = startSelectionOffset;
    int newSelectionEnd = endSelectionOffset;
    if (startSelectionOffset >= caretOffset) {
      newSelectionStart += symbolsDiff;
    }
    if (endSelectionOffset >= caretOffset) {
      newSelectionEnd += symbolsDiff;
    }
    selectionModel.setSelection(newSelectionStart, newSelectionEnd);
  }
  shifts[0] = document.getLineCount() - lineCountBeforeWrap;
  shifts[1] = symbolsDiff;
}
 
Example 19
Source File: BackspaceAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void doBackSpaceAtCaret(@Nonnull Editor editor) {
  if(editor.getSelectionModel().hasSelection()) {
    EditorModificationUtil.deleteSelectedText(editor);
    return;
  }

  int lineNumber = editor.getCaretModel().getLogicalPosition().line;
  int colNumber = editor.getCaretModel().getLogicalPosition().column;
  Document document = editor.getDocument();
  int offset = editor.getCaretModel().getOffset();
  if(colNumber > 0) {
    if(EditorModificationUtil.calcAfterLineEnd(editor) > 0) {
      int columnShift = -1;
      editor.getCaretModel().moveCaretRelatively(columnShift, 0, false, false, true);
    }
    else {
      EditorModificationUtil.scrollToCaret(editor);
      editor.getSelectionModel().removeSelection();

      FoldRegion region = editor.getFoldingModel().getCollapsedRegionAtOffset(offset - 1);
      if (region != null && region.shouldNeverExpand()) {
        document.deleteString(region.getStartOffset(), region.getEndOffset());
        editor.getCaretModel().moveToOffset(region.getStartOffset());
      }
      else {
        document.deleteString(offset - 1, offset);
        editor.getCaretModel().moveToOffset(offset - 1, true);
      }
    }
  }
  else if(lineNumber > 0) {
    int separatorLength = document.getLineSeparatorLength(lineNumber - 1);
    int lineEnd = document.getLineEndOffset(lineNumber - 1) + separatorLength;
    document.deleteString(lineEnd - separatorLength, lineEnd);
    editor.getCaretModel().moveToOffset(lineEnd - separatorLength);
    EditorModificationUtil.scrollToCaret(editor);
    editor.getSelectionModel().removeSelection();
    // Do not group delete newline and other deletions.
    CommandProcessor commandProcessor = CommandProcessor.getInstance();
    commandProcessor.setCurrentCommandGroupId(null);
  }
}
 
Example 20
Source File: WinPathChooserDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void choose(@Nullable VirtualFile toSelect, @Nonnull Consumer<List<VirtualFile>> callback) {
  if (toSelect != null && toSelect.getParent() != null) {

    String directoryName;
    String fileName = null;
    if (toSelect.isDirectory()) {
      directoryName = toSelect.getCanonicalPath();
    }
    else {
      directoryName = toSelect.getParent().getCanonicalPath();
      fileName = toSelect.getPath();
    }
    myFileDialog.setDirectory(directoryName);
    myFileDialog.setFile(fileName);
  }


  myFileDialog.setFilenameFilter((dir, name) -> {
    File file = new File(dir, name);
    return myFileChooserDescriptor.isFileSelectable(fileToVirtualFile(file));
  });

  myFileDialog.setMultipleMode(myFileChooserDescriptor.isChooseMultiple());

  final CommandProcessorEx commandProcessor = ApplicationManager.getApplication() != null ? (CommandProcessorEx)CommandProcessor.getInstance() : null;
  final boolean appStarted = commandProcessor != null;


  if (appStarted) {
    commandProcessor.enterModal();
    LaterInvocator.enterModal(myFileDialog);
  }

  Component parent = myParent.get();
  try {
    myFileDialog.setVisible(true);
  }
  finally {
    if (appStarted) {
      commandProcessor.leaveModal();
      LaterInvocator.leaveModal(myFileDialog);
      if (parent != null) parent.requestFocus();
    }
  }

  File[] files = myFileDialog.getFiles();
  List<VirtualFile> virtualFileList = getChosenFiles(Stream.of(files));
  virtualFiles = virtualFileList.toArray(VirtualFile.EMPTY_ARRAY);

  if (!virtualFileList.isEmpty()) {
    try {
      if (virtualFileList.size() == 1) {
        myFileChooserDescriptor.isFileSelectable(virtualFileList.get(0));
      }
      myFileChooserDescriptor.validateSelectedFiles(virtualFiles);
    }
    catch (Exception e) {
      if (parent == null) {
        Messages.showErrorDialog(myProject, e.getMessage(), myTitle);
      }
      else {
        Messages.showErrorDialog(parent, e.getMessage(), myTitle);
      }

      return;
    }

    if (!ArrayUtil.isEmpty(files)) {
      callback.consume(virtualFileList);
    }
    else if (callback instanceof FileChooser.FileChooserConsumer) {
      ((FileChooser.FileChooserConsumer)callback).cancelled();
    }
  }
}