Example #1
0
 protected void assertIntentionApplication(
     final String intentionId, final String source, final String after) {
   final PsiFile file = this.configureByText(source);
   final IntentionAction intention = this.myFixture.findSingleIntention(intentionId);
   CommandProcessor _instance = CommandProcessor.getInstance();
   Project _project = this.getProject();
   final Runnable _function =
       new Runnable() {
         @Override
         public void run() {
           Application _application = ApplicationManager.getApplication();
           final Runnable _function =
               new Runnable() {
                 @Override
                 public void run() {
                   Project _project = file.getProject();
                   Editor _editor = IntentionsTest.this.getEditor();
                   intention.invoke(_project, _editor, file);
                   Project _project_1 = IntentionsTest.this.getProject();
                   PsiDocumentManager _instance = PsiDocumentManager.getInstance(_project_1);
                   _instance.commitAllDocuments();
                 }
               };
           _application.runWriteAction(_function);
         }
       };
   _instance.executeCommand(_project, _function, "", "");
   Editor _editor = this.myFixture.getEditor();
   Document _document = _editor.getDocument();
   String _text = _document.getText();
   TestCase.assertEquals(after, _text);
 }
 public long assertIntentionApplication(final String intentionId, final String source) {
   long _xblockexpression = (long) 0;
   {
     final PsiFile file = this.configureByText(source);
     final IntentionAction intention = this.myFixture.findSingleIntention(intentionId);
     CommandProcessor _instance = CommandProcessor.getInstance();
     Project _project = this.getProject();
     final Runnable _function =
         new Runnable() {
           @Override
           public void run() {
             Application _application = ApplicationManager.getApplication();
             final Runnable _function =
                 new Runnable() {
                   @Override
                   public void run() {
                     Project _project = file.getProject();
                     Editor _editor = XtendLibraryManagerTest.this.getEditor();
                     intention.invoke(_project, _editor, file);
                     Project _project_1 = XtendLibraryManagerTest.this.getProject();
                     PsiDocumentManager _instance = PsiDocumentManager.getInstance(_project_1);
                     _instance.commitAllDocuments();
                   }
                 };
             _application.runWriteAction(_function);
           }
         };
     _instance.executeCommand(_project, _function, "", "");
     _xblockexpression = this.myFixture.checkHighlighting();
   }
   return _xblockexpression;
 }
 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<String, String>();
           predefinedVarValues.put(TemplateImpl.ARG, argument);
         }
         templateState.start(template, processor, predefinedVarValues);
       },
       CodeInsightBundle.message("insert.code.template.command"),
       null);
 }
  private boolean disposeSelf() {
    myDisposeInProgress = true;
    final CommandProcessor commandProcessor = CommandProcessor.getInstance();
    final Ref<Boolean> canClose = new Ref<Boolean>(Boolean.TRUE);
    for (final Project project : ProjectManagerEx.getInstanceEx().getOpenProjects()) {
      try {
        commandProcessor.executeCommand(
            project,
            new Runnable() {
              public void run() {
                canClose.set(ProjectUtil.closeAndDispose(project));
              }
            },
            ApplicationBundle.message("command.exit"),
            null);
      } catch (Throwable e) {
        LOG.error(e);
      }
      if (!canClose.get()) {
        myDisposeInProgress = false;
        return false;
      }
    }
    Disposer.dispose(this);

    Disposer.assertIsEmpty();
    return true;
  }
  public boolean navigateSelectedElement() {
    final Ref<Boolean> succeeded = new Ref<Boolean>();
    final CommandProcessor commandProcessor = CommandProcessor.getInstance();
    commandProcessor.executeCommand(
        myProject,
        new Runnable() {
          public void run() {
            final AbstractTreeNode selectedNode = getSelectedNode();
            if (selectedNode != null) {
              if (selectedNode.canNavigateToSource()) {
                myPopup.cancel();
                selectedNode.navigate(true);
                succeeded.set(true);
              } else {
                succeeded.set(false);
              }
            } else {
              succeeded.set(false);
            }

            IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation();
          }
        },
        "Navigate",
        null);
    return succeeded.get();
  }
Example #6
0
  private static void copyClassesImpl(
      final String copyClassName,
      final Project project,
      final Map<PsiFile, PsiClass[]> classes,
      final HashMap<PsiFile, String> map,
      final Object targetDirectory,
      final PsiDirectory defaultTargetDirectory,
      final String commandName,
      final boolean selectInActivePanel,
      final boolean openInEditor) {
    final boolean[] result = new boolean[] {false};
    Runnable command =
        () -> {
          final Runnable action =
              () -> {
                try {
                  PsiDirectory target;
                  if (targetDirectory instanceof PsiDirectory) {
                    target = (PsiDirectory) targetDirectory;
                  } else {
                    target =
                        ((MoveDestination) targetDirectory)
                            .getTargetDirectory(defaultTargetDirectory);
                  }
                  Collection<PsiFile> files =
                      doCopyClasses(classes, map, copyClassName, target, project);
                  if (files != null) {
                    if (openInEditor) {
                      for (PsiFile file : files) {
                        CopyHandler.updateSelectionInActiveProjectView(
                            file, project, selectInActivePanel);
                      }
                      EditorHelper.openFilesInEditor(files.toArray(new PsiFile[files.size()]));
                    }

                    result[0] = true;
                  }
                } catch (final IncorrectOperationException ex) {
                  ApplicationManager.getApplication()
                      .invokeLater(
                          () ->
                              Messages.showMessageDialog(
                                  project,
                                  ex.getMessage(),
                                  RefactoringBundle.message("error.title"),
                                  Messages.getErrorIcon()));
                }
              };
          ApplicationManager.getApplication().runWriteAction(action);
        };
    CommandProcessor processor = CommandProcessor.getInstance();
    processor.executeCommand(project, command, commandName, null);

    if (result[0]) {
      ToolWindowManager.getInstance(project)
          .invokeLater(() -> ToolWindowManager.getInstance(project).activateEditorComponent());
    }
  }
  /**
   * Emulates pressing <code>Enter</code> 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(
      @NotNull final Editor editor, @NotNull 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 =
          new Runnable() {
            @Override
            public void run() {
              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;
  }
 public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
   if (editor == null) return;
   // final PsiFile psiFile =
   // PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
   final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
   if (psiFile == null) return;
   CommandProcessor.getInstance()
       .executeCommand(
           project,
           () -> {
             final CodeInsightActionHandler handler = getHandler();
             final Runnable action =
                 () -> {
                   if (!ApplicationManager.getApplication().isUnitTestMode()
                       && !editor.getContentComponent().isShowing()) return;
                   handler.invoke(project, editor, psiFile);
                 };
             if (handler.startInWriteAction()) {
               ApplicationManager.getApplication().runWriteAction(action);
             } else {
               action.run();
             }
           },
           getCommandName(),
           DocCommandGroupId.noneGroupId(editor.getDocument()));
 }
 protected void doOKAction() {
   CommandProcessor.getInstance()
       .executeCommand(
           myProject,
           new Runnable() {
             public void run() {
               final Runnable action =
                   new Runnable() {
                     public void run() {
                       String directoryName =
                           myTargetDirectoryField.getText().replace(File.separatorChar, '/');
                       try {
                         myTargetDirectory =
                             DirectoryUtil.mkdirs(
                                 PsiManager.getInstance(myProject), directoryName);
                       } catch (IncorrectOperationException e) {
                       }
                     }
                   };
               ApplicationManager.getApplication().runWriteAction(action);
             }
           },
           RefactoringBundle.message("create.directory"),
           null);
   if (myTargetDirectory == null) {
     CommonRefactoringUtil.showErrorMessage(
         getTitle(), RefactoringBundle.message("cannot.create.directory"), myHelpID, myProject);
     return;
   }
   myCallback.run(this);
 }
  private static PsiDirectory createSubdirectory(
      final PsiDirectory oldDirectory, final String name, Project project)
      throws IncorrectOperationException {
    final PsiDirectory[] psiDirectory = new PsiDirectory[1];
    final IncorrectOperationException[] exception = new IncorrectOperationException[1];

    CommandProcessor.getInstance()
        .executeCommand(
            project,
            new Runnable() {
              public void run() {
                psiDirectory[0] =
                    ApplicationManager.getApplication()
                        .runWriteAction(
                            new Computable<PsiDirectory>() {
                              public PsiDirectory compute() {
                                try {
                                  return oldDirectory.createSubdirectory(name);
                                } catch (IncorrectOperationException e) {
                                  exception[0] = e;
                                  return null;
                                }
                              }
                            });
              }
            },
            IdeBundle.message("command.create.new.subdirectory"),
            null);

    if (exception[0] != null) throw exception[0];

    return psiDirectory[0];
  }
  protected void doTest(final String extension) throws Exception {
    CommandProcessor.getInstance()
        .executeCommand(
            getProject(),
            () ->
                WriteCommandAction.runWriteCommandAction(
                    null,
                    () -> {
                      String fileName = getTestName(false) + extension;
                      try {
                        String text = loadFile(fileName);
                        PsiFile file = createFile(fileName, text);

                        JavaCodeStyleManager.getInstance(myProject).optimizeImports(file);
                        PostprocessReformattingAspect.getInstance(getProject())
                            .doPostponedFormatting();
                        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
                        String textAfter = loadFile(getTestName(false) + "_after" + extension);
                        String fileText = file.getText();
                        assertEquals(textAfter, fileText);
                      } catch (Exception e) {
                        LOG.error(e);
                      }
                    }),
            "",
            "");
  }
  private boolean convertLocalToField(
      PsiLocalVariable local, PsiClass aClass, Editor editor, boolean isStatic) {
    final PsiExpression[] occurences =
        CodeInsightUtil.findReferenceExpressions(RefactoringUtil.getVariableScope(local), local);
    if (editor != null) {
      RefactoringUtil.highlightAllOccurrences(myProject, occurences, editor);
    }

    final BaseExpressionToFieldHandler.Settings settings =
        showRefactoringDialog(aClass, local, occurences, isStatic);
    if (settings == null) return true;
    // LocalToFieldDialog dialog = new LocalToFieldDialog(project, aClass, local, isStatic);
    final PsiClass destinationClass = settings.getDestinationClass();
    boolean rebindNeeded = false;
    if (destinationClass != null) {
      aClass = destinationClass;
      rebindNeeded = true;
    }

    final PsiClass aaClass = aClass;
    final boolean rebindNeeded1 = rebindNeeded;
    final Runnable runnable =
        new IntroduceFieldRunnable(rebindNeeded1, local, aaClass, settings, isStatic, occurences);
    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            new Runnable() {
              public void run() {
                ApplicationManager.getApplication().runWriteAction(runnable);
              }
            },
            REFACTORING_NAME,
            null);
    return false;
  }
  /**
   * <strong>This is very important test.</strong> Almost all actions are performed inside
   * surrounding command. Therefore we have to correctly handle such situations.
   */
  public void testActionInsideCommand() throws Exception {
    final VirtualFile f = createFile("f.txt");
    setContent(f, "file");
    setDocumentTextFor(f, "doc1");

    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            new Runnable() {
              @Override
              public void run() {
                LocalHistoryAction a = LocalHistory.getInstance().startAction("action");
                setDocumentTextFor(f, "doc2");
                a.finish();
              }
            },
            "command",
            null);

    List<Revision> rr = getRevisionsFor(f);
    assertEquals(5, rr.size());
    assertContent("doc2", rr.get(0).findEntry());
    assertEquals("command", rr.get(1).getChangeSetName());
    assertContent("doc1", rr.get(1).findEntry());
    assertContent("file", rr.get(2).findEntry());
    assertContent("", rr.get(3).findEntry());
  }
 @CalledInAwt
 @NotNull
 private ApplyPatchStatus getApplyPatchStatus(@NotNull final TriggerAdditionOrDeletion trigger) {
   final Ref<ApplyPatchStatus> refStatus = Ref.create(null);
   try {
     setConfirmationToDefault();
     CommandProcessor.getInstance()
         .executeCommand(
             myProject,
             new Runnable() {
               @Override
               public void run() {
                 // consider pre-check status only if not successful, otherwise we could not
                 // detect already applied status
                 if (createFiles() != ApplyPatchStatus.SUCCESS) {
                   refStatus.set(createFiles());
                 }
                 addSkippedItems(trigger);
                 trigger.prepare();
                 refStatus.set(ApplyPatchStatus.and(refStatus.get(), executeWritable()));
               }
             },
             VcsBundle.message("patch.apply.command"),
             null);
   } finally {
     returnConfirmationBack();
     VcsFileListenerContextHelper.getInstance(myProject).clearContext();
   }
   final ApplyPatchStatus status = refStatus.get();
   return status == null ? ApplyPatchStatus.ALREADY_APPLIED : status;
 }
  public void testActionInsideCommandSurroundedWithSomeChanges() throws Exception {
    // see testActionInsideCommand comment
    final VirtualFile f = createFile("f.txt");

    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            new RunnableAdapter() {
              @Override
              public void doRun() throws IOException {
                setContent(f, "file");
                setDocumentTextFor(f, "doc1");

                LocalHistoryAction a = LocalHistory.getInstance().startAction("action");
                setDocumentTextFor(f, "doc2");
                a.finish();

                saveDocument(f);
                setContent(f, "doc3");
              }
            },
            "command",
            null);

    List<Revision> rr = getRevisionsFor(f);
    assertEquals(4, rr.size());

    assertContent("doc3", rr.get(0).findEntry());
    assertContent("doc1", rr.get(1).findEntry());
    assertContent("", rr.get(2).findEntry());

    assertEquals("command", rr.get(1).getChangeSetName());
    assertNull(rr.get(2).getChangeSetName());
  }
 private static boolean navigateInCurrentEditor(
     @NotNull PsiElement element, @NotNull PsiFile currentFile, @NotNull Editor currentEditor) {
   if (element.getContainingFile() == currentFile) {
     int offset = element.getTextOffset();
     PsiElement leaf = currentFile.findElementAt(offset);
     // check that element is really physically inside the file
     // there are fake elements with custom navigation (e.g. opening URL in browser) that override
     // getContainingFile for various reasons
     if (leaf != null && PsiTreeUtil.isAncestor(element, leaf, false)) {
       Project project = element.getProject();
       CommandProcessor.getInstance()
           .executeCommand(
               project,
               () -> {
                 IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation();
                 new OpenFileDescriptor(
                         project, currentFile.getViewProvider().getVirtualFile(), offset)
                     .navigateIn(currentEditor);
               },
               "",
               null);
       return true;
     }
   }
   return false;
 }
  private void replaceUsagesUnderCommand(
      @NotNull final ReplaceContext replaceContext, @Nullable final Set<Usage> usagesSet) {
    if (usagesSet == null) {
      return;
    }

    final List<Usage> usages = new ArrayList<Usage>(usagesSet);
    Collections.sort(usages, UsageViewImpl.USAGE_COMPARATOR);

    if (!ensureUsagesWritable(replaceContext, usages)) return;

    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            new Runnable() {
              @Override
              public void run() {
                final boolean success = replaceUsages(replaceContext, usages);
                final UsageView usageView = replaceContext.getUsageView();

                if (closeUsageViewIfEmpty(usageView, success)) return;
                usageView.getComponent().requestFocus();
              }
            },
            FindBundle.message("find.replace.command"),
            null);

    replaceContext.invalidateExcludedSetCache();
  }
  @Override
  protected boolean performRefactoring() {
    if (!ensureValid()) return false;
    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            () -> {
              final String refactoringId = getRefactoringId();
              if (refactoringId != null) {
                final RefactoringEventData beforeData = new RefactoringEventData();
                final V localVariable = getLocalVariable();
                if (localVariable != null) {
                  beforeData.addElement(localVariable);
                } else {
                  final E beforeExpr = getBeforeExpr();
                  if (beforeExpr != null) {
                    beforeData.addElement(beforeExpr);
                  }
                }
                myProject
                    .getMessageBus()
                    .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC)
                    .refactoringStarted(refactoringId, beforeData);
              }
              performIntroduce();
            },
            getCommandName(),
            getCommandName());

    V variable = getVariable();
    if (variable != null) {
      saveSettings(variable);
    }
    return false;
  }
  private void updateTextElement(final PsiElement elt) {
    final String newText = getNewText(elt);
    if (newText == null || Comparing.strEqual(newText, myEditor.getDocument().getText())) return;
    CommandProcessor.getInstance()
        .runUndoTransparentAction(
            new Runnable() {
              @Override
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            Document fragmentDoc = myEditor.getDocument();
                            fragmentDoc.setReadOnly(false);

                            fragmentDoc.replaceString(0, fragmentDoc.getTextLength(), newText);
                            fragmentDoc.setReadOnly(true);
                            myEditor.getCaretModel().moveToOffset(0);
                            myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                          }
                        });
              }
            });
  }
 @Override
 public void invoke(
     final @NotNull Project project, Editor editor, final PsiFile file, DataContext dataContext) {
   final ResourceBundleEditor resourceBundleEditor =
       (ResourceBundleEditor) PlatformDataKeys.FILE_EDITOR.getData(dataContext);
   assert resourceBundleEditor != null;
   final ResourceBundleEditorViewElement selectedElement =
       resourceBundleEditor.getSelectedElementIfOnlyOne();
   if (selectedElement != null) {
     CommandProcessor.getInstance()
         .runUndoTransparentAction(
             () -> {
               if (selectedElement instanceof PropertiesPrefixGroup) {
                 final PropertiesPrefixGroup group = (PropertiesPrefixGroup) selectedElement;
                 ResourceBundleRenameUtil.renameResourceBundleKeySection(
                     getPsiElementsFromGroup(group),
                     group.getPresentableName(),
                     group.getPrefix().length() - group.getPresentableName().length());
               } else if (selectedElement instanceof ResourceBundlePropertyStructureViewElement) {
                 final PsiElement psiElement =
                     ((ResourceBundlePropertyStructureViewElement) selectedElement)
                         .getProperty()
                         .getPsiElement();
                 ResourceBundleRenameUtil.renameResourceBundleKey(psiElement, project);
               } else if (selectedElement instanceof ResourceBundleFileStructureViewElement) {
                 ResourceBundleRenameUtil.renameResourceBundleBaseName(
                     ((ResourceBundleFileStructureViewElement) selectedElement).getValue(),
                     project);
               } else {
                 throw new IllegalStateException(
                     "unsupported type: " + selectedElement.getClass());
               }
             });
   }
 }
  @Override
  protected void invokeTestRunnable(@NotNull final Runnable runnable) throws Exception {
    final Exception[] e = new Exception[1];
    Runnable runnable1 =
        new Runnable() {
          @Override
          public void run() {
            try {
              if (ApplicationManager.getApplication().isDispatchThread() && isRunInWriteAction()) {
                ApplicationManager.getApplication().runWriteAction(runnable);
              } else {
                runnable.run();
              }
            } catch (Exception e1) {
              e[0] = e1;
            }
          }
        };

    if (annotatedWith(WrapInCommand.class)) {
      CommandProcessor.getInstance().executeCommand(myProject, runnable1, "", null);
    } else {
      runnable1.run();
    }

    if (e[0] != null) {
      throw e[0];
    }
  }
 private void doImport(final PsiMethod toImport) {
   CommandProcessor.getInstance()
       .executeCommand(
           toImport.getProject(),
           new Runnable() {
             @Override
             public void run() {
               ApplicationManager.getApplication()
                   .runWriteAction(
                       new Runnable() {
                         @Override
                         public void run() {
                           try {
                             PsiMethodCallExpression element = myMethodCall.getElement();
                             if (element != null) {
                               element
                                   .getMethodExpression()
                                   .bindToElementViaStaticImport(toImport.getContainingClass());
                             }
                           } catch (IncorrectOperationException e) {
                             LOG.error(e);
                           }
                         }
                       });
             }
           },
           getText(),
           this);
 }
 private static boolean clearReadOnlyFlag(final VirtualFile virtualFile, final Project project) {
   final boolean[] success = new boolean[1];
   CommandProcessor.getInstance()
       .executeCommand(
           project,
           new Runnable() {
             public void run() {
               Runnable action =
                   new Runnable() {
                     public void run() {
                       try {
                         ReadOnlyAttributeUtil.setReadOnlyAttribute(virtualFile, false);
                         success[0] = true;
                       } catch (IOException e1) {
                         Messages.showMessageDialog(
                             project,
                             e1.getMessage(),
                             CommonBundle.getErrorTitle(),
                             Messages.getErrorIcon());
                       }
                     }
                   };
               ApplicationManager.getApplication().runWriteAction(action);
             }
           },
           "",
           null);
   return success[0];
 }
 private static LinkedList<EditorChangeAction> justTypeChar(
     final char charTyped, final LookupImpl lookup, final Editor editor) {
   final LinkedList<EditorChangeAction> events = new LinkedList<EditorChangeAction>();
   final DocumentAdapter listener =
       new DocumentAdapter() {
         @Override
         public void documentChanged(DocumentEvent e) {
           events.addFirst(new EditorChangeAction(e));
         }
       };
   editor.getDocument().addDocumentListener(listener);
   CommandProcessor.getInstance()
       .executeCommand(
           editor.getProject(),
           new Runnable() {
             @Override
             public void run() {
               lookup.performGuardedChange(
                   new Runnable() {
                     @Override
                     public void run() {
                       EditorModificationUtil.typeInStringAtCaretHonorBlockSelection(
                           editor, String.valueOf(charTyped), true);
                     }
                   });
             }
           },
           null,
           "Just insert the completion char");
   editor.getDocument().removeDocumentListener(listener);
   return events;
 }
Example #25
0
  @Override
  public ActionCallback show() {
    LOG.assertTrue(
        EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only");
    if (myTypeAheadCallback != null) {
      IdeFocusManager.getInstance(myProject).typeAheadUntil(myTypeAheadCallback);
    }
    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();
    anCancelAction.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)), rootPane);
    myDisposeActions.add(
        new Runnable() {
          @Override
          public void run() {
            anCancelAction.unregisterCustomShortcutSet(rootPane);
          }
        });

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

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

    if (myDialog.isModal() && !isProgressDialog()) {
      if (appStarted) {
        commandProcessor.enterModal();
        LaterInvocator.enterModal(myDialog);
      }
    }

    if (appStarted) {
      hidePopupsIfNeeded();
    }

    try {
      myDialog.show();
    } finally {
      if (myDialog.isModal() && !isProgressDialog()) {
        if (appStarted) {
          commandProcessor.leaveModal();
          LaterInvocator.leaveModal(myDialog);
        }
      }

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

    return result;
  }
 public void stopIntroduce(Editor editor) {
   final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
   if (templateState != null) {
     final Runnable runnable = () -> templateState.gotoEnd(true);
     CommandProcessor.getInstance()
         .executeCommand(myProject, runnable, getCommandName(), getCommandName());
   }
 }
  protected void performIntroduce() {
    boolean isDeleteLocalVariable = false;

    PsiExpression parameterInitializer = myExpr;
    if (getLocalVariable() != null) {
      if (myPanel.isUseInitializer()) {
        parameterInitializer = getLocalVariable().getInitializer();
      }
      isDeleteLocalVariable = myPanel.isDeleteLocalVariable();
    }

    final TIntArrayList parametersToRemove = myPanel.getParametersToRemove();

    final IntroduceParameterProcessor processor =
        new IntroduceParameterProcessor(
            myProject,
            myMethod,
            myMethodToSearchFor,
            parameterInitializer,
            myExpr,
            (PsiLocalVariable) getLocalVariable(),
            isDeleteLocalVariable,
            getInputName(),
            myPanel.isReplaceAllOccurences(),
            myPanel.getReplaceFieldsWithGetters(),
            myMustBeFinal || myPanel.isGenerateFinal(),
            isGenerateDelegate(),
            getType(),
            parametersToRemove);
    final Runnable runnable =
        new Runnable() {
          public void run() {
            final Runnable performRefactoring =
                new Runnable() {
                  public void run() {
                    processor.setPrepareSuccessfulSwingThreadCallback(
                        new Runnable() {
                          @Override
                          public void run() {}
                        });
                    processor.run();
                    normalizeParameterIdxAccordingToRemovedParams(parametersToRemove);
                    final PsiParameter parameter = getParameter();
                    if (parameter != null) {
                      InplaceIntroduceParameterPopup.super.saveSettings(parameter);
                    }
                  }
                };
            if (ApplicationManager.getApplication().isUnitTestMode()) {
              performRefactoring.run();
            } else {
              ApplicationManager.getApplication().invokeLater(performRefactoring);
            }
          }
        };
    CommandProcessor.getInstance().executeCommand(myProject, runnable, getCommandName(), null);
  }
  /**
   * Begins the in-place refactoring operation.
   *
   * @return true if the in-place refactoring was successfully started, false if it failed to start
   *     and a dialog should be shown instead.
   */
  public boolean startInplaceIntroduceTemplate() {
    final boolean replaceAllOccurrences = isReplaceAllOccurrences();
    final Ref<Boolean> result = new Ref<>();
    CommandProcessor.getInstance()
        .executeCommand(
            myProject,
            () -> {
              final String[] names = suggestNames(replaceAllOccurrences, getLocalVariable());
              final V variable = createFieldToStartTemplateOn(replaceAllOccurrences, names);
              boolean started = false;
              if (variable != null) {
                int caretOffset = getCaretOffset();
                myEditor.getCaretModel().moveToOffset(caretOffset);
                myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);

                final LinkedHashSet<String> nameSuggestions = new LinkedHashSet<>();
                nameSuggestions.add(variable.getName());
                nameSuggestions.addAll(Arrays.asList(names));
                initOccurrencesMarkers();
                setElementToRename(variable);
                updateTitle(getVariable());
                started = super.performInplaceRefactoring(nameSuggestions);
                if (started) {
                  onRenameTemplateStarted();
                  myDocumentAdapter =
                      new DocumentAdapter() {
                        @Override
                        public void documentChanged(DocumentEvent e) {
                          if (myPreview == null) return;
                          final TemplateState templateState =
                              TemplateManagerImpl.getTemplateState(myEditor);
                          if (templateState != null) {
                            final TextResult value =
                                templateState.getVariableValue(
                                    InplaceRefactoring.PRIMARY_VARIABLE_NAME);
                            if (value != null) {
                              updateTitle(getVariable(), value.getText());
                            }
                          }
                        }
                      };
                  myEditor.getDocument().addDocumentListener(myDocumentAdapter);
                  updateTitle(getVariable());
                  if (TemplateManagerImpl.getTemplateState(myEditor) != null) {
                    myEditor.putUserData(ACTIVE_INTRODUCE, this);
                  }
                }
              }
              result.set(started);
              if (!started) {
                finish(true);
              }
            },
            getCommandName(),
            getCommandName());
    return result.get();
  }
 @Override
 protected void invoke(@NotNull final Project project, final Editor editor, final JetFile file) {
   CommandProcessor.getInstance()
       .runUndoTransparentAction(
           new Runnable() {
             @Override
             public void run() {
               createAction(project, editor, file).execute();
             }
           });
 }
  @NotNull
  private String replaceAndProcessDocument(
      @NotNull final Action action,
      @NotNull final String text,
      @NotNull final PsiFile file,
      @Nullable final Document document)
      throws IncorrectOperationException {
    if (document == null) {
      fail("Don't expect the document to be null");
      return null;
    }
    if (myLineRange != null) {
      final DocumentImpl doc = new DocumentImpl(text);
      myTextRange =
          new TextRange(
              doc.getLineStartOffset(myLineRange.getStartOffset()),
              doc.getLineEndOffset(myLineRange.getEndOffset()));
    }
    final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
    CommandProcessor.getInstance()
        .executeCommand(
            getProject(),
            new Runnable() {
              @Override
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            document.replaceString(0, document.getTextLength(), text);
                            manager.commitDocument(document);
                            try {
                              TextRange rangeToUse = myTextRange;
                              if (rangeToUse == null) {
                                rangeToUse = file.getTextRange();
                              }
                              ACTIONS
                                  .get(action)
                                  .run(
                                      file, rangeToUse.getStartOffset(), rangeToUse.getEndOffset());
                            } catch (IncorrectOperationException e) {
                              assertTrue(e.getLocalizedMessage(), false);
                            }
                          }
                        });
              }
            },
            action == Action.REFORMAT ? ReformatCodeProcessor.COMMAND_NAME : "",
            "");

    return document.getText();
  }