com.intellij.openapi.command.CommandProcessor Java Examples

The following examples show how to use com.intellij.openapi.command.CommandProcessor. 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: DeleteToWordEndAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, Caret caret, DataContext dataContext) {
  CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
  CopyPasteManager.getInstance().stopKillRings();

  int lineNumber = editor.getCaretModel().getLogicalPosition().line;
  if (editor.isColumnMode() && editor.getCaretModel().supportsMultipleCarets()
      && editor.getCaretModel().getOffset() == editor.getDocument().getLineEndOffset(lineNumber)) {
    return;
  }

  boolean camelMode = editor.getSettings().isCamelWords();
  if (myNegateCamelMode) {
    camelMode = !camelMode;
  }
  deleteToWordEnd(editor, camelMode);
}
 
Example #2
Source File: RenameRefactoringListener.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Override
public void elementRenamed(@NotNull final PsiElement psiElement)
{
    final String moduleName = originalFile.substring(0, originalFile.indexOf('.'));

    CommandProcessor.getInstance().executeCommand(psiElement.getProject(), new Runnable() {
        @Override
        public void run() {
            new ModuleImporter(possibleFiles,
                    moduleName,
                    (PsiFile) psiElement,
                    new SourcesLocator().getSourceLibraries(psiElement.getProject()).toArray(new SourceLibrary[0]),
                    ServiceManager.getService(psiElement.getProject(),
                            DojoSettings.class).getNamingExceptionList())
                    .findFilesThatReferenceModule(SourcesLocator.getProjectSourceDirectories(psiElement.getProject(), true), true);
        }
    },
    "Rename Dojo Module",
    "Rename Dojo Module");
}
 
Example #3
Source File: LocalHistoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void initHistory() {
  ChangeListStorage storage;
  try {
    storage = new ChangeListStorageImpl(getStorageDir());
  }
  catch (Throwable e) {
    LocalHistoryLog.LOG.warn("cannot create storage, in-memory  implementation will be used", e);
    storage = new InMemoryChangeListStorage();
  }
  myChangeList = new ChangeList(storage);
  myVcs = new LocalHistoryFacade(myChangeList);

  myGateway = new IdeaGateway();

  myEventDispatcher = new LocalHistoryEventDispatcher(myVcs, myGateway);

  CommandProcessor.getInstance().addCommandListener(myEventDispatcher, this);

  myConnection = myBus.connect();
  myConnection.subscribe(VirtualFileManager.VFS_CHANGES, myEventDispatcher);

  VirtualFileManager fm = VirtualFileManager.getInstance();
  fm.addVirtualFileManagerListener(myEventDispatcher, this);
}
 
Example #4
Source File: EditVariableDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateTemplateTextByVarNameChange(final Variable oldVar, final Variable newVar) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      CommandProcessor.getInstance().executeCommand(null, new Runnable() {
        @Override
        public void run() {
          Document document = myEditor.getDocument();
          String templateText = document.getText();
          templateText = templateText.replaceAll("\\$" + oldVar.getName() + "\\$", "\\$" + newVar.getName() + "\\$");
          document.replaceString(0, document.getTextLength(), templateText);
        }
      }, null, null);
    }
  });
}
 
Example #5
Source File: Log4J2Logger.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void logErrorHeader() {
  final String info = ourApplicationInfoProvider.get();

  if (info != null) {
    myLogger.error(info);
  }

  myLogger.error("JDK: " + System.getProperties().getProperty("java.version", "unknown"));
  myLogger.error("VM: " + System.getProperties().getProperty("java.vm.name", "unknown"));
  myLogger.error("Vendor: " + System.getProperties().getProperty("java.vendor", "unknown"));
  myLogger.error("OS: " + System.getProperties().getProperty("os.name", "unknown"));

  ApplicationEx2 application = (ApplicationEx2)ApplicationManager.getApplication();
  if (application != null && application.isComponentsCreated()) {
    final String lastPreformedActionId = LastActionTracker.ourLastActionId;
    if (lastPreformedActionId != null) {
      myLogger.error("Last Action: " + lastPreformedActionId);
    }

    CommandProcessor commandProcessor = CommandProcessor.getInstance();
    final String currentCommandName = commandProcessor.getCurrentCommandName();
    if (currentCommandName != null) {
      myLogger.error("Current Command: " + currentCommandName);
    }
  }
}
 
Example #6
Source File: GotoCustomRegionAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull final AnActionEvent e) {
  final Project project = e.getProject();
  final Editor editor = e.getData(CommonDataKeys.EDITOR);
  if (Boolean.TRUE.equals(e.getData(PlatformDataKeys.IS_MODAL_CONTEXT))) {
    return;
  }
  if (project != null && editor != null) {
    if (DumbService.getInstance(project).isDumb()) {
      DumbService.getInstance(project).showDumbModeNotification(IdeBundle.message("goto.custom.region.message.dumb.mode"));
      return;
    }
    CommandProcessor processor = CommandProcessor.getInstance();
    processor.executeCommand(project, () -> {
      Collection<FoldingDescriptor> foldingDescriptors = getCustomFoldingDescriptors(editor, project);
      if (foldingDescriptors.size() > 0) {
        CustomFoldingRegionsPopup regionsPopup = new CustomFoldingRegionsPopup(foldingDescriptors, editor, project);
        regionsPopup.show();
      }
      else {
        notifyCustomRegionsUnavailable(editor, project);
      }
    }, IdeBundle.message("goto.custom.region.command"), null);
  }
}
 
Example #7
Source File: ClassToUtilConverter.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Object[] result)
{
    DeclareResolver util = new DeclareResolver();

    final DeclareStatementItems utilItem = util.getDeclareStatementFromParsedStatement(result);
    if(utilItem == null)
    {
        Notifications.Bus.notify(new Notification("needsmoredojo", "Convert class module to util module", "Valid declare block was not found", NotificationType.WARNING));
        return;
    }

    CommandProcessor.getInstance().executeCommand(utilItem.getDeclareContainingStatement().getProject(), new Runnable() {
        @Override
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    doRefactor(utilItem.getClassName(), utilItem.getDeclareContainingStatement(), utilItem.getExpressionsToMixin(), utilItem.getMethodsToConvert());
                }
            });
        }
    },
    "Convert class module to util module",
    "Convert class module to util module");
}
 
Example #8
Source File: PasteReferenceProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void insert(final String fqn, final PsiElement element, final Editor editor, final QualifiedNameProvider provider) {
  final Project project = editor.getProject();
  if (project == null) return;

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitDocument(editor.getDocument());

  final PsiFile file = documentManager.getPsiFile(editor.getDocument());
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    Document document = editor.getDocument();
    documentManager.doPostponedOperationsAndUnblockDocument(document);
    documentManager.commitDocument(document);
    EditorModificationUtil.deleteSelectedText(editor);
    provider.insertQualifiedName(fqn, element, editor, project);
  }), IdeBundle.message("command.pasting.reference"), null);
}
 
Example #9
Source File: ProjectViewImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void detachLibrary(@Nonnull final LibraryOrderEntry orderEntry, @Nonnull Project project) {
  final Module module = orderEntry.getOwnerModule();
  String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName());
  String title = IdeBundle.message("detach.library");
  int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon());
  if (ret != Messages.OK) return;
  CommandProcessor.getInstance().executeCommand(module.getProject(), () -> {
    final Runnable action = () -> {
      ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
      OrderEntry[] orderEntries = rootManager.getOrderEntries();
      ModifiableRootModel model = rootManager.getModifiableModel();
      OrderEntry[] modifiableEntries = model.getOrderEntries();
      for (int i = 0; i < orderEntries.length; i++) {
        OrderEntry entry = orderEntries[i];
        if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) {
          model.removeOrderEntry(modifiableEntries[i]);
        }
      }
      model.commit();
    };
    ApplicationManager.getApplication().runWriteAction(action);
  }, title, null);
}
 
Example #10
Source File: SearchStringsAction.java    From android-strings-search-plugin with Apache License 2.0 6 votes vote down vote up
private void insertToEditor(final Project project, final StringElement stringElement) {
    CommandProcessor.getInstance().executeCommand(project, new Runnable() {
        @Override
        public void run() {
            getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
                    if (editor != null) {
                        int offset = editor.getCaretModel().getOffset();
                        Document document = editor.getDocument();
                        String key = stringElement.getName();
                        if (key != null) {
                            document.insertString(offset, key);
                            editor.getCaretModel().moveToOffset(offset + key.length());
                        }
                    }
                }
            });
        }
    }, "WriteStringKeyCommand", "", UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
}
 
Example #11
Source File: UndoManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void undoOrRedo(final FileEditor editor, final boolean isUndo) {
  myCurrentOperationState = isUndo ? OperationState.UNDO : OperationState.REDO;

  final RuntimeException[] exception = new RuntimeException[1];
  Runnable executeUndoOrRedoAction = () -> {
    try {
      if (myProject != null) {
        PsiDocumentManager.getInstance(myProject).commitAllDocuments();
      }
      CopyPasteManager.getInstance().stopKillRings();
      myMerger.undoOrRedo(editor, isUndo);
    }
    catch (RuntimeException ex) {
      exception[0] = ex;
    }
    finally {
      myCurrentOperationState = OperationState.NONE;
    }
  };

  String name = getUndoOrRedoActionNameAndDescription(editor, isUndoInProgress()).second;
  CommandProcessor.getInstance()
          .executeCommand(myProject, executeUndoOrRedoAction, name, null, myMerger.getUndoConfirmationPolicy());
  if (exception[0] != null) throw exception[0];
}
 
Example #12
Source File: WebProjectViewImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void detachLibrary(@Nonnull final LibraryOrderEntry orderEntry, @Nonnull Project project) {
  final Module module = orderEntry.getOwnerModule();
  String message = IdeBundle.message("detach.library.from.module", orderEntry.getPresentableName(), module.getName());
  String title = IdeBundle.message("detach.library");
  int ret = Messages.showOkCancelDialog(project, message, title, Messages.getQuestionIcon());
  if (ret != Messages.OK) return;
  CommandProcessor.getInstance().executeCommand(module.getProject(), () -> {
    final Runnable action = () -> {
      ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
      OrderEntry[] orderEntries = rootManager.getOrderEntries();
      ModifiableRootModel model = rootManager.getModifiableModel();
      OrderEntry[] modifiableEntries = model.getOrderEntries();
      for (int i = 0; i < orderEntries.length; i++) {
        OrderEntry entry = orderEntries[i];
        if (entry instanceof LibraryOrderEntry && ((LibraryOrderEntry)entry).getLibrary() == orderEntry.getLibrary()) {
          model.removeOrderEntry(modifiableEntries[i]);
        }
      }
      model.commit();
    };
    ApplicationManager.getApplication().runWriteAction(action);
  }, title, null);
}
 
Example #13
Source File: CleanupInspectionIntention.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static AbstractPerformFixesTask applyFixesNoSort(@Nonnull Project project,
                                                        @Nonnull String presentationText,
                                                        @Nonnull List<ProblemDescriptor> descriptions,
                                                        @Nullable Class quickfixClass) {
  final SequentialModalProgressTask progressTask =
          new SequentialModalProgressTask(project, presentationText, true);
  final boolean isBatch = quickfixClass != null && BatchQuickFix.class.isAssignableFrom(quickfixClass);
  final AbstractPerformFixesTask fixesTask = isBatch ?
                                             new PerformBatchFixesTask(project, descriptions.toArray(ProblemDescriptor.EMPTY_ARRAY), progressTask, quickfixClass) :
                                             new PerformFixesTask(project, descriptions.toArray(ProblemDescriptor.EMPTY_ARRAY), progressTask, quickfixClass);
  CommandProcessor.getInstance().executeCommand(project, () -> {
    CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
    progressTask.setMinIterationTime(200);
    progressTask.setTask(fixesTask);
    ProgressManager.getInstance().run(progressTask);
  }, presentationText, null);
  return fixesTask;
}
 
Example #14
Source File: DocumentsSynchronizer.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void replaceString(@Nonnull final Document document, final int startOffset, final int endOffset, @Nonnull final String newText) {
  LOG.assertTrue(!myDuringModification);
  try {
    myDuringModification = true;
    CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
      @Override
      public void run() {
        LOG.assertTrue(endOffset <= document.getTextLength());
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
          @Override
          public void run() {
            document.replaceString(startOffset, endOffset, newText);
          }
        });
      }
    }, DiffBundle.message("save.merge.result.command.name"), document);
  }
  finally {
    myDuringModification = false;
  }
}
 
Example #15
Source File: VcsVFSListener.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected VcsVFSListener(@Nonnull Project project, @Nonnull AbstractVcs vcs) {
  myProject = project;
  myVcs = vcs;
  myChangeListManager = ChangeListManager.getInstance(project);
  myDirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);

  final MyVirtualFileListener myVFSListener = new MyVirtualFileListener();
  final MyCommandAdapter myCommandListener = new MyCommandAdapter();

  myVcsManager = ProjectLevelVcsManager.getInstance(project);
  myAddOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.ADD, vcs);
  myRemoveOption = myVcsManager.getStandardConfirmation(VcsConfiguration.StandardConfirmation.REMOVE, vcs);

  VirtualFileManager.getInstance().addVirtualFileListener(myVFSListener, this);
  CommandProcessor.getInstance().addCommandListener(myCommandListener, this);
  myVcsFileListenerContextHelper = VcsFileListenerContextHelper.getInstance(myProject);
}
 
Example #16
Source File: PlainTextEditor.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
public void replaceSelection(@Nonnull final String clipboardText) {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
          final SelectionModel model = Assertions.assertNotNull(getEditor()).getSelectionModel();
          final int start = model.getSelectionStart();
          final int end = model.getSelectionEnd();
          getDocument().replaceString(start, end, "");
          getDocument().insertString(start, clipboardText);
        }
      }, null, null, UndoConfirmationPolicy.DEFAULT, getDocument());
    }
  });
}
 
Example #17
Source File: ElementCreator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private Exception executeCommand(String commandName, ThrowableRunnable<Exception> invokeCreate) {
  final Exception[] exception = new Exception[1];
  CommandProcessor.getInstance().executeCommand(myProject, () -> {
    LocalHistoryAction action = LocalHistory.getInstance().startAction(commandName);
    try {
      invokeCreate.run();
    }
    catch (Exception ex) {
      exception[0] = ex;
    }
    finally {
      action.finish();
    }
  }, commandName, null, UndoConfirmationPolicy.REQUEST_CONFIRMATION);
  return exception[0];
}
 
Example #18
Source File: GeneratorDialog.java    From idea-gitignore with MIT License 6 votes vote down vote up
/**
 * Updates editor's content depending on the selected {@link TreePath}.
 *
 * @param path selected tree path
 */
private void updateDescriptionPanel(@NotNull TreePath path) {
    final TemplateTreeNode node = (TemplateTreeNode) path.getLastPathComponent();
    final Resources.Template template = node.getTemplate();

    ApplicationManager.getApplication().runWriteAction(
            () -> CommandProcessor.getInstance().runUndoTransparentAction(() -> {
                String content = template != null ?
                        StringUtil.notNullize(template.getContent()).replace('\r', '\0') : "";
                previewDocument.replaceString(0, previewDocument.getTextLength(), content);

                List<Pair<Integer, Integer>> pairs =
                        getFilterRanges(profileFilter.getTextEditor().getText(), content);
                highlightWords(pairs);
            })
    );
}
 
Example #19
Source File: BashFormatterTestCase.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
protected void checkFormatting(String expected) throws IOException {
    CommandProcessor.getInstance().executeCommand(myFixture.getProject(), new Runnable() {
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    try {
                        final PsiFile file = myFixture.getFile();
                        TextRange myTextRange = file.getTextRange();
                        CodeStyleManager.getInstance(file.getProject()).reformatText(file, myTextRange.getStartOffset(), myTextRange.getEndOffset());
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                }
            });
        }
    }, null, null);
    myFixture.checkResult(expected);
}
 
Example #20
Source File: PropertySuppressableInspectionBase.java    From eslint-plugin with MIT License 6 votes vote down vote up
protected void createSuppression(@NotNull Project project, @NotNull PsiElement element, @NotNull PsiElement container) throws IncorrectOperationException {
    if (element.isValid()) {
        PsiFile psiFile = element.getContainingFile();
        if (psiFile != null) {
            psiFile = psiFile.getOriginalFile();
        }

        if (psiFile != null && psiFile.isValid()) {
            final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document != null) {
                int lineNo = document.getLineNumber(element.getTextOffset());
                final int lineEndOffset = document.getLineEndOffset(lineNo);
                CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                    public void run() {
                        document.insertString(lineEndOffset, " //eslint-disable-line");
                    }
                }, null, null);
            }
        }
    }
}
 
Example #21
Source File: FormatterTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"UNUSED_SYMBOL"})
private void checkPsi(final PsiFile file, String textAfter) {
  CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          performFormatting(file);
        }
      });
    }
  }, "", "");


  String fileText = file.getText();
  assertEquals(textAfter, fileText);
}
 
Example #22
Source File: DeleteSingleImportAction.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e)
{
    final PsiFile psiFile = PsiFileUtil.getPsiFileInCurrentEditor(e.getProject());
    Editor editor = e.getData(PlatformDataKeys.EDITOR);

    if(editor == null)
    {
        return;
    }

    PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());

    final AMDImport amdImport = new NearestAMDImportLocator().findNearestImport(element, psiFile);

    if(amdImport == null)
    {
        Notifications.Bus.notify(new Notification("needsmoredojo", "Remove Import", "No valid literal/parameter pair found to delete", NotificationType.WARNING));
        return;
    }

    CommandProcessor.getInstance().executeCommand(psiFile.getProject(), new Runnable() {
        @Override
        public void run() {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            @Override
            public void run() {
                AMDPsiUtil.removeSingleImport(amdImport);
            }
        });
        }
    },
    "Remove Import",
    "Remove Import");
}
 
Example #23
Source File: YamlCreateServiceArgumentsCallbackTest.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void testYamlServiceArgumentCreation() {
    YAMLFile yamlFile = YAMLElementGenerator.getInstance(getProject()).createDummyYamlWithText("" +
        "services:\n" +
        "    foo:\n" +
        "        class: Foo\\Foo\n"
    );

    Collection<YAMLKeyValue> yamlKeyValues = PsiTreeUtil.collectElementsOfType(yamlFile, YAMLKeyValue.class);

    YAMLKeyValue services = ContainerUtil.find(yamlKeyValues, new YamlUpdateArgumentServicesCallbackTest.YAMLKeyValueCondition("foo"));
    assertNotNull(services);

    final YamlCreateServiceArgumentsCallback callback = new YamlCreateServiceArgumentsCallback(services);

    CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    callback.insert(Arrays.asList("foo", null, ""));
                }
            });

        }
    }, null, null);

    assertEquals("" +
                    "services:\n" +
                    "    foo:\n" +
                    "        class: Foo\\Foo\n" +
                    "        arguments:\n" +
                    "          ['@foo', '@?', '@?']\n",
            yamlFile.getText()
    );
}
 
Example #24
Source File: BaseHaxeGenerateHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
protected void doInvoke(final Project project,
                        final Editor editor,
                        final PsiFile file,
                        final Collection<HaxeNamedElementNode> selectedElements,
                        final BaseCreateMethodsFix createMethodsFix) {
  Runnable runnable = new Runnable() {
    public void run() {
      createMethodsFix.addElementsToProcessFrom(selectedElements);
      createMethodsFix.beforeInvoke(project, editor, file);

      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        public void run() {
          try {
            createMethodsFix.invoke(project, editor, file);
          }
          catch (IncorrectOperationException ex) {
            Logger.getInstance(getClass().getName()).error(ex);
          }
        }
      });
    }
  };

  if (CommandProcessor.getInstance().getCurrentCommand() == null) {
    CommandProcessor.getInstance().executeCommand(project, runnable, getClass().getName(), null);
  }
  else {
    runnable.run();
  }
}
 
Example #25
Source File: ContextImpl.java    From floobits-intellij with Apache License 2.0 5 votes vote down vote up
@Override
public void writeThread(final Runnable runnable) {
    final long l = System.currentTimeMillis();
    final ContextImpl context = this;
    mainThread(new Runnable() {
        @Override
        public void run() {
            CommandProcessor.getInstance().executeCommand(context.project, new Runnable() {
                @Override
                public void run() {
                    ApplicationManager.getApplication().runWriteAction(new Runnable() {
                        @Override
                        public void run() {
                            long time = System.currentTimeMillis() - l;
                            if (time > 200) {
                                Flog.log("spent %s getting lock", time);
                            }
                            try {
                                runnable.run();
                            } catch (Throwable throwable) {
                                API.uploadCrash(context, throwable);
                            }
                        }
                    });
                }
            }, "Floobits", null);
        }
    });
}
 
Example #26
Source File: IgnoreSettingsPanel.java    From idea-gitignore with MIT License 5 votes vote down vote up
/**
 * Sets new content to the editor component.
 *
 * @param content new content
 */
public void setContent(@NotNull final String content) {
    ApplicationManager.getApplication().runWriteAction(
            () -> CommandProcessor.getInstance().runUndoTransparentAction(
                    () -> previewDocument.replaceString(0, previewDocument.getTextLength(), content)
            )
    );
}
 
Example #27
Source File: AbstractInplaceIntroducer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean performRefactoring() {
  final String newName = getInputName();
  if (getLocalVariable() == null && myExpr == null ||
      newName == null ||
      getLocalVariable() != null && !getLocalVariable().isValid() ||
      myExpr != null && !myExpr.isValid()) {
    super.moveOffsetAfter(false);
    return false;
  }
  if (getLocalVariable() != null) {
    new WriteCommandAction(myProject, getCommandName(), getCommandName()) {
      @Override
      protected void run(Result result) throws Throwable {
        getLocalVariable().setName(myLocalName);
      }
    }.execute();
  }

  if (!isIdentifier(newName, myExpr != null ? myExpr.getLanguage() : getLocalVariable().getLanguage())) return false;
  CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
    @Override
    public void run() {
      performIntroduce();
    }
  }, getCommandName(), getCommandName());

  V variable = getVariable();
  if (variable != null) {
    saveSettings(variable);
  }
  return false;
}
 
Example #28
Source File: Action.java    From dummytext-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Insert or replace selection with random dummy text
 *
 * @param event ActionSystem event
 */
public void actionPerformed(final AnActionEvent event) {
    Project currentProject = event.getData(PlatformDataKeys.PROJECT);

    CommandProcessor.getInstance().executeCommand(currentProject, () -> ApplicationManager.getApplication().runWriteAction(() -> {
        String genreCode  = PluginPreferences.getGenreCode();
        new ActionPerformer(genreCode).write(event);
    }), StaticTexts.HISTORY_INSERT_DUMMY_TEXT, UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION);
}
 
Example #29
Source File: BuildifierAutoFormatter.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void initComponent() {
  mMessageBusConnection = ApplicationManager.getApplication().getMessageBus().connect(this);
  mMessageBusConnection.subscribe(
      FileEditorManagerListener.FILE_EDITOR_MANAGER,
      new FileEditorManagerListener() {
        @Override
        public void selectionChanged(@NotNull FileEditorManagerEvent event) {
          Project project = event.getManager().getProject();
          if (!BuckProjectSettingsProvider.getInstance(project).isAutoFormatOnBlur()) {
            return;
          }
          FileEditor newFileEditor = event.getNewEditor();
          FileEditor oldFileEditor = event.getOldEditor();
          if (oldFileEditor == null || oldFileEditor.equals(newFileEditor)) {
            return; // still editing same file
          }
          VirtualFile virtualFile = oldFileEditor.getFile();
          Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
          if (document == null) {
            return; // couldn't find document
          }
          PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
          if (!BuckFileType.INSTANCE.equals(psiFile.getFileType())) {
            return; // file type isn't a Buck file
          }
          Runnable runnable = () -> BuildifierUtil.doReformat(project, virtualFile);
          LOGGER.info("Autoformatting " + virtualFile.getPath());
          CommandProcessor.getInstance()
              .executeCommand(
                  project,
                  runnable,
                  null,
                  null,
                  UndoConfirmationPolicy.DO_NOT_REQUEST_CONFIRMATION,
                  document);
        }
      });
}
 
Example #30
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;
    }
  });
}